#include "library.h" const int screen_size = 600; const double function_max = 20.0; // the window will be 600 x 600 // the window's pixel coordinates ranging from (0,0) to (600,600) // will represent complex numbers running from (-20-20i) to (20+20i) struct complex { double real, imag; }; complex make_complex(double r, double i) { complex c; c.real = r; c.imag = i; return c; } void print(complex c) { cout << "(" << c.real << "+" << c.imag << "i) "; } complex add(complex a, complex b) { complex c; c.real = a.real + b.real; c.imag = a.imag + b.imag; return c; } complex sub(complex a, complex b) { complex c; c.real = a.real - b.real; c.imag = a.imag - b.imag; return c; } complex mul(complex a, complex b) { complex c; c.real = a.real * b.real - a.imag * b.imag; c.imag = a.real * b.imag + a.imag * b.real; return c; } complex div(complex a, complex b) { complex c; double bottom = b.real * b.real + b.imag * b.imag; if (bottom==0.0) cout << "Error, division by zero!\n"; else { c.real = (a.real * b.real + a.imag * b.imag) / bottom; c.imag = (b.real * a.imag - a.real * b.imag) / bottom; } return c; } double size(complex a) { return sqrt(a.real*a.real + a.imag*a.imag); } void screen_pos_to_function(int scrx, int scry, double & x, double & y) { x = (scrx-screen_size/2.0)/(screen_size/2.0)*function_max; y = (screen_size/2.0-scry)/(screen_size/2.0)*function_max; } void function_to_screen_pos(double x, double y, int & scrx, int & scry) { scrx = (int)(x/function_max*(screen_size/2)+screen_size/2); scry = screen_size/2-(int)(y/function_max*(screen_size/2)); } complex get_complex() // wait for the user to click the mouse // then work out which complex number // the mouse-click position corresponds to. { wait_for_mouse_click(); int x = get_click_x(), y = get_click_y(); double r, i; screen_pos_to_function(x, y, r, i); return make_complex(r, i); } void main() { make_window(screen_size, screen_size); set_pen_color(color::grey); // draw in the axes so we can see where zero is move_to(0, screen_size/2); draw_to(screen_size, screen_size/2); move_to(screen_size/2, 0); draw_to(screen_size/2, screen_size); set_pen_color(color::black); while (true) { complex c = get_complex(); // let the user select a starting position, c print(c); cout << " size = " << size(c) << "\n"; int sx, sy; function_to_screen_pos(c.real, c.imag, sx, sy); move_to(sx, sy); complex v = make_complex(0, 0); for (int i=0 ; i<1000; i+=1) // repeat a thousand times the complex number // calculation v = v*v + c and see what happens { v = add(mul(v, v), c); function_to_screen_pos(v.real, v.imag, sx, sy); draw_to(sx, sy); } } }