I already wrote the code to calculate the derivative of a single variable function at a point by making a class called "Der". In class Der
, I defined two private variables double f
and double df
and a print()
function to print the values of f
and df
. Inside the class, I overloaded the operators +, -, *, /, ^
to calculate the derivative of the sum, difference, multiplication etc of functions. I can't show the whole code because it's very long but I will show some snippets to give an idea.
class Der{
private:
double f; // function value at x
double df; // derivative of function at x
public:
Der();
Der(double);
Der operator+(Der); // f + g
Der operator-(Der); // f - g
Der operator*(Der); // f * g
Der operator/(Der); // f / g
friend Der operator+(double, Der); //c+f
friend Der operator-(double, Der); //c-f
friend Der operator*(double, Der); //c*f
friend Der operator/(double, Der); //c/f
Der operator^(double); // f^c, Where c is constant
friend Der sin(Der);
friend Der cos(Der);
friend Der tan(Der);
friend Der log(Der);
friend Der exp(Der);
void print();
};
Der :: Der(){}
Der :: Der(double x){
this->f = x;
this->df = 1;
}
Der Der :: operator+(Der g){
Der h;
h.f = this->f + g.f;
h.df = this->df + g.df;
return h;
}
Der sin(Der g){
Der h;
h.f = sin(g.f);
h.df = cos(g.f)*g.df;
return h;
}
void Der :: print(){
cout<<"Derivative of function at a point : "<<df<<endl;
}
int main()
{
Der x(10), f;
f = x^2+x^3;
f.print();
}
Now I want to use this derivative calculator to calculate the partial derivative of a several variable function and ultimately to calculate the gradient of that function. I have some vague ideas but I am not able to implement it in code. I am a beginner in C++ programming, so it would be helpful if you don't use too many advanced concepts.
Any kind of help would be highly appreciated. Thanks!
Edit: I have added how Der
is used. The program should take inputs of independent variables like x(2), y(4), z(5)
and function like f(x,y,z)=x^2*y*z+log(x*y*z)
. Then, it will give the partial derivative of f
w.r.t x, y, z
at point (2, 4, 5)
in the form of an array. But, I just need some idea on how to code the partial derivative calculator.