% bisection.m
function bisection
% find root of x^2 - 3 on some interval
xa = 0; xb = 10; % search interval
for it = 1:20 % loop
xtest = xa + (xb-xa)/2; % mid point of interval
fa = f(xa); % left-interval function value
fb = f(xb); % right-interval function value
ftest = f(xtest); % mid-point function value
if sign(fa)*sign(ftest)<0 % if zero in left half
xb = xtest; % take left half of interval
elseif sign(ftest)*sign(fb)<0 % if zero in right half
xa = xtest; % take right half of interval
elseif ftest ==0 % if zero at mid-point
break % this is the zero
else %
error('multiple roots or no root') % may have no zero or multiple zeros
end
xit(it) = xtest; % store mid-points
end
figure;plot(xit) % plot mid-points, should converge to the root
function y = f(x) % function we're finding the root of
y = x^2-3;