Sample Matlab codes for Mapl/CMCS 466, Spring 2000 - Bo Li
% bisection.m --- a sample MATLAB code implementing the bisection
% algorithm for solving the equation x*x-2 = 0.
% a = the left end-point of the interval [a,b]
% b = the right end-point of the interval [a,b]
% N = maximum number of iterations
% epsilon = tolerance: the smallest absolute function value
clear;
a = 0; b = 2; N = 20; epsilon = 1.e-14;
fa = a*a-2; fb = b*b-2; e = b-a;
disp([a,b,fa,fb]);
if sign(fa) ~= sign(fb)
for k = 1:N
e = e/2; p = a+e; fp = p*p-2;
disp(sprintf('%5.0f %12.8f %12.8f %12.8f %12.8f', k,p,abs(fp),e));
if (abs(e) < epsilon)
break;
end
if sign(fp) ~= sign(fa)
b = p; fb = fp;
else
% fill in this line to complete the code
end
end
end