// ChebyshevFit.java // // approximate f(x) ~ a0 + a1*T1(x) + a2*T2(x) + ... // ai = 2/pi * int -1 to 1 f(x)*Ti(x)/sqrt(1-x^2) dx // a0 = a0/2 import java.awt.*; import java.awt.event.*; import java.text.*; class ChebyshevFit extends Frame { ChebyshevFit() { setTitle("ChebyshevFit(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 T(int i, double x) // Chebyshev polynomial evaluation { if(i<=0) return 1.0; if(i==1) return x; return 2.0*x*T(i-1,x)-T(i-2,x); } public void paint(Graphics g) { final double pi=Math.PI; // set up function to be approximated final int n=100; // number of samples final double nf=(double)n; double fx[] = new double[n]; // f(x) double ax[] = new double[n]; // approximation(x) double bx[] = new double[n]; // alternate 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 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