import java.awt.Graphics; public class TaylorSeries extends java.applet.Applet { double sq(double x) { double y; y = x*x; return y; } double cu(double x) { double y; y = x*x*x; return y; } double my_power(double x, int exponent) { double y; int n; y = 1.0; if (exponent < 0) y = 0.0; // wrong if (exponent > 0 ) { for (n = 0; n < exponent; n++) { y = y*x; } } return y; } int my_factorial(int n) { int i; int f; f = 1; if (n <= 0) return 1; // wrong if (n == 1) return 1; if (n > 1) { for (i = 2; i <= n; i++) { f = f*i; } } return f; } double deriv_sin(int n) { if (n%4 == 0) return 0.0; if (n%4 == 1) return 1.0; if (n%4 == 2) return 0.0; if (n%4 == 3) return -1.0; return 0.0; // never happens } double taylor_sin(double x, int terms) { int n; double y; y = 0.0; if (terms <= 0) { // wrong return y; } if (terms == 1) { return y; } if (terms > 1) { for (n = 1; n <= terms; n++) { y = y + deriv_sin(n)*my_power(x, n)/(double)my_factorial(n); } } return y; } public void paint(Graphics g) { int x, x1, y, y1; double ax, ay, ax1, ay1; // draw axes g.drawLine(0, size().height/2, size().width - 1, size().height/2); g.drawLine(size().width/2, 0, size().width/2, size().height - 1); // draw functions for (x = 0 ; x < size().width ; x++) { // ax = actual x, ay = actual y (not in pixels) // I want ax to range from -2 to 2 ax = ((double)x - size().width/2)/(size().width/4); // ay = sq(ax); ay = taylor_sin(ax, 2); y = (int)(-ay*size().height/4 + size().height/2); ax1 = ((double)x + 1 - size().width/2)/(size().width/4); // ay1 = sq(ax1); ay1 = taylor_sin(ax1, 2); y1 = (int)(-ay1*size().height/4 + size().height/2); if (x >= 0 && y >= 0 && x < size().width && y < size().height) { g.drawLine(x, (int)y, x + 1, (int)y1); } // ay = cu(ax); ay = taylor_sin(ax, 4); y = (int)(-ay*size().height/4 + size().height/2); // ay1 = cu(ax1); ay1 = taylor_sin(ax1, 4); y1 = (int)(-ay1*size().height/4 + size().height/2); if (x >= 0 && y >= 0 && x < size().width && y < size().height) { g.drawLine(x, (int)y, x + 1, (int)y1); } } } public String getAppletInfo() { return "Draws Taylor approximations of sine."; } }