// TaylorFit.java // // specific for e^x = 1 + x + x^2/2! + x^3/3! + x^4/4! + ... import java.awt.*; import java.awt.event.*; import java.text.*; class TaylorFit extends Frame { TaylorFit() { setTitle("TaylorFit(x) 0 to 2 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 texp(int n, double x) // Taylor polynomial evaluation for exp { double val; double fct=1.0; double coef[]=new double[n+1]; coef[0]=1.0; for(int i=1; i<=n; i++) { fct=fct*(double)i; coef[i]=1.0/fct; } val=coef[n]*x; for(int i=n-1; i>0; i--) { val=(coef[i]+val)*x; } val=val+coef[0]; return val; } 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 texp(x) final double xmin=0.0; final double xmax=2.0; double ymin=1.0; // for automatic scaling some day double ymax=7.0; double dx; // x step increment double xstart; // initial value double x; // stepped value xmin to xmax xstart=xmin; dx = (xmax-xmin)/(double)n; // do NOT use x=x+dx, very inaccurate! for(int i=0; i