In: Advanced Math
7. Finding Roots Using the Bisection Method
Write a function that implements the "bisection method" for finding the roots of function. The signature of your function should look like
def find_root(f,a,b,n):
where n is the maximum number of iterations of to search for the root.
The code should follow this algorithm:
We are given a continuous function f and numbers a and b and with a<b with f(a)<0<f(b). From the intermediate value theorem we know that there exists a c with a<c<b with f(c)=0. We want to find c.
Set a1=a and b1=b and m=12(a+b).
For i=1 to n do
%%Matlab code for finding root using Bisection method
clear all
close all
%Function for which root have to find
fun=@(x) sin(x)-1/2;
%displaying the function
fprintf('\tFor the function\n')
disp(fun)
%Root using Bisection method
x0=0; x1=1; %Initial guess
n=100; %maximum iteration
[root]=find_root(fun,x0,x1,n);
fprintf('Root using Bisection method for initial guess[%f,%f] is
%2.15f with iteration count %d.\n\n',x0,x1,root,n);
%Matlab function for Bisection Method
function [root]=find_root(f,a,b,n)
if f(a)<=0
t=a;
a=b;
b=t;
end
%f(x1) should be positive
%f(x0) should be negative
for i=1:n
xx(i)=(a+b)/2;
mm=double(f(xx(i)));
if mm>=0
a=xx(i);
else
b=xx(i);
end
end
root=xx(end);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%