Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

Lab.

Sheet 440
Finding Root of Equation Using
Bisection Method

Part 1

Course examiner: Dr. Shijun Zhao


shijzhao@cityu.edu.hk

1
Department of Mechanical Engineering City University of Hong Kong
2

“roots” problem
gm  gc 
-1=x2-2x v(t ) = tanh t
c  
 m 

Define: Define:
 gc 
f(x)=x2-2x+1 f (m ) =
gm
c
tanh

t  - v(t)

 m 

Let: Let:
f(x)=0 f(m)=0

We have: We have:
gm  gc 
f(x)=x2-2x+1=0 f (m ) = tanh t  - v(t) = 0
c  
 m 

X=1
m=?
Department of Mechanical Engineering Bisection method: MATLAB of
City University can helpKong
Hong you
3

Problem Statement
• A parachutist jumps out of a stationary
hot air balloon. The air resistance force
on the parachutist is assuming to be
proportional to the square of the velocity
of the parachutist:
Fair resistance = cv 2
Eq 5
c is the drag coefficient,
v is the velocity of the falling parachutist
Fair resistance is the air resistance force

Department of Mechanical Engineering City University of Hong Kong


4

Problem Statement (cont’)


• The falling velocity of the parachutist can be
predicted using the following formula:
gm  gc 
v (t ) = tanh t Eq 6
c  m 
• Suppose the drag coefficient c = 0.25kg/m, g =
9.81 m/s2 and we want to find the mass of the
parachutist which will make v = 36m/s after
falling for time t=4s. In order to solve this
problem, we need to reformulate Eq 6 into a
“roots” problem as shown in Eq 7:
gm  gc 
f(m) = tanh  t  - v(t) = 0 Eq 7
c  m 
Department of Mechanical Engineering City University of Hong Kong
5

Preliminary: Bisection Method


f(m)
gm  gc 
f (m ) = tanh t  - v(t) = 0
c  
 m 

fu

fr

xr xu mass
xl
xr2
fl

Department of Mechanical Engineering City University of Hong Kong


6

Problem Statement (cont’)


i. Develop a MATLAB program to plot the above
equation (Eq 7) with the x axis between 50kg and
200kg, and step size 50kg.
ii. Based on the graph generated by (i), estimate the root
for Eq 7 (that is when the equation crosses the x axis)
and also determine the upper and lower bounds for
the Bisection method.
iii. Develop a MATLAB program to implement Bisection
Method and use the program to find the root for Eq 7
with the upper and lower bounds obtained in (ii) and
the stopping criterion εs = 0.5%
iv. Compare and comment the value of root obtained in (ii)
and (iii)

Department of Mechanical Engineering City University of Hong Kong


7

Problem Statement (cont’)


• Notes:
– Students are encouraged to develop more generic
MATLAB programs which can be reused for other
functions or applications
– A good user interface, which allows users to enter
parameters or even functions to the MATLAB
program, can be a good means to develop more
generic program.
– MATLAB commands such as ‘input’, ‘menu’, ‘inputdlg’
and ‘feval’ can be used to develop such user interface
– More advanced MATLAB users can also try
MATLAB’s GUIDE (Graphical User Interface
Development Environment) to create Microsoft
Windows-like interface.

Department of Mechanical Engineering City University of Hong Kong


8

Preliminary: Bisection Method


f(m)
gm  gc 
f (m ) = tanh t  - v(t) = 0
c  
 m 

fu

fr

xr xu mass
xl
xr2
fl

Department of Mechanical Engineering City University of Hong Kong


9

Bisection Method
The initial guesses could be obtained from a plot of the function
or from an incremental search method
• A simple algorithm for the bisection calculation:
– Step 1: choose lower xL and upper xU guesses for the root
that the function changes sign over the interval, i.e.
f(xL)f(xU)<0
– Step 2: An estimate of the root xr is determined by
x +x
xr = L U Eq 5.6 Assuming the root is in the middle of the interval
2
– Step 3: Make the following evaluation to determine in which
Check
whether
subinterval the root lies:
the a. If f(xL)f(xr)<0, the root lies in the lower subinterval. Therefore,
assumption set xU=xr and return to step 2
in step 2 is b. If f(xL)f(xr)>0, the root lies in the upper subinterval. Therefore,
true set xL=xr and return to step 2
c. If f(xL)f(xr)=0, the root equals xr; terminate the computation
Step 3c is not a good criterion for many practical applications!

Department of Mechanical Engineering City University of Hong Kong


10

Bisection Method (cont’)


• Define the stopping criterion for the approximate
percent relative error (recall Eq 3.3)
present approximat ion - previous approximat ion
a =  100% Eq 3.3
present approximat ion

x rnew − x rold
a = new
 100% Eq 5.7 and  a   s
xr
 a is the approximat e percent relative error
x rnew is the estimated root for the current iteration
x rold is the estimated root for the previous iteration
and  s is the stopping criterion
This method is more suitable for practical applications

