// 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 import java.text.*; public class Nderiv { Nderiv() { System.out.println("Nderiv"); int norder = 3; int npoints = 9; int order, points, term, jterm; int a[] = new int[50]; // coefficients of f(x0), f(x1), ... int b[] = new int[1] ; // use only b[0], output parameter System.out.println("compute formulas for numerical derivatives"); for(order=1; order<=norder; order++) { for(points=order+1; points<=npoints; points++) { for(term=0; termMath.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 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, k=0, term, b; int jorder, ipower, isum, iat, jterm, r; int debug = 0; if(npoints<=order) { System.out.println("ERROR in call to deriv, npoints < 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 double pow(double x, int pwr) { int i; double val = 1.0; for(i=0; i