The Bisection method discussed in class was just a manor in which to approximate
ID: 2085792 • Letter: T
Question
The Bisection method discussed in class was just a manor in which to approximate the roots of an equation. This needs to be written in MATLAB. I know this is basically the binary root search method but I am not sure how to write this code.
1) Write a Matlab program that implements the bisection method that we dis- cussed in class. Hard coded at the beginning of your program should be f, a, b, and e. Here f is the function for which we are trying to solve f(x - 0 and the initial interval is [a, b]. Finally, e is a small positive number such that the program halts execution when the error (i.e., the difference between the exact answer and its approximation) is less than e. The output of your program should be the approximate solution x* such that f(x*) 0.Explanation / Answer
function m = bisection(f, low, high, tol)
disp('Bisection Method');
% Evaluate both ends of the interval
y1 = feval(f, low);
y2 = feval(f, high);
i = 0;
% Display error and finish if signs are not different
if y1 * y2 > 0
disp('Have not found a change in sign. Will not continue...');
m = 'Error'
return
end
% Work with the limits modifying them until you find
% a function close enough to zero.
disp('Iter low high x0');
while (abs(high - low) >= tol)
i = i + 1;
% Find a new value to be tested as a root
m = (high + low)/2;
y3 = feval(f, m);
if y3 == 0
fprintf('Root at x = %f ', m);
return
end
fprintf('%2i %f %f %f ', i-1, low, high, m);
% Update the limits
if y1 * y3 > 0
low = m;
y1 = y3;
else
high = m;
end
end
% Show the last approximation considering the tolerance
w = feval(f, m);
fprintf(' x = %f produces f(x) = %f %i iterations ', m, y3, i-1);
fprintf(' Approximation with tolerance = %f ', tol);
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.