我正在写一个小的微积分库供个人使用.它是标准的微积分工具 - 取一阶导数,n阶导数,黎曼和等.我遇到的一个问题是,n阶导数函数对某些h值(有限差分)返回明显的虚假结果.
代码在这里和下面:
typedef double(*math_func)(double x);
inline double max ( double a, double b ) { return a > b ? a : b; }
//Uses the five-point-stencil algorithm.
double derivative(math_func f,double x){
double h=max(sqrt(DBL_EPSILON)*x,1e-8);
return ((-f(x+2*h)+8*f(x+h)-8*f(x-h)+f(x-2*h))/(12*h));
}
#define NDEPS (value)
double nthDerivative(math_func f, double x, int N){
if(N<0) return NAN; //bogus value of N
if(N==0) return f(x);
if(N==1) return derivative(f,x);
double* vals=calloc(2*N+9,sizeof(double)); //buffer region around the real values
if(vals==NULL){ //oops! no memory
return NAN;
}
int i,j; …Run Code Online (Sandbox Code Playgroud)