#include "library.h" const double pom[] = { 0.0, +1.0, 0.0, -1.0 }; /* This calculates the sine of x (radians) using the Taylor series only as far as the term in X to-the-power-of MaxN */ double sine(const double x, const int N, const int MaxN, const double xpn, const double fac) { if (N > MaxN) return 0.0; const double thisterm = pom[N%4] * xpn / fac; const double otherterms = sine(x, N+1, MaxN, xpn * x, fac * (N+1)); return thisterm + otherterms; } double sine(const double x, const int MaxN) { return sine(x, 1, MaxN, x, 1); } const double pi = acos(-1.0); /* This plots the Nth approximation to sine, for angles between 0 and just over 360 degrees */ void one_test_sine(const double x, const int N) { if (x > 8) return; if (x == 0.0) move_to(x*100, 400-sine(x, N)*200); else draw_to(x*100, 400-sine(x, N)*200); one_test_sine(x+0.005, N); } /* This does the same, but for the real library sine function */ void real_sine(const double x) { if (x > 8) return; if (x == 0.0) move_to(x*100, 400-sin(x)*200); else draw_to(x*100, 400-sin(x)*200); real_sine(x+0.002); } /* This plots all the sine approximations, one by one, in different colours ranging from red to blue via green */ void testsine(int N, int MaxN) { if (N <= MaxN) { set_pen_color_hls(N*0.7/MaxN, 0.5, 1); one_test_sine(0.0, N); testsine(N+2, MaxN); } } /* This plots the real sine in black, then all the approximations in various colours */ void main() { make_window(800, 600); set_pen_width(2); set_pen_color(color::black); real_sine(0.0); testsine(1, 51); }