#include "library.h" double power2(const double sofar, const double apower, const int p) { if (p == 0) return sofar; if (p % 2 == 0) return power2(sofar, apower * apower, p / 2); else return power2(sofar * apower, apower * apower, p / 2); } double power2(const double x, const int p) { return power2(1.0, x, p); } double factorial(const int n) { if (n == 0) return 1.0; return n * factorial(n - 1); } int plus_or_minus(const int n) { return 2 - n % 4; } double sine2(const double sofar, const double x, const int p, const int maxp) { if (p > maxp) return sofar; return sine2(sofar + plus_or_minus(p) * power2(x, p) / factorial(p), x, p + 2, maxp); } double sine2(const double x, const double steps) { return sine2(0.0, x, 1, steps); } const int winw = 800, winh = 600; const double pi = acos(-1.0); const double maxx = 4 * pi; void plot(const int steps, const double x) { if (x > maxx) return; const double screenx = x / maxx * winw; const double screeny = (1 - sine2(x, steps) / 2) * winh / 2; if (x == 0) move_to(screenx, screeny); else draw_to(screenx, screeny); plot(steps, x + maxx / winw); } void plot_real(const double x) { if (x > maxx) return; const double screenx = x / maxx * winw; const double screeny = (1 - sin(x) / 2) * winh / 2; if (x == 0) move_to(screenx, screeny); else draw_to(screenx, screeny); plot_real(x + maxx / winw); } void show_error(const double x, const int steps) { cout << "error at " << x << " = " << fabs(sin(x) - sine2(x, steps)) << "\n"; } void test(const int steps) { set_pen_color(color::red); plot(steps, 0); cout << "maximum term " << steps << ", " << (steps + 1) / 2 << " computational steps\n"; show_error(pi / 4, steps); show_error(pi / 2, steps); show_error(pi, steps); show_error(2 * pi, steps); cout << "\n"; wait_for_key_typed(); set_pen_color(color::blue); plot(steps, 0); test(steps + 2); } void main() { make_window(winw, winh); set_pen_width(2); set_pen_color(color::green); plot_real(0); test(1); }