In: Computer Science
You have been provided with starter code that contains the place holders and some implementations for Bisection and Secant methods. Complete the code where it says #provide this line so that it could be run for the following case:
1) ?(?) = ? 3 + 4, ?? = −3, ?? = 0, ??????? = 100, ?? = 0.2
Starter Code:
def eq(x):
return x**3+4
def err(xr,xold):
return abs((xr-xold)/xr)*100
def bisection(xl,xu,maxIter,sc):
# xl is the lower bound of the initial bracket
# xu is the upper bound of the initial bracket
# maxIter is the maximum number of iteration for finding the root
# sc is the stopping criteria
xm=(xl+xu)/2
for i in range(maxIter):
if eq(xl)*eq(xm)>0:
# provide this line
# provide this line
else:
# provide this line
# provide this line
xn=(xl+xu)/2
if # provide this line
return xn
xm=xn
def secant(xi,xip1,maxIter,sc):
# xip1 is xi plus one
# maxIter is the maximum number of iteration for finding the root
# sc is the stopping criteria
for i in range(maxIter):
eqDer= # provide this line
xi=xip1
# provide this line
if eq(xip1)=1: # provide this line
return xip1
Bisection Method
Step1: First let us understand about bisection method.
> Given a function f(x) on number x.
> Also given two numbers ‘p’ and ‘q’ such that f(p)*f(q) < 0 and f(x) is continuous in [p, q].
Here f(x) represents algebraic or transcendental equation.
> Now we need to find the root of function in interval [p, q] such that f(x) is 0.e
Step 2: Let us have the algorithm for the bisection method
Let r=(p+q)/2
If f(r)=0, stop and return cc.
If sign(f(p))≠sign(f(r)), then set q=r. Else if sign(f(q))≠sign(f(r)), then set p=r.
Go to the beginning and repeat until convergence.
Secant Method
Step 1: It is the procedure to find the roots of an equation for two distinct values using an interpolation method.
Step 2: The algorithm for the second method is given as follows:
def eq(x):
return x**3+4
def err(xr,xold):
return abs((xr-xold)/xr)*100
def bisection(xl,xu,maxIter,sc):
# xl is the lower bound of the initial bracket
# xu is the upper bound of the initial bracket
# maxIter is the maximum number of iteration for finding the root
# sc is the stopping criteria
xm=(xl+xu)/2
for i in range(maxIter):
if eq(xl)*eq(xm)>0:
xl=xm# provide this line
xu=xu# provide this line
else:
xu=xm# provide this line
xl=xl# provide this line
xn=(xl+xu)/2
if xn==0:# provide this line
return xn
xm=xn
def secant(xi,xip1,maxIter,sc):
# xip1 is xi plus one
# maxIter is the maximum number of iteration for finding the root
# sc is the stopping criteria
for i in range(maxIter):
eqDer=xi - (xip1-xi)*f(xi)/( f(xip1) - f(xi) ) # provide this line
xi=xip1
xip1=eqDer# provide this line
if eq(xip1)==1: # provide this line
return xip1