Solve the following problem using the MATLAB environment
Write a function [approx_root, num_its] = bisection(f,a,b,tol) that implements the bisection method. You function should take as input 4 arguments with the last argument being optional, i.e, if the user does not provide the accuracy tol use a default of 1.0e-6 (use varargin to attain this). Your function should output the approximate root, approx_root and the number of iterations it took to attain the root, num_its. However, if the user calls the function with one argument, your function should return a vector consisting of the approximate root and the number of iterations (see how we used nargout in class). In addition, your function should display and error message and terminate if the user provides an interval without a root. Test your method to solve the following:
(a) x x = 50 on [3, 4]
(b) ln(x) = cos(x) on [1, 2]
In each case first find an interval of size 1 that contains the root, sketch the graphs to determine this. You should also provide tests showing
(a) Your error code handling error messages is correct.
(b) Run the code with the different options for input and output.
(c) Run your code with tol = 1.0e-12 and the default, tol = 1.0e-06.
This is the required function:
function[approx_root,num_its]=
bisection(f,a,b,tol=10^(-6))
if(f(a)*f(b)>0)
printf("\n There is no root in the interval")
return;
endif
dif=f(a)-f(b);
iter=0;
while(abs(dif)>tol)
c=(a+b)/2;
num_its=num_its+1;
if(f(a)*f(c)>0)
a=c;
elseif(f(b)*f(c)>0)
b=c;
elseif(f(c)==0)
break;
elseif(abs(dif2)<10^(-6))
break;
endif
dif=f(a)-f(b)
dif2=a-b
endwhile
approx_root=(a+b)/2
v=[approx_root,num_its]
disp(v)
endfunction
We can call this using:
f=@(x) x.^x.-50
g=@(x) log(x).-cos(x)
bisection(f,3,4)
bisection(g,0,1)
Get Answers For Free
Most questions answered within 1 hours.