/* legendre_fit.c */ /* fit f(x) = a_0 g0 P0(x) + a_1 g1 P1(x) + ... a_n gn Pn(x) */ /* where Pi(x) as P(i,x) is a Legendre polynomial */ /* the weight function is 1.0 */ /* the integral range is -1 to 1 */ /* a_i = integral -1 to 1 of f(x) Pi(x) dx */ /* gi = (2*i+1)/2 */ /* test on e^x = 1 + x + 1/2 x^2 + 1/6 x^3 + 1/24 x^4 + 1/120 x^5 */ /* (just using Pi(x) does not work. (2i+1)/2 could be the weight) */ /* using Phi(i,x) = sqrt((2i+1)/2) P(i,x) for integration and */ /* evaluation works also. */ /* first few Legendre polynomials: */ /* P(0,x) = 1.0 */ /* P(1,x) = x */ /* P(2,x) = 1/2 (3x^2 - 1) */ /* P(3,x) = 1/2 (5x^3-3.0*x) */ /* P(4,x) = 1/8 (35x^4-30x^2+3) */ #include #include #undef max #define max(a,b) ((a)>(b)?(a):(b)) #undef abs #define abs(a) ((a)<0.0?(-(a)):(a)) static double P(int i, double x); static double Phi(int i, double x); int main(int argc, char * argv[]) { double a[10]; double exact[10]; int n = 4; int nn = 2048; /* for trapezoid integration */ int m = 10; /* for check */ double err, maxerr, rmserr; double xmin = -1.0; double xmax = 1.0; double h, hh, x, val; int i, j; printf("legendre_fit.c running \n"); printf("fit f(x) = a_0 g0 P0(x) + a_1 g1 P1(x) + ... a_n gn Pn(x) \n"); printf("where Pi(x) as P(i,x) is a Legendre polynomial \n"); printf("the weight function is 1.0 \n"); printf("the integral range is -1 to 1 \n"); printf("a_i = integral -1 to 1 of f(x) Pi(x) dx \n"); printf("gi = (2*i+1)/2 \n"); printf("test on e^x = 1 + x + 1/2 x^2 + 1/6 x^3 + 1/24 x^4 + 1/120 x^5 \n"); printf("using Phi(i,x) = sqrt((2i+1)/2 P(i,x) both places works also \n"); printf("\n"); exact[0] = 1.0; for(i=1; i<10; i++) { exact[i] = exact[i-1]/(double)i; } h = (xmax-xmin)/(double)nn; hh = (double)nn; printf("using P0 thru P4, trapezoidal nn=%d \n", nn); for(i=0; i<=n; i++) { a[i] = exp(xmin)*P(i,xmin)/2.0; /* trapezoidal */ a[i] = a[i]+exp(xmax)*P(i,xmax)/2.0; for(j=1; j