Advertisement
Guest User

Calculus

a guest
Oct 9th, 2012
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.08 KB | None | 0 0
  1. #define NDEPS (value)
  2. typedef double(*math_func)(double x);
  3. double nthDerivative(math_func f, double x, int N){
  4.     //perfectly fine derivative function
  5.     double derivative(math_func f, double x);
  6.     if(N<0) return NAN; //bogus value of N
  7.     if(N==0) return f(x);
  8.     if(N==1) return derivative(f,x);
  9.     double* vals=calloc(2*N+9,sizeof(double)); //buffer region around the real values
  10.     if(vals==NULL){ //oops! no memory
  11.         return NAN;
  12.     }
  13.     int i,j;
  14.     //don't take too small a finite difference
  15.     double h=max(sqrt(DBL_EPSILON)*x,NDEPS);
  16.     for(i=-(N+4);i<=N+4;i++){
  17.         vals[i+N+4]=derivative(f,x+h*i);
  18.     }
  19.     //for(i=0;i<2*N+9;i++){printf("%.1e ",vals[i]);}putchar('\n');
  20.     for(j=1;j<N;j++){
  21.         double *vals2=calloc(2*N+9,sizeof(double));
  22.         for(i=2;i<2*N+7;i++){
  23.             vals2[i]=(-vals[i+2]+8*vals[i+1]-8*vals[i-1]+vals[i-2])/(12*h);
  24.         }
  25.         free(vals);
  26.         vals=vals2;
  27.         //for(i=0;i<2*N+9;i++){printf("%.1e ",vals[i]);}putchar('\n');
  28.     }
  29.     double result=vals[N+4];
  30.     free(vals);
  31.     return result;
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement