Chapter 15 Functions and graphing Bjarne Stroustrup www.stroustrup.com/Programming.

Slides:



Advertisements
Similar presentations
Best fit line Graphs (scatter graphs) Looped Intro Presentation.
Advertisements

LINEAR Y=MX + B Part I A graph is not a function unless all the ____ values are different. It must pass the __________ Line Test. 1 2 y depends on x.
HyperText Markup Language (HTML) – Part 2 Laboratory of Intelligent Networks KUT Youn-Hee Han from
Square root of the Variance:
Chapter 17 vector and Free Store Bjarne Stroustrup
Chapter 16 Graphical User Interfaces
Chapter 12 A display model Bjarne Stroustrup
Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup
Chapter 8 Technicalities: Functions, etc. Bjarne Stroustrup
Chapter 13 Graphics classes Bjarne Stroustrup
Chapter 7 Completing a Program
Chapter 14 Graph class design Bjarne Stroustrup
Chapter 4 Computation Bjarne Stroustrup
Chapter 18 Vectors and Arrays
Chapter 9 Technicalities: Classes, etc. Bjarne Stroustrup
Computer Science Department Introduction To Computers and Programming Knowledge: Understand the concepts of computer, hardware, software and programming.
Chapter 5 introduces the often- used data structure of linked lists. This presentation shows how to implement the most common operations on linked lists.
CSC211 Data Structures Lecture 9 Linked Lists Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College.
Computer Science Department FTSM Algorithm Knowledge: Understand algorithm representation using flowchart and pseudocode Skill: Map problem to solution.
1 Structures. 2 Structure Basics A structure is a collection of data values, called data members, that form a single unit. Unlike arrays, the data members.
1 Structures. 2 Structure Basics A structure is a collection of data values, called data members, that form a single unit. Unlike arrays, the data members.
Object Oriented Programming with Java
How Science works: Graphs.
Chapters 12 and 13 A Display Model and Graphics Classes John Keyser’s Modifications of Slides by Bjarne Stroustrup
Graphing Linear Equations
MEL 4E.  Graphing data can make it easier to quickly see trends. There are different types of graphs which each show and compare data.
Chapter 15 Functions and graphing John Keyser’s Modification of Slides by Bjarne Stroustrup
Noadswood Science,  To understand the flow procedure when writing programs Thursday, January 15, 2015.
Computer Science Department
Chapter 16 Graphical User Interfaces John Keyser’s Modifications of Slides by Bjarne Stroustrup
Chapter 18 Vectors and Arrays John Keyser’s Modification of Slides by Bjarne Stroustrup
The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
Control Structure: Loop (Part 1) Knowledge: Understand the various concepts of loop control structure Skill: Be able to develop a program involving loop.
Introduction to Graphing Using MATLAB. Line Graphs  Useful for graphing functions  Useful for displaying data trends over time  Useful for showing.
Chapter 17 vector and Free Store John Keyser’s Modifications of Slides By Bjarne Stroustrup
Chapter 14 Graph class design John Keyser’s Modifications of Slides by Bjarne Stroustrup
Chapter 15 Functions and Graphing
Slideshow C4: Drawing graphs. Features of a good bar chart The bars should be drawn accurately with a pencil and ruler. They should be of equal width.
Slideshow P4: Drawing a line graph. Features of a good line graph A 'line of best fit' can sometimes be drawn to show the pattern of the plotted points.
Introduction Many relationships can be represented by linear equations. Linear equations in two variables can be written in the form y = mx + b, where.
Copyright (c) Bani K. Mallick1 STAT 651 Lecture #18.
Introduction Earlier we studied the circle, which is the set of all points in a plane that are equidistant from a given point in that plane. We have investigated.
Graphs in Science Chapter 1, Section 5 Page 34.
Mathcad Variable Names A string of characters (including numbers and some “special” characters (e.g. #, %, _, and a few more) Cannot start with a number.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 14 Graphics class design Hartmut Kaiser
Chapter 5 Review: Plotting Introduction to MATLAB 7 Engineering 161.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 12 A display model Hartmut Kaiser
Programming for Artists ART 315 Dr. J. R. Parker Art/Digital Media Lab Lec 10 Fall 2010.
Chapter 13 Graphics classes Bjarne Stroustrup
Honors Physics Lab Journals Graphing. Lab Journal Entries  Number pages in consecutive order  Date all entries  Title all activities and investigations.
CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 12: A Display Model 1 Based on slides created by Bjarne.
Histograms Lecture 14 Sec Tue, Sep 26, 2006.
Chapter 15 Functions and graphing Bjarne Stroustrup
CSCE 121: Introduction to Program Design and Concepts, Honors J. Michael Moore Spring 2015 Set 14: Plotting Functions and Data 1.
Area of a circle Radius r (m) Area A (m 2 ) when r = 2.5 A = 20 (to 2sf) when A = 30 r = 3.1 (to 2sf)
Graphing Data. Graphs All graphs must have title and labeled axis Labels let you know what information is shown.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 12 A display model Hartmut Kaiser
Histograms Lecture 14 Sec Fri, Feb 8, 2008.
Aim: How do we construct a line graph? Do Now: 1.How many inches of rain fell during the month of June? 2.During which month did the most rain fall?
Histograms Lecture 18 Sec Tue, Feb 17, 2004.
Graphing Steps, Types, & Relationships. Steps  Draw axes on graph paper with ruler.  Label axes with quantity and unit.  Determine range of x & y quantities.Scale.
Histograms Lecture 14 Sec Wed, Sep 29, 2004.
The Normal Model Chapter 6 Density Curves and Normal Distributions.
9/19/16 HOW to make a graph Objective: I will construct a graph from a data table and include all of the required parts of a graph. PAGE 11.
11.2 Graphical Techniques Syed Arshad Mushtaq.
Graphing Rules: According to DRTAILSS
Introduction Solving a linear inequality in two variables is similar to graphing a linear equation, with a few extra steps that will be explained on the.
Histograms Lecture 14 Sec Fri, Feb 8, 2008.
Numerical and Graphical Analysis in Physical Science
GRAPHING.
Presentation transcript:

Chapter 15 Functions and graphing Bjarne Stroustrup

Abstract Here we present ways of graphing functions and data and some of the programming techniques needed to do so, notably scaling. Here we present ways of graphing functions and data and some of the programming techniques needed to do so, notably scaling. Stroustrup/Programming2

Note This course is about programming This course is about programming The examples – such as graphics – are simply examples of The examples – such as graphics – are simply examples of Useful programming techniques Useful programming techniques Useful tools for constructing real programs Useful tools for constructing real programs Look for the way the examples are constructed Look for the way the examples are constructed How are big problems broken down into little ones and solved separately? How are big problems broken down into little ones and solved separately? How are classes defined and used How are classes defined and used Do they have sensible data members? Do they have sensible data members? Do they have useful member functions? Do they have useful member functions? Use of variables Use of variables Are there too few? Are there too few? Too many? Too many? How would you have named them better? How would you have named them better? Stroustrup/Programming3

Graphing functions Start with something really simple Start with something really simple Always remember Hello, World! Always remember Hello, World! We graph functions of one argument yielding a one value We graph functions of one argument yielding a one value Plot (x, f(x)) for values of x in some range [r1,r2) Plot (x, f(x)) for values of x in some range [r1,r2) Lets graph three simple functions Lets graph three simple functions double one(double x) { return 1; } // y==1 double slope(double x) { return x/2; }// y==x/2 double square(double x) { return x*x; } // y==x*x Stroustrup/Programming4

Functions double one(double x) { return 1; } // y==1 double slope(double x) { return x/2; }// y==x/2 double square(double x) { return x*x; } // y==x*x Stroustrup/Programming5

How do we write code to do this? Simple_window win0(Point(100,100),xmax,ymax,"Function graphing"); Function s(one,-10,11,orig,n_points,x_scale,y_scale); 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(s2);win0.attach(s3); win0.wait_for_button( ); Stroustrup/Programming6 Function to be graphed Range in which to graph stuff to make the graph fit into the window

We need some Constants const int xmax = 600;// window size const int ymax = 400; const int x_orig = xmax/2; const int y_orig = ymax/2; const Point orig(x_orig, y_orig); // position of (0,0) in window const int r_min = -10;// range [-10:11) == [-10:10] of x const int r_max = 11; const int n_points = 400;// number of points used in range const int x_scale = 20;// scaling factors const int y_scale = 20; // Choosing a center (0,0), scales, and number of points can be fiddly // The range usually comes from the definition of what you are doing Stroustrup/Programming7

Functions – but what does it mean? Whats wrong with this? Whats wrong with this? No axes (no scale) No axes (no scale) No labels No labels Stroustrup/Programming8

Label the functions 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/Programming9

Add x-axis and y-axis We can use axes to show (0,0) and the scale 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/Programming10

Use color (in moderation) s.set_color(Color::green); x.set_color(Color::red); y.set_color(Color::red); ts.set_color(Color::green); Stroustrup/Programming11

The implementation of Function We need a type for the argument specifying the function to graph We need a type for the argument specifying the function to graph typedef can be used to declare a new name for a type typedef can be used to declare a new name for a type typedef int Color;// now Color means int typedef int Color;// now Color means int Define the type of our desired argument, Fct Define the type of our desired argument, Fct typedef double Fct(double);// now Fct means function // taking a double argument // and returning a double typedef double Fct(double);// now Fct means function // taking a double argument // and returning a double Examples of functions of type Fct: Examples of functions of type Fct: double one(double x) { return 1; } // y==1 double slope(double x) { return x/2; }// y==x/2 double square(double x) { return x*x; } // y==x*x Stroustrup/Programming12

Now Define Function struct Function : Shape // Function is derived from Shape { // all it needs is a constructor: Function( Fct f,// f is a Fct (takes a double, returns a double) double r1, // the range of x values (arguments to f) [r1:r2) double r2, Point orig,// the screen location of (0,0) int count,// number of points used to draw the function // (number of line segments used is count-1) double xscale, // the location (x,f(x)) is (xscale*x,yscale*f(x)) double yscale ); }; }; Stroustrup/Programming13

Implementation of Function Function::Function( Fct f, double r1, double r2,// 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/Programming14

Default arguments Seven arguments are too many! Seven arguments are too many! Many too many Many too many Were just asking for confusion and errors Were just asking for confusion and errors Provide defaults for some (trailing) arguments Provide defaults for some (trailing) arguments Default arguments are often useful for constructors Default arguments are often useful for constructors struct Function : Shape { Function( Fct f, double r1, double r2, Point xy, int count = 100, double xscale = 25, double yscale=25 ); }; Function f1(sqrt, 0, 11, orig, 100, 25, 25 );// ok (obviously) Function f2(sqrt, 0, 11, orig, 100, 25);// ok: exactly the same as f1 Function f3(sqrt, 0, 11, orig, 100);// ok: exactly the same as f1 Function f4(sqrt, 0, 11, orig);// ok: exactly the same as f1 Stroustrup/Programming15

Function Is Function a pretty class? Is Function a pretty class? No No Why not? Why not? What could you do with all of those position and scaling arguments? What could you do with all of those position and scaling arguments? See for one minor idea See for one minor idea If you cant do something genuinely clever, do something simple, so that the user can do anything needed If you cant do something genuinely clever, do something simple, so that the user can do anything needed Such as adding parameters so that the caller can control Such as adding parameters so that the caller can control Stroustrup/Programming16

Some more functions #include // standard mathematical functions // You can combine functions (e.g., by addition): 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/Programming17

Cos and sloping-cos Stroustrup/Programming18

Standard mathematical functions ( ) double abs(double);// absolute value double abs(double);// absolute value double ceil(double d);// smallest integer >= d double ceil(double d);// smallest integer >= d double floor(double d);// largest integer <= d double floor(double d);// largest integer <= d double sqrt(double d);// d must be non-negative double sqrt(double d);// d must be non-negative double cos(double); double cos(double); double sin(double); double sin(double); double tan(double); double tan(double); double acos(double);// result is non-negative; a for arc double acos(double);// result is non-negative; a for arc double asin(double);// result nearest to 0 returned double asin(double);// result nearest to 0 returned double atan(double); double atan(double); double sinh(double);// h for hyperbolic double sinh(double);// h for hyperbolic double cosh(double); double cosh(double); double tanh(double); double tanh(double); Stroustrup/Programming19

Standard mathematical functions ( ) double exp(double);// base e double exp(double);// base e double log(double d);// natural logarithm (base e) ; d must be positive double log(double d);// natural logarithm (base e) ; d must be positive double log10(double);// base 10 logarithm double log10(double);// base 10 logarithm double pow(double x, double y);// x to the power of y double pow(double x, double y);// x to the power of y double pow(double x, int y);// x to the power of y double pow(double x, int y);// x to the power of y double atan2(double x, double y);// atan(x/y) double atan2(double x, double y);// atan(x/y) double fmod(double d, double m);// floating-point remainder // same sign as d%m double fmod(double d, double m);// floating-point remainder // same sign as d%m double ldexp(double d, int i);// d*pow(2,i) double ldexp(double d, int i);// d*pow(2,i) Stroustrup/Programming20

Why graphing? Because you can see things in a graph that are not obvious from a set of numbers Because you can see things in a graph that are not obvious from a set of numbers How would you understand a sine curve if you couldnt (ever) see one? How would you understand a sine curve if you couldnt (ever) see one? Visualization is Visualization is key to understanding in many fields key to understanding in many fields Used in most research and business areas Used in most research and business areas Science, medicine, business, telecommunications, control of large systems Science, medicine, business, telecommunications, control of large systems Stroustrup/Programming21

An example: e x e x == 1 + x + x + x 2 /2! + x 3 /3! + x 4 /4! + x 5 /5! + x 6 /6! + x 7 /7! + … Where ! Means factorial (e.g. 4!==4*3*2*1) Stroustrup/Programming22

Simple algorithm to approximate e x double fac(int n) { /* … */ }// factorial double term(double x, int n) // x n /n! { return pow(x,n)/fac(n); } double expe(double x, int n)// sum of n terms of x { double sum = 0; for (int i = 0; i<n; ++i) sum+=term(x,i); return sum; } Stroustrup/Programming23

Simple algorithm to approximate e x But we can only graph functions of one argument, so how can we get graph expe(x,n) for various n ? But we can only graph functions of one argument, so how can we get graph expe(x,n) for various n ? int expN_number_of_terms = 6;// nasty sneaky argument to expN double expN(double x) // sum of expN_number_of_terms terms of x { return expe(x,expN_number_of_terms); } Stroustrup/Programming24

Animate approximations to e x Simple_window win(Point(100,100),xmax,ymax,""); // the real exponential : 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/Programming25

Animate approximations to e x for (int n = 0; n<50; ++n) { ostringstream ss; ss << "exp approximation; n==" << n ; win.set_label(ss.str().c_str()); expN_number_of_terms = n;// nasty sneaky argument to expN // next approximation: Function e(expN,r_min,r_max,orig,200,x_scale,y_scale); win.attach(e); wait_for_button();// give the user time to look win.detach(e);} Stroustrup/Programming26

Demo The following screenshots are of the successive approximations of exp(x) using expe(x,n) The following screenshots are of the successive approximations of exp(x) using expe(x,n) Stroustrup/Programming27

Demo n = 0 Stroustrup/Programming28

Demo n = 1 Stroustrup/Programming29

Demo n = 2 Stroustrup/Programming30

Demo n = 3 Stroustrup/Programming31

Demo n = 4 Stroustrup/Programming32

Demo n = 5 Stroustrup/Programming33

Demo n = 6 Stroustrup/Programming34

Demo n = 7 Stroustrup/Programming35

Demo n = 8 Stroustrup/Programming36

Demo n = 18 Stroustrup/Programming37

Demo n = 19 Stroustrup/Programming38

Demo n = 20 Stroustrup/Programming39

Demo n = 21 Stroustrup/Programming40

Demo n = 22 Stroustrup/Programming41

Demo n = 23 Stroustrup/Programming42

Demo n = 30 Stroustrup/Programming43

Why did the graph go wild? Floating-point numbers are an approximations of real numbers Floating-point numbers are an approximations of real numbers Just approximations Just approximations Real numbers can be arbitrarily large and arbitrarily small Real numbers can be arbitrarily large and arbitrarily small Floating-point numbers are of a fixed size Floating-point numbers are of a fixed size Sometimes the approximation is not good enough for what you do Sometimes the approximation is not good enough for what you do Here, small inaccuracies (rounding errors) built up into huge errors Here, small inaccuracies (rounding errors) built up into huge errors Always Always be suspicious about calculations be suspicious about calculations check your results check your results hope that your errors are obvious hope that your errors are obvious You want your code to break early – before anyone else gets to use it You want your code to break early – before anyone else gets to use it Stroustrup/Programming44

Graphing data Often, what we want to graph is data, not a well-defined mathematical function Often, what we want to graph is data, not a well-defined mathematical function Here, we used three Open_polylines Here, we used three Open_polylines Stroustrup/Programming45

Graphing data Carefully design your screen layout Carefully design your screen layout Stroustrup/Programming46

Code for Axis struct Axis : Shape { enum Orientation { x, y, z }; Axis(Orientation d, Point xy, int length, int number_of_notches=0,// default: no notches string label = ""// default : no label ); 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 // line stored in Shape // orientation not stored (can be deduced from line) Text label; Lines notches; }; Stroustrup/Programming47

Axis::Axis(Orientation d, Point xy, int length, int n, string lab) :label(Point(0,0),lab){ if (length<0) error("bad axis length"); switch (d){ case Axis::x: {Shape::add(xy);// axis line begin Shape::add(Point(xy.x+length,xy.y));// axis line end 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 break;} // … } Stroustrup/Programming48

Axis implementation void Axis::draw_lines() const { Shape::draw_lines();// the line notches.draw_lines();// the notches may have a different color from the line label.draw(); // the label may have a different color from the line } void Axis::move(int dx, int dy) { Shape::move(dx,dy);// the line notches.move(dx,dy);label.move(dx,dy);} void Axis::set_color(Color c) { // … the obvious three lines … } Stroustrup/Programming49

Next Lecture Graphical user interfaces Graphical user interfaces Windows and Widgets Windows and Widgets Buttons and dialog boxes Buttons and dialog boxes Stroustrup/Programming50