// LegendreFit.java // // approximate f(x) ~ a0*g0 + a1*g1*P1(x) + a2*gn*P2(x) + ... // ai = int -1 to 1 f(x)*Pi(x) dx // gi = (2i+1)/2 package myjava; import java.awt.*; import java.awt.event.*; import java.text.*; class LegendreFit extends Frame { LegendreFit() { setTitle("LegendreFit(x) -1 to 1 of e^x"); setSize(450,500); setBackground(Color.white); setForeground(Color.black); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); setVisible(true); } double f(double x) // "exact" function e^x { return Math.exp(x); } double P(int i, double x) // Legendre polynomial evaluation { if(i<=0) return 1.0; else if(i==1) return x; else return x*((double)(2*i-1)/i)*P(i-1,x)-((double)(i-1)/i)*P(i-2,x); } double Pchk(int i, double x) // check recursive definition { switch(i) { case 0: return 1.0; case 1: return x; case 2: return -0.5+1.5*x*x; case 3: return -1.5*x+2.5*x*x*x; case 4: return 0.375-3.75*x*x+4.375*x*x*x*x; case 5: return 1.875*x-8.75*x*x*x+7.875*x*x*x*x*x; case 6: return -0.3125+6.5625*x*x-19.6875*x*x*x*x+14.4375*x*x*x*x*x*x; default : return 0.0; } } public void paint(Graphics g) { // set up function to be approximated final int n=100; // number of samples for plotting final double nf=(double)n; double fx[] = new double[n]; // f(x) double ax[] = new double[n]; // approximation(x) final double xmin=-1.0; final double xmax=1.0; double ymin=0.0; // for automatic scaling some day double ymax=3.0; double dx; // x step increment double xstart; // initial value double x; // stepped value xmin to xmax if(n%2==0) // even, center samples, not end points or center { dx=(xmax-xmin)/nf; xstart=xmin+dx/2.0; } else // odd, end points are samples, center point in center { dx=(xmax-xmin)/(double)(n-1); xstart=xmin; } // do NOT use x=x+dx, very inaccurate! for(int i=0; i