// nderiv.java // compute formulas for numerical derivatives // order is order of derivative, 1 = first derivative, 2 = second // points is number of points where value of function is known // f(x0), f(x1), f(x2) ... f(x points-1) // term is the point where derivative is computed // f'(x0) = (1/bh)*( a(0)*f(x0) + a(1)*f(x1) // + ... + a(points-1)*f(x points-1) // algorithm: use divided differences to get polynomial p(x) that // approximates f(x). f(x)=p(x)+error term // f'(x) = p'(x) + error term' // substitute xj = x0 + j*h // substitute x = x0 to get p'(x0) etc public class nderiv // for function deriv { public nderiv() { // no initialization needed } public static int gcd(int a, int b) // needed by deriv { int a1, b1, q, r; if(a==0 || b==0) return 1; if(Math.abs(a)>Math.abs(b)) { a1 = Math.abs(a); b1 = Math.abs(b); } else { a1 = Math.abs(b); b1 = Math.abs(a); } r=1; while(r!=0) { q = a1 / b1; r = a1 - q * b1; a1 = b1; b1 = r; } return a1; } // end gcd public static void deriv(int order, int npoints, int point, int a[], int bb[]) { // compute the exact coefficients to numerically compute a derivative // of order 'order' using 'npoints' at ordinate point, // where order>=1, npoints>=order+1, 0 <= point < npoints, // 'a' array returned with numerator of coefficients, // 'bb' returned with denominator of h^order int h[]=new int[100]; // coefficients of h int x[]=new int[100]; // coefficients of x, variable for differentiating int numer[][]=new int[100][100]; // numerator of a term numer[term][pos] int denom[]=new int[100]; // denominator of coefficient int i, j, term, b; int k = 0; int jorder, ipower, isum, iat, jterm, r; int debug = 0; if(npoints<=order) { System.out.println("ERROR in call to deriv, npoints="+npoints+ " < order="+order+"+1"); return; } for(term=0; term0) for(i=0; i0) System.out.println(" "); b = 0; for(jterm=0; jtermb) b=denom[jterm]; // largest denominator } for(jterm=0; jterm0) System.out.println("f^("+order+")(x["+iat+"])=(1/"+b+"h^"+order+ ")("+a[jterm]+" f(x["+jterm+"]) +"); } // end computing terms of coefficients bb[0] = b; } // end deriv public static double pown(double x, int pwr) { int i; double val = 1.0; for(i=0; i3 && degree==npoints+1) m=3; // extra check on error for(k=0; k0 && degree3) h=h/2.0; // cumulative, for reasonable error if(order>4) h=h/2.0; if(order>5) h=h/2.0; pwr = degree; sum = 0.0; x = 1.0; // let x = 1.0, compute derivative using this x for(i=0; i