有没有更好的方法在C中找到函数的n阶导数?

时间:2016-08-31 14:37:47

标签: c numerical-methods

我想写一个子程序来计算表格子程序给出的函数的n阶导数:

double func(double x)
{
    // a mathematical expression representing a smooth curve 
    //returns the value of the function at x      
}

我写了以下子程序:

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);
   }
}

有人可以提出更好的算法来找到第n个导数吗?

2 个答案:

答案 0 :(得分:0)

不计算数值不稳定性问题,这使得Delta的调整变得困难并且排除了高阶导数的使用(比如n > 3!),递归解决方案效率非常低,因为它需要{{ 1}}函数评估,其中2^n就足够了。

确实,你计算

n+1

当二项式公式告诉你

f' = f(+1) - f(-1)
f'' = f'(+1) - f'(-1) = f(+2) - f(0) - f(0) + f(-2)
f''' = f''(+1) - f''(-1) = f(+3) - f(+1) - f(+1) + f(-1) - f(+1) + f(-1) + f(-1) - f(-3)
...

答案 1 :(得分:0)

可以使用Cauchy's integral lemma计算第n个导数。

将路径上的积分转换为"标准积分" (见Line integral)。

然后您可以整合该表达式(例如与trapezoidal rule)。

如果你想计算高阶导数,这种方法很可能是稳定的。