Bisection Method For Finding Roots • Root of function f: Value x such that f(x)=0 • Many problems can be expressed as finding roots, e.g. square root of w is the same as root of f(x) = x 2 – w • Requirement: − Need to be able to evaluate f − f must be continuous − We must be given points x L and x R such that f(x L ) and f(x R ) are not both positive or both negative
Bisection Method For Finding Roots • Because of continuity, there must be a root between x L and x R (both inclusive) • Let x M = (x L + x R )/2 = midpoint of interval (x L , x R ) x L • If f(x M ) has same sign as f(x L ), x M x R then f(x M ), f(x R ) have different signs So we can set x L = x M and repeat • Similarly if f(x M ) has same sign as f(x R ) • In each iteration, x L , x R are coming closer. • When they come closer than certain epsilon, we can declare x L as the root
Bisection Method For Finding Square Root of 2 • Same as finding the root of x 2 - 2 = 0 • Need to support both scenarios: − xL is negative, xR is positive − xL is positive, xR is negative • We have to check if xM has the same sign as xL or xR
Newton Raphson method • Method to find the root of f(x), i.e. x s.t. f(x)=0 • Method works if: f(x) and derivative f'(x) can be easily calculated A good initial guess x 0 for the root is available • Example: To find square root of y use f(x) = x 2 - y. f'(x) = 2x f(x), f'(x) can be calculated easily. 2,3 arithmetic ops • Initial guess x 0 = 1 is good enough!
How To Get Better x i+1 Given x i Point A =(x i ,0) known Calculate f(x i ) B Point B=(x i ,f(x i )) Draw the tangent to f(x) C= intercept on x axis C=(x i+1 ,0) f'(x i ) = derivative C A = (d f(x))/dx at x i x i+1 x i ≈ AB/AC f(x) x i+1 = x i – AC = x i - AB/(AB/AC) = x i - f(x i ) / f'(x i )
Square root of y x i+1 = x i - f(x i ) / f'(x i ) f(x) = x 2 - y, f'(x) = 2x x i+1 = x i - (x i2 - y)/(2x i ) = (x i + y/x i )/2 Starting with x 0 =1, we compute x 1 , then x 2 , … We can get as close to sqrt(y) as required Proof not part of the course.
Computing √y Using the Newton Raphson Method float y; cin >> y; float xi=1; // Initial guess. Known to work repeat(10){ // Repeating a fixed number of times xi = (xi + y/xi)/2; } cout << xi;
Make |x i *x i – y| Small float y; cin >> y; float xi=1; while(abs(xi*xi – y) > 0.001){ xi = (xi + y/xi)/2 ; } cout << xi;
CS 101: Computer Programming and Utilization
Can We Define New Commands? • We already have many commands, e.g − sqrt(x) evaluates to the square root of x − forward(d) moves the turtle forward d pixels • Can we define new commands? e.g − gcd(m,n) should evaluate to the GCD of m,n − dash(d) should move the turtle forward, but draw dashes as it moves rather than a continuous line • Function : official name for command
Why Functions? main_program{ Write a program that prints the GCD of 36, 24, and of 99, 47 int m=36, n=24; while(m % n != 0){ Using what you already know: int r = m%n; Make 2 copies of code to find m = n; GCD. Use the first copy to find the GCD of 36, 24 Use the n = r; second copy to find the GCD of } 99, 47 cout << n << endl; Duplicating code is not good m=99; n=47; May make mistakes in copying. while(m % n != 0){ What if we need the GCD at 10 int r = m%n; places in the program? m = n; This is inelegant. Ideally, you n = r; should not have to state anything } more than once cout << n << endl; }
Using a Function (exactly how it works, later) • A complete program int gcd(int m, int n){ = function definitions while(m % n != 0){ + main program int r = m%n; • Function definition: m = n; information about n = r; − function name } − how it is to be called return n; − what it computes } − what it returns • Main program: main_program{ calls or invokes functions int a=36,b=24, c=47; − gcd(a,b) : call/invocation − gcd(99,c) : another call cout <<gcd(a,b) << endl; − Values supplied for each cout <<gcd(99,c)<< endl; call: arguments or } parameters to the call
Form of Function Definitions return-type name-of-function ( parameter1-type parameter1-name, parameter2-type parameter2-name, …) { function-body } • return-type: the type of the value returned by the function, e.g. int Some functions may not return anything (discussed later) • name-of-function: e.g. gcd • parameter: variables that to hold the values of the arguments to the function. m,n in gcd • function-body: code that will get executed
Function Execution int gcd(int m, int n) { • Each function has a while(m % n != 0){ separate data space int r = m%n; (independent scope) m = n; • These data spaces are n = r; arranged in a data } structure called stack return n; • Imagine the data spaces } as data books and stacked main_program{ up one on the other int a=36,b=24; • The book on the top of the cout << gcd(a,b) << endl; stack is the one we can cout << gcd(99,47)<< endl; access } Last-In-First-Out (LIFO)
Function Execution int gcd(int m, int n) { • Data space of a function is while(m % n != 0){ also called an activation int r = m%n; frame (or activation m = n; record) n = r; } return n; copy n back m = 36, n=24 } Activation frame of gcd main_program{ int a=36,b=24; cout << gcd(a,b) << endl; copy values of a and b store n in a into m and n return value cout << gcd(99,47)<< endl; a=36, b =24 area } Activation frame of main
Function Execution int gcd(int m, int n) { • Activation frame: area in while(m % n != 0){ memory where function int r = m%n; variables are stored m = n; n = r; } return n; } main_program{ int a=36,b=24; gcd activation frame is destroyed cout << gcd(a,b) << endl; cout << gcd(99,47)<< endl; a=36, b =24 returned value of n } Activation frame of main
How A Function Executes 1. main_program executes and reaches gcd(36,24) 2. main_program suspends 3. Preparations made to run subprogram gcd: • Area allocated in memory where gcd will have its variables. activation frame • Variables corresponding to parameters are created in activation frame • Values of arguments are copied from activation frame of main_program to that of gcd. This is termed passing arguments by value 4. Execution of function-body starts
(contd.) • Execution of the called function ends when return statement is encountered • Value following the keyword return is copied back to the calling program, to be used in place of the expression gcd(…,…) • Activation frame of function is destroyed, i.e. memory reserved for it is taken back • main_program resumes execution
Remarks • Set of variables in calling program e.g. main_program is completely disjoint from the set in called function, e.g. gcd • Both may contain same name. Calling program will reference the variables in its activation frame, and called program in its activation frame • New variables can be created in called function • Arguments to calls/invocations can be expressions, which are first evaluated before called function executes • Functions can be called while executing functions • A declaration of function must appear before its call
Function To Compute LCM We can compute the least common multiple of two numbers m, n using the identity LCM(m,n) = m*n/GCD(m,n) int lcm(int m, int n){ return m*n/gcd(m,n); } lcm calls gcd.
Program To Find LCM Using Functions gcd, lcm Function definitions appear Function declarations before their calls appear before their calls int gcd(int m, int n) int lcm(int m, int n); { …} main_program{ int lcm(int m, int n) cout << lcm(50,75); { } return m*n/gcd(m,n); int gcd(int m, int n) } { …} main_program{ int lcm(int m, int n) cout << lcm(50,75); { } return m*n/gcd(m,n); }
Execution • main_program starts executing • main_program suspends when the call lcm(..) is encountered • Activation frame created for lcm • lcm starts executing after 50, 75 copied to m,n call to gcd encountered. lcm suspends • Activation frame created for gcd • Execution of gcd starts after copying arguments 50, 75 to m,n of gcd. • gcd executes. Will returns 25 as result • Result copied into activation frame of lcm, to replace call to gcd • Activation frame of gcd destroyed • lcm continues execution using result. m*n/gcd(m,n) = 50*75/25 = 150 computed • 150 returned to main_program, to replace call to lcm • Activation frame of gcd destroyed • main_program resumes and prints 15
A Function to Draw Dashes void dash(int d){ while(d>10){ forward(10); penUp(); d -= 10; if(d<10) break; forward(10); penDown(); d -= 10; } forward(d); penDown(); return; } main_program{ turtleSim(); repeat(4){dash(100); right(90);} }
Contract View Of Functions • Function : piece of code which takes the responsibility of getting something done • Specification : what the function is supposed to do Typical form: If the arguments satisfy certain properties, then a certain value will be returned, or a certain action will happen certain properties = preconditions • Example: gcd : If positive integers are given as arguments, then their GCD will be returned • If preconditions are not satisfied, nothing is promised
Recommend
More recommend