Chapter 15 - Chapter 15 Chapter Functions and graphing...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Chapter 15 Chapter Functions and graphing Bjarne Stroustrup Bjarne www.stroustrup.com/Programming www.stroustrup.com/Programming Abstract Abstract Here we present ways of graphing functions Here and data and some of the programming techniques needed to do so, notably scaling. Stroustrup/Programming Stroustrup/Programming 2 Note Note This course is about programming The examples – such as graphics – are simply examples of Look for the way the examples are constructed Look How are “big problems” broken down into little ones and How solved separately? solved How are classes defined and used Useful programming techniques Useful tools for constructing real programs Do they have sensible data members? Do Do they have useful member functions? Use of variables Are there too few? Too many? How would you have named them better? Stroustrup/Programming 3 Graphing functions Graphing Start with something really simple We graph functions of one argument yielding a one value Always remember “Hello, World!” Plot (x, f(x)) for values of x in some range [r1,r2) Let’s graph three simple functions double one(double x) { return 1; } double double slope(double x) { return x/2; } double double square(double x) { return x*x; } double Stroustrup/Programming // y==1 // y==x/2 // y==x/2 // y==x*x y==x*x 4 Functions Functions double one(double x) { return 1; } double double slope(double x) { return x/2; } double square(double x) { return x*x; } double Stroustrup/Programming // y==1 y==1 // y==x/2 // y==x/2 // y==x*x y==x*x 5 How do we write code to do this? How Function to be graphed Simple_window win0(Point(100,100),xmax,ymax,"Function graphing"); Function s(one,-10,11,orig,n_points,x_scale,y_scale); Function Function s2(slope,-10,11,orig,n_points,x_scale,y_scale); Function s3(square,-10,11,orig,n_points,x_scale,y_scale); win0.attach(s); win0.attach(s); win0.attach(s2); win0.attach(s3); Range in which to graph win0.wait_for_button( ); “stuff” to make the graph fit into the window Stroustrup/Programming 6 We need some Constants We const int xmax = 600; const int ymax = 400; // window size // window const int x_orig = xmax/2; const const int y_orig = ymax/2; const const Point orig(x_orig, y_orig); // position of (0,0) in window const position const int r_min = -10; const int r_max = 11; // range [-10:11) == [-10:10] of x // range const int n_points = 400; // number of points used in range // number const int x_scale = 20; const int y_scale = 20; // scaling factors // scaling // Choosing a center (0,0), scales, and number of points can be fiddly // Choosing // The range usually comes from the definition of what you are doing // The Stroustrup/Programming 7 Functions – but what does it mean? Functions What’s wrong with this? No axes (no scale) No labels Stroustrup/Programming 8 Label the functions Label Text ts(Point(100,y_orig-30),"one"); Text ts2(Point(100,y_orig+y_orig/2-10),"x/2"); Text ts3(Point(x_orig-90,20),"x*x"); Stroustrup/Programming 9 Add x-axis and y-axis Add We can use axes to show (0,0) and the scale Axis x(Axis::x, Point(20,y_orig), xlength/x_scale, "one notch == 1 "); Axis y(Axis::y, Point(x_orig, ylength+20, ylength/y_scale, "one notch == 1"); Stroustrup/Programming 10 Use color (in moderation) Use s.set_color(Color::green); s.set_color(Color::green); y.set_color(Color::red); y.set_color(Color::red); x.set_color(Color::red); x.set_color(Color::red); ts.set_color(Color::green); ts.set_color(Color::green); Stroustrup/Programming 11 The implementation of Function The We need a type for the argument specifying the function We to graph to typedef can be used to declare a new name for a type typedef can // now color means int // now Define the type of our desired argument, Fct Define Fct typedef int color; typedef double Fct(double); // now Fct means function // now // taking a double argument // and returning a double Examples of functions of type Fct: Examples Fct double one(double x) { return 1; } double double slope(double x) { return x/2; } double square(double x) { return x*x; } double Stroustrup/Programming // y==1 y==1 // y==x/2 // y==x/2 // y==x*x y==x*x 12 Now Define “Function” Now struct Function : Shape // Function is derived from Shape struct Function { // all it needs is a constructor: // all Function( Fct f, // f is a Fct (takes a double, returns a double) // is double r1, double double r2, Point orig, int count, // the range of x values (arguments to f) [r1:r2) the double xscale , double double yscale // the location (x,f(x)) is (xscale*x,yscale*f(x)) // the // the screen location of (0,0) // the // number of points used to draw the function // number // (number of line segments used is count-1) // (number ); }; }; Stroustrup/Programming 13 Implementation of Function Implementation Function::Function( Fct f, double r1, double r2, // range // range Point xy, int count, double xscale, double yscale ) { if (r2-r1<=0) error("bad graphing range"); if (count <=0) error("non-positive graphing count"); double dist = (r2-r1)/count; double r = r1; for (int i = 0; i<count; ++i) { add(Point(xy.x+int(r*xscale), xy.y-int(f(r)*yscale))); r += dist; } } Stroustrup/Programming 14 Default arguments Default Seven arguments are too many! Many too many We’re just asking for confusion and errors Provide defaults for some (trailing) arguments Default arguments are often useful for constructors struct Function : Shape { Function( Fct f, double r1, double r2, Point xy, Point int count = 100, double xscale = 25, double yscale=25 ); double }; Function f1(sqrt, -10, 11, Point(0,0), 100, 25, 25 ); Function f2(sqrt, -10, 11, Point(0,0), 100, 25); Function f3(sqrt, -10, 11, Point(0,0), 100); Function f4(sqrt, -10, 11, Point(0,0)); Stroustrup/Programming // ok (obviously) // ok // ok: exactly the same as f1 // ok: // ok: exactly the same as f1 // ok: // ok: exactly the same as f1 // ok: 15 Function Function Is Function a “pretty class”? Is Function No What could you do with all of those position and scaling What arguments? arguments? Why not? See 15.6.3 for one minor idea If you can’t do something genuinely clever, do something If simple, so that the user can do anything needed simple, Such as adding parameters so that the caller can control Stroustrup/Programming 16 Some more functions Some #include<cmath> // standard mathematical functions // standard // You can combine functions (e.g., by addition): // You double sloping_cos(double x) { return cos(x)+slope(x); } Function s4(cos,-10,11,orig,400,20,20); s4.set_color(Color::blue); Function s5(sloping_cos,-10,11,orig,400,20,20); Stroustrup/Programming 17 Cos and sloping-cos Cos Stroustrup/Programming 18 Standard mathematical functions (<cmath>) (<cmath>) double abs(double); // absolute value // absolute double ceil(double d); double floor(double d); // smallest integer >= d // smallest // largest integer <= d // largest double sqrt(double d); // d must be non-negative // must double cos(double); double sin(double); double tan(double); double acos(double); double asin(double); double atan(double); double sinh(double); double cosh(double); double tanh(double); // result is non-negative; “a” for “arc” // result // result nearest to 0 returned // result // “h” for “hyperbolic” // “h” Stroustrup/Programming 19 Standard mathematical functions (<cmath>) (<cmath>) double exp(double); double log(double d); positive positive double log10(double); // base e // base // natural logarithm (base e) ; d must be // natural e) // base 10 logarithm // base double pow(double x, double y); double pow(double x, int y); double atan2(double x, double y); double fmod(double d, double m); double ldexp(double d, int i); // x to the power of y // to // x to the power of y // to // atan(x/y) // atan(x/y) // floating-point remainder // // same sign as d%m same // d*pow(2,i) // d*pow(2,i) Stroustrup/Programming 20 Why graphing? Why Because you can see things in a graph that are not obvious from Because a set of numbers set How would you understand a sine curve if you couldn’t (ever) see one? How Visualization is key to understanding in many fields Used in most research and business areas Science, medicine, business, telecommunications, control of large systems Stroustrup/Programming 21 An example: e x ex == 1 +x + x2/2! + x3/3! + x4/4! + x5/5! + x6/6! + x7/7! /7! +… Where ! Means factorial (e.g. 4!==4*3*2*1) Stroustrup/Programming 22 Simple algorithm to approximate ex Simple double fac(int n) { /* … */ } double // factorial // factorial double term(double x, int n) double { return pow(x,n)/fac(n); } // xn/n! double expe(double x, int n) // sum of n terms of x // sum { double sum = 0; for (int i = 0; i<n; ++i) sum+=term(x,i); return sum; } Stroustrup/Programming 23 Simple algorithm to approximate ex Simple But we can only graph functions of one arguments, so how can we But get graph expr(x,n) for various n? expr(x,n) int expN_number_of_terms = 6; // nasty sneaky argument to expN // nasty double expN(double x) // sum of expN_number_of_terms terms of x double sum { return expe(x,expN_number_of_terms); } Stroustrup/Programming 24 “Animate” approximations to ex Simple_window win(Point(100,100),xmax,ymax,""); // the real exponential : // the Function real_exp(exp,r_min,r_max,orig,200,x_scale,y_scale); real_exp.set_color(Color::blue); win.attach(real_exp); const int xlength = xmax-40; const int ylength = ymax-40; Axis x(Axis::x, Point(20,y_orig), xlength, xlength/x_scale, "one notch == 1"); Axis y(Axis::y, Point(x_orig,ylength+20), ylength, ylength/y_scale, "one notch == 1"); win.attach(x); win.attach(y); x.set_color(Color::red); y.set_color(Color::red); Stroustrup/Programming 25 “Animate” approximations to ex for (int n = 0; n<50; ++n) { ostringstream ss; ss << "exp approximation; n==" << n ; win.set_label(ss.str().c_str()); exp_number_of_terms = n; // nasty sneaky argument to expN // nasty // next approximation: // next Function e(expN,r_min,r_max,orig,200,x_scale,y_scale); Function win.attach(e); win.attach(e); wait_for_button(); win.detach(e); // give the user time to look // give } Stroustrup/Programming 26 Demo Demo The following screenshots are of the successive The approximations of exp(x) using expe(x,n) expe(x,n) Stroustrup/Programming 27 Demo n = 0 Demo Stroustrup/Programming 28 Demo n = 1 Demo Stroustrup/Programming 29 Demo n = 2 Demo Stroustrup/Programming 30 Demo n = 3 Demo Stroustrup/Programming 31 Demo n = 4 Demo Stroustrup/Programming 32 Demo n = 5 Demo Stroustrup/Programming 33 Demo n = 6 Demo Stroustrup/Programming 34 Demo n = 7 Demo Stroustrup/Programming 35 Demo n = 8 Demo Stroustrup/Programming 36 Demo n = 18 Demo Stroustrup/Programming 37 Demo n = 19 Demo Stroustrup/Programming 38 Demo n = 20 Demo Stroustrup/Programming 39 Demo n = 21 Demo Stroustrup/Programming 40 Demo n = 22 Demo Stroustrup/Programming 41 Demo n = 23 Demo Stroustrup/Programming 42 Demo n = 30 Demo Stroustrup/Programming 43 Why did the graph “go wild”? Why Floating-point numbers are an approximations of real numbers Just approximations Real numbers can be arbitrarily large and arbitrarily small Floating-point numbers are of a fixed size Sometimes the approximation is not good enough for what you do Here, small inaccuracies (rounding errors) built up into huge errors Always be suspicious about calculations check your results hope that your errors are obvious You want your code to break early – before anyone else gets to use it Stroustrup/Programming 44 Graphing data Graphing Often, what we want to graph is data, not a well-defined Often, mathematical function mathematical Here, we used three Open_polylines Here, Open_polyline Stroustrup/Programming 45 Graphing data Graphing Carefully design your screen layout Stroustrup/Programming 46 Code for Axis Code struct Axis : Shape { enum Orientation { x, y, z }; Axis(Orientation d, Point xy, int length, int number_of_notches=0, // default: no notches // default: string label = "" // default : no label // default ); void draw_lines() const; void move(int dx, int dy); void set_color(Color); // in case we want to change the color of all parts at once // in // line stored in Shape // line // orientation not stored (can be deduced from line) Text label; Lines notches; }; Stroustrup/Programming 47 Axis::Axis(Orientation d, Point xy, int length, int n, string lab) Axis::Axis(Orientation :label(Point(0,0),lab) { if (length<0) error("bad axis length"); switch (d){ case Axis::x: { Shape::add(xy); // axis line begin // axis Shape::add(Point(xy.x+length,xy.y)); // axis line end // axis if (1<n) { int dist = length/n; int x = xy.x+dist; for (int i = 0; i<n; ++i) { notches.add(Point(x,xy.y),Point(x,xy.y-5)); x += dist; } } label.move(length/3,xy.y+20); // put label under the line label.move(length/3,xy.y+20); put break; } // … } Stroustrup/Programming 48 Axis implementation Axis void Axis::draw_lines() const { Shape::draw_lines(); // the line // the notches.draw_lines(); // the notches may have a difference color from the line // the label.draw(); // the label may have a different color from the line label.draw(); the } void Axis::move(int dx, int dy) { Shape::move(dx,dy); // the line // the notches.move(dx,dy); label.move(dx,dy); } void Axis::set_color(Color c) { // … the obvious three lines … // the } Stroustrup/Programming 49 Next Lecture Next Graphical user interfaces Windows and Widgets Buttons and dialog boxes Stroustrup/Programming 50 ...
View Full Document

This note was uploaded on 02/18/2012 for the course CSCE 121 taught by Professor Walter daugherity during the Fall '09 term at Texas A&M.

Ask a homework question - tutors are online