// Calculating sines by approximating the sum of the infinite series, // and comparing the quality of the different levels of approximation. #include "library.h" #include // is needed for access to setprecision() double factorial(const int n) { double f = 1; int i = 1; while (i <= n) { f = f * i; i = i + 1; } return f; } double power(const double x, const int n) { double p = 1; int i = 1; while (i <= n) { p = p * x; i = i + 1; } return p; } double sineterm(const double x, const int n) { double r = power(x, n)/factorial(n); if (n % 4 == 1) return r; else return - r; } double sine(const double x, const int last_term) { double sum = 0; int i = 1; while (i <= last_term) { sum = sum + sineterm(x, i); i = i + 2; } return sum; } void exmain() { while (true) { const double x = read_double(); const int n = read_int(); cout << setprecision(17) << sine(x, n) << " " << setprecision(17) << sin(x) << "\n"; } } void plot(const double start, const double end, const int which) // which = 0 means use the standard sin function // any other value says which level of approximation { if (end - start < 0.01) { const double x0 = start * 100, x1 = end * 100; double y0, y1; if (which == 0) { y0 = sin(start); y1 = sin(end); } else { y0 = sine(start, which); y1 = sine(end, which); } y0 = y0 * 124 + 250, y1 = y1 * 124 + 250; move_to(x0, 500 - y0); draw_to(x1, 500 - y1); } else { const double middle = (start+end)/2; plot(start, middle, which); plot(middle, end, which); } } void main() { make_window(629, 500); set_pen_width(3); set_pen_color(color::red); plot(0.0, 6.29, 0); // This shows the official library sine function in red set_pen_width(2); set_pen_color(color::blue); int approx = 1; while (approx <= 15) // now the first 8 approximations in blue { plot(0.0, 6.29, approx); approx = approx + 2; } set_pen_width(1); // and the original in thin red again so we can see set_pen_color(color::red); // where it was plot(0.0, 6.29, 0); }