有没有更好的方法在 C 中找到函数的 n 阶导数?
Is there any better way to find nth derivative of a function in C?
我想编写一个子程序来计算由以下形式的子程序给出的函数的 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 阶导数的算法?
不考虑数值不稳定问题,这使得 Delta
的调整变得困难并且排除了对高阶导数的使用(例如 n > 3
!),递归解决方案效率很低,因为它需要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)
...
当二项式公式告诉您时
f' = f(+1) - f(-1)
f'' = f(+2) - 2f(0) + f(-2)
f''' = f(+3) - 3f(+1) + 3f(-1) - f(-3)
...
可以使用 Cauchy's integral lemma.
计算第 n 个导数
将路径上的积分转换为 "standard integral"(参见 Line integral)。
然后您可以整合该表达式(例如 trapezoidal rule)。
如果你想计算高阶导数,这种方法很可能是稳定的。
我想编写一个子程序来计算由以下形式的子程序给出的函数的 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 阶导数的算法?
不考虑数值不稳定问题,这使得 Delta
的调整变得困难并且排除了对高阶导数的使用(例如 n > 3
!),递归解决方案效率很低,因为它需要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)
...
当二项式公式告诉您时
f' = f(+1) - f(-1)
f'' = f(+2) - 2f(0) + f(-2)
f''' = f(+3) - 3f(+1) + 3f(-1) - f(-3)
...
可以使用 Cauchy's integral lemma.
计算第 n 个导数将路径上的积分转换为 "standard integral"(参见 Line integral)。
然后您可以整合该表达式(例如 trapezoidal rule)。
如果你想计算高阶导数,这种方法很可能是稳定的。