function [a,b,fail] = bisect(f,a,b,eps,N)
%
% Applies the bisection method to the function f on [a,b],
% f is assumed to be continuous and f(a)*f(b) < 0.
% Stops when |f(a)| < eps or |f(b)| < eps or |b-a| < eps.
% Failure is reported (fail = 1) when the accuracy requirement
% is not satisfied in N steps; otherwise fail = 0 on return.
%
% Example :
% >> [a,b,fail] = bisect('cos',pi/4,2*pi/3,1.0e-4,100)
%
fprintf('running the bisection method...\n');
fprintf('-------------------------------------------\n');
fprintf(' a b m |f(m)| |b-a| \n');
fprintf('-------------------------------------------\n');
for i = 1:N
m = (a+b)/2;
fm = feval(f,m);
if fm*feval(f,a) < 0
b = m;
else
a = m;
end;
fprintf(' %4.3f %4.3f %4.3f %.2e %.2e\n',a,b,m,abs(fm),abs(b-a));
if (abs(fm) < eps) | ((b-a) < eps)
fail = 0;
fprintf('succeeded after %d steps\n', i);
return;
end
end
fprintf('failed requirements after %d steps\n', N);
fail = 1;
Follow the links to download the m-file.
The output of this algorithm on cos(x) = 0 with [a,b] = [pi/4,2*pi/3] :
[a,b,fail] = bisect('cos',pi/4,2*pi/3,1.0e-4,100)
running the bisection method...
-------------------------------------------
a b m |f(m)| |b-a|
-------------------------------------------
1.440 2.094 1.440 1.31e-01 6.54e-01
1.440 1.767 1.767 1.95e-01 3.27e-01
1.440 1.604 1.604 3.27e-02 1.64e-01
1.522 1.604 1.522 4.91e-02 8.18e-02
1.563 1.604 1.563 8.18e-03 4.09e-02
1.563 1.583 1.583 1.23e-02 2.05e-02
1.563 1.573 1.573 2.05e-03 1.02e-02
1.568 1.573 1.568 3.07e-03 5.11e-03
1.570 1.573 1.570 5.11e-04 2.56e-03
1.570 1.572 1.572 7.67e-04 1.28e-03
1.570 1.571 1.571 1.28e-04 6.39e-04
1.571 1.571 1.571 1.92e-04 3.20e-04
1.571 1.571 1.571 3.20e-05 1.60e-04
succeeded after 13 steps
a =
1.5708
b =
1.5709
fail =
0