MATLAB Write a code bisect.m that implements the bisection method for finding a
ID: 3804430 • Letter: M
Question
MATLAB
Write a code bisect.m that implements the bisection method for finding a root of F(x) = 0 in an interval [a , b] to a given accuracy.
? The code should accept inputs: a , b, TOL , should print out the iterates: n x F(x) ERRn (neatly, in columns, use format: %d %f %e %e ),
? and upon convergence it should print out the value of the root, the residual, the error and how many iterations it took.
? The (formula for the) function F(x) should be coded in a function subprogram: function y = FCN(x)
? You may set maxIT=100; in the code.
? Of course, you must debug the code (on a simple problem with known solution).
Explanation / Answer
Create a file driver.m and run it
bisect.m
function [root] = bisect(a,b,Tol)
format long;
a = 1;
b = pi;
c = 2;
iter = 1;
while ((b-a) >= Tol && iter <= 100)
iter;
c = (a+b)/2;
if ((FCN(c)) == 0.0)
break;
elseif ((FCN(c))*(FCN(a)) < 0)
b = (a+b)/2;
else
a = (a+b)/2;
end
fprintf('Iteration = %d X = %d F(x)= %d Error = %d ',iter,c,FCN(c),FCN(c));
iter = iter + 1;
end
fprintf('Actual Root = %d Iterations = %d Error = %d ', c,iter,FCN(c));
root=c;
end
FCN.m
function [value] = FCN(x)
value = x^3 + x^2 - 3*x - 3;
end
Sample Output:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.