Department of Mechanical Engineering City University of Hong Kong


11

Bisection Algorithm –Pseudo Code


function Bisectroot=findroot(xL, xU, es, imax)
% es: stopping criterion fr=f(xr)
% ea: approximate percent relative error fL=f(xL)
% imax: the maximum number of iteration test = fL * fr
iter = 0 IF test < 0
xr=xL % give an initial value to xr xU = xr
fL = f(xL) % f( ) is the function for evaluation ELSE IF test > 0
fU=f(xU) % xL = xr
IF fL*fU>0, output error, RETURN, END ELSE
ea = 0
DO END IF
xr_old = xr IF ea < es OR iter >= imax break end
xr = (xL + xU)/2
iter = iter +1 END DO
IF xr ≠ 0 THEN
ea =ABS((xr – xr_old)/xr)*100
Bisectroot = xr %This is the root
END IF
END Bisect

This is only a pseudo code and not a real MATLAB


Department of Mechanical Engineering
program!!!
City University of Hong Kong
12

MATLAB – Passing Functions to M-Files


• There are many occasions when you would like a function
to perform calculations using an arbitrary function.
• The built-in feval function can be used to accomplish this
task
– The feval function provides an alternative means to evaluate a
function.
– It has the syntax:
outvar = feval (fname, arg1, arg2, …)
e.g outvar=feval(‘cos’, pi/6) will generate the following output in
MATLAB:
>> outvar=feval('cos', pi/6)
Run the function: cos(pi/6)
outvar =
0.8660
– The above example is equivalent to merely writing:
outvar = cos(pi/6)

Department of Mechanical Engineering City University of Hong Kong


13

