I want to write a subroutine that calculates the nth derivative of a function given by the subroutine of the form:
double func(double x)
{
// a mathematical expression representing a smooth curve
//returns the value of the function at x
}
i wrote the following subroutine:
double nthderive(double (*f)(double),double x0,int n)
{
const double delta=1.0e-8;
double x1=x0 - delta;
double x2=x0 + delta;
if(n==0) {
return f(x0);
}
else {
return (nthderive(f,x2,n-1)-nthderive(f,x1,n-1))/(2*delta);
}
}
Can someone suggest a better algorithm for finding the nth derivative?
The nth derivative can be computed using Cauchy's integral lemma.
Transform the integral over the path into a "standard integral" (see Line integral).
Then you can integrate that expression (e.g. with trapezoidal rule).
If you want to calculate high order derivatives this method will most likely be stable.