Write a MATLAB function, called bisection_method that inputs a function f, two n
ID: 3879667 • Letter: W
Question
Write a MATLAB function, called bisection_method that inputs a function f, two numbers a, b, an error tolerance, tol, and a maximum number of iterations, N, and finds a root c of f in the interval [a, b using the bisection method. Your function should compute a bound on the error, and stop when the error is less than the tolerance, or if the number of iterations exceeds N whichever happens first. (a) Hint #1: The function should start with the line function [c,n,err] bisection, method ( f , a, b, tol,N) = (b) Hint #2: The function should contain a"while, loop, looking something like: while err tol && nExplanation / Answer
PLEASE CREATE bisection_method.m AND PASTE BELOW CODE
function [c,n,err] = bisection_method(f,a,b,tol,N)
% Check that that neither end-point is a root
% and if f(a) and f(b) have the same sign, throw an exception.
if( f(a) == 0)
c = a;
n = 0;
err = 0;
return;
elseif(f(b) == 0)
c = b;
n = 0;
err = 0;
return;
elseif(f(a) * f(b) > 0)
error('f(a) and f(b) do not have opposite sign');
end
% We will iterate N times and if a root was not
% found after N iterations.
err = 0.1;
n = 1;
while err > tol && n < N
m = (a+b)/2;
% Check if we found a root or whether or not
% we should continue with:
% [a, m] if f(a) and f(m) have opposite signs, or
% [m, b] if f(m) and f(b) have opposite signs.
if( f(m) == 0 )
c = m;
err = 0;
return;
elseif( f(m) * f(a) < 0 )
b = m;
else
a = m;
end
if( b - a < tol)
if(abs(f(a)) < abs(f(b)))
c = a;
err = b - a;
return;
else
c = b;
err = b - a;
return;
end
end
n = n + 1;
end
error( 'the method did not converge' );
end
CREATE test.m AND PASTE BELOW CODE
close all
clear all
clc
syms x
f = @(x)(2*x^3 + 3 * x - 1) * cos(x) -x;
a = -1;
b = 1;
tol = 10^-5;
N = 100000;
[c,n,err] = bisection_method(f,a,b,tol,N)
c = fzero(f,[-1,1])
PLEASE REFER BELOW OUTPUT
c =
0.4386
n =
18
err =
7.6294e-06
c =
0.4386
>>
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.