Вы находитесь на странице: 1из 25

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) = x2 –
w
• Requirement:
− Need to be able to evaluate f
− f must be continuous
− We must be given points xL and xR such that f(xL)
and f(xR) are not both positive or both negative
Bisection Method For Finding Roots
• Because of continuity, there must
be a root between xL and xR (both
inclusive)
• Let xM = (xL + xR)/2 = midpoint of
interval (xL, xR) xL
• If f(xM) has same sign as f(xL), xM xR
then f(xM), f(xR) have different
signs
So we can set xL = xM and
repeat
• Similarly if f(xM) has same sign as
f(xR)
• In each iteration, xL, xR are
coming closer.
• When they come closer than
certain epsilon, we can declare xL
as the root
Bisection Method For Finding Square
Root of 2
• Same as finding the root of
x2 - 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 x0 for the root is available
• Example: To find square root of y
use f(x) = x2 - y. f'(x) = 2x
f(x), f'(x) can be calculated easily. 2,3 arithmetic ops
• Initial guess x0 = 1 is good enough!
How To Get Better xi+1 Given xi
Point A =(xi,0) known

Calculate f(xi )
B Point B=(xi,f(xi))
Draw the tangent to f(x)
C= intercept on x axis
C=(xi+1,0)
C A f'(xi) = derivative
xi+1 xi = (d f(x))/dx at xi
f(x) ≈ AB/AC

xi+1= xi – AC = xi - AB/(AB/AC) = xi- f(xi) / f'(xi)


Square root of y

xi+1 = xi- f(xi) / f'(xi)


f(x) = x2 - y, f'(x) = 2x
xi+1 = xi - (xi2 - y)/(2xi) = (xi + y/xi)/2

Starting with x0=1, we compute x1, then x2, …


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 |xi*xi – 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?
Write a program that prints the GCD main_program{
of 36, 24, and of 99, 47 int m=36, n=24;
Using what you already know: while(m % n != 0){
Make 2 copies of code to find int r = m%n;
GCD. Use the first copy to find m = n;
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
− function name
n = r;
− how it is to be called }
− what it computes return n;
− what it returns }
• Main program:
calls or invokes functions main_program{
− gcd(a,b) : call/invocation int a=36,b=24, c=47;
− 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
main_program{ Activation frame of gcd

int a=36,b=24;
cout << gcd(a,b) << endl; copy values of a and b
into m and n
store n in a
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
Contract View of Functions (contd.)

• Function = contract between the programmer who wrote


the function, and other programmers who use it
• Programmer who uses the function trusts the function
writer
• Programmer who wrote the function does not care which
program uses it
• Analogous to giving cloth to tailor. Tailor promises to
give you a shirt if the cloth is good. Tailor does not care
who wears the shirt, wearer does not care how it was
stitched

Вам также может понравиться