Example
function root = MyUnfinishSearch (func, xl, xu, es) %%%----start of while loop---%%%
% This is only a dummy search program xrold = xr;
% func = name of function xr = (xl + xu)/2;
x −x 
% xl, xu = lower and upper guesses % if xr ~=0, calculate ea: εa = abs r rold   100
% es = stopping criterion in percentage  xr 
% <insert your program here>
% ‘~=‘ is the operator for Not-Equal in MATLAB
fl= feval(func,xl); %fl=function(xl), the function name fl = feval(func,xl);
%is from variable input ‘func’, fr = feval(func,xr);
% for example: ’cos’,’sin’,’fm’,etc % check fl*fr >0, <0 or =0 and calculate xu and xl for
fu = feval(func, xu); %fu=function(xu) the next iteration
<insert your program here>
if fl*fu >0
error(‘Not bracketing the root') % if ea <= es, break from while loop
return % If there is no sign change,
end %error so exit the function %%% end of while loop---%%%

xr = xl; %To initialize xr to the value of xl root = xr; % Return the final xr as the best estimate of
% this is for calculating the ea for the first iteration the root

% end of function MyUnfinishSearch

Department of Mechanical Engineering City University of Hong Kong


14

Example (cont’)
y=x
function y = myfunc(x)
% a simple function
% you can replace the following function
% with you own

y = x;

In MATLAB, you can execute the function as following:


>> r=mysearch('myfunc',-2,2,0.5) >> r=mysearch('myfunc',1,2,0.5)
r= ??? Error using ==> mysearch
Not bracketing the root
0

The xl and xu must bracket the root. Otherwise, error will happen.

Department of Mechanical Engineering City University of Hong Kong


15

Convert the Pseudo Code into a MATLAB program


for performing Bisection Algorithm

• You can use the


1

following simple
function to test
0.5

your program:

cos(x)
➢y= cos(x); x is angle
0

in radian
➢y=0 when
-0.5
x =1.570796327 0 0.2 0.4 0.6 0.8 1 1.2
x - angle in radian
1.4 1.6 1.8 2

➢Set xL=1.4 and xU


=1.6
Department of Mechanical Engineering City University of Hong Kong
16

Learning Outcomes
After this lecture, the student would be able to
understand the following:
– The details of the coursework
– How functions can be passed to a M-file in
MATLAB
• outvar = feval (fname, arg1, arg2, …)

– Find the root by Matlab program

Department of Mechanical Engineering City University of Hong Kong


17

User interface

Department of Mechanical Engineering City University of Hong Kong


18

Appendix

Department of Mechanical Engineering City University of Hong Kong


19

Useful Commands
.* Array multiply.
X.*Y denotes element-by-element multiplication. X and Y
must have the same dimensions unless one is a scalar.
A scalar can be multiplied into anything.

./ Right array divide.


A./B denotes element-by-element division. A and B
must have the same dimensions unless one is a scalar.
A scalar can be divided with anything.

SQRT Square root.


sqrt(X) is the square root of the elements of X. Complex
results are produced if X is not positive.

Department of Mechanical Engineering City University of Hong Kong


20

Useful Commands (cont’)


TANH Hyperbolic tangent.
tanh(X) is the hyperbolic tangent of the elements of X.

== Equal.
A == B does element by element comparisons between A and B
and returns a matrix of the same size with elements set to logical 1
where the relation is true and elements set to logical 0 where it is
not. A and B must have the same dimensions unless one is a
scalar. A scalar can be compared with any size array.
~= Not equal.
A ~= B does element by element comparisons between A and B
and returns a matrix of the same size with elements set to logical 1
where the relation is true and elements set to logical 0 where it is
not. A and B must have the same dimensions unless one is a
scalar. A scalar can be compared with any size array.

Department of Mechanical Engineering City University of Hong Kong


21

Useful Commands (cont’)


< Less than.
A < B does element by element comparisons between A and B
and returns a matrix of the same size with elements set to logical 1
where the relation is true and elements set to logical 0 where it is
not. A and B must have the same dimensions unless one is a
scalar. A scalar can be compared with any size array.

> Greater than.


A > B does element by element comparisons between A and B
and returns a matrix of the same size with elements set to logical 1
where the relation is true and elements set to logical 0 where it is
not. A and B must have the same dimensions unless one is a
scalar. A scalar can be compared with any size array.

Department of Mechanical Engineering City University of Hong Kong


22

Useful Commands (cont’)


IF Conditionally execute statements. Example
The general form of the IF statement is if I == J
A(I,J) = 2;
if expression elseif abs(I-J) == 1
statements
A(I,J) = -1;
elseif expression
statements else
else A(I,J) = 0;
statements end
end

The statements are executed if the real part of the expression


has all non-zero elements. The ELSE and ELSEIF parts are optional.
Zero or more ELSEIF parts can be used as well as nested IF's.
The expression is usually of the form expr rop expr where
rop is ==, <, >, <=, >=, or ~=.

Department of Mechanical Engineering City University of Hong Kong


23

Useful Commands (cont’)


WHILE Repeat statements an indefinite number of times.
The general form of a WHILE statement is:

while expression
statements
end

The statements are executed while the real part of the expression
has all non-zero elements. The expression is usually the result of
expr rop expr where rop is ==, <, >, <=, >=, or ~=.

The break statement can be used to terminate the loop prematurely.


For example:
n=0;
x=0;
while n<16
if x>5, break, end
n=n+1
x=x+1
end
Department of Mechanical Engineering City University of Hong Kong
24

MATLAB – Another Way to Passing


Functions to M-Files
– The inline function provides a way to create a one-line function
that does not have to be stored in a separate M-file.
– It has the syntax:
funcname = inline (expression,arg1, arg2,...)

e.g.
>> fx = inline ('cos(x)*sin(x)')

fx =

Inline function:
fx(x) = cos(x)*sin(x)
feval(inline('cos(x)*sin(x)'), pi/6)
>> fx(pi/6)

ans =
cos(pi/6)*sin(pi/6)
0.4330

Department of Mechanical Engineering City University of Hong Kong


25

Example of function inline


y=x
function y = myfunc(x)
% a simple function
% you can replace the following function
% with you own

y = x;

In MATLAB, you can execute the function as following:


>> r=mysearch(inline('x'),-2,2,0.5) >> r=mysearch(inline('x'),1,2,0.5)
??? Error using ==> mysearch
r=
The given range is not bracketing the root
0
The xl and xu must bracket the root. Otherwise, error will happen.

feval(inline('x'),3) 3
feval(inline(‘cos(x)'),pi) cos(pi)
Department of Mechanical Engineering City University of Hong Kong
26

Programming and Software


Sequence, selection, iteration and how to use function

Department of Mechanical Engineering City University of Hong Kong


27

Sequence

Matlab example:

x=3;
y=x+5;
z=x*y;

Department of Mechanical Engineering City University of Hong Kong


28

Selection
Matlab example:

if x<0
y=-10;
else if x>0
y=10;
else
y=0;
end

Department of Mechanical Engineering City University of Hong Kong


29

Iteration
Matlab example:

for i=0:2:20
x=x+i;
end

Department of Mechanical Engineering City University of Hong Kong


30

Another iteration
Matlab example:

while (1)

i=i+1;

if i>=10, break, end

y=x^2;

end

Department of Mechanical Engineering City University of Hong Kong


31

function mainprog

m=68.1;
g=9.8; function myvelocity(m,g,c,t)
c=0.25;
t=0:2:12;

v=velocity(m,g,c,t) function velocity_profile(m,g,c,t)

v1=velocity_profile(m,g,c,t)

plot (t, v, t, v1) function ……

Department of Mechanical Engineering City University of Hong Kong


32

Your tasks
• Complete the rootfind function
• Prepare a main function to solve the
following three equations (precision 0.1%):
– f(x)=x=0 within [-2 2] range
– f(x)=cos(x)=0 within [1.4 1.6] range
– At least two roots of f(x)=cos(x)+exp(-x2)=0

Department of Mechanical Engineering City University of Hong Kong

You might also like