bisection in matlab

Here's an implementation of the bisection method in MATLAB:

main.m
function [root, fx, ea, iter] = bisection(f, xl, xu, es, maxiter)
% bisection: root finding via the bisection method
%   [root, fx, ea, iter] = bisection(f, xl, xu, es, maxiter):
%       uses the bisection method to find the root of function f
%       within the bracket [xl, xu]
% input:
%   f = the function to be evaluated
%   xl, xu = the lower and upper bounds of the bracket
%   es = the desired relative error (default: 0.0001%)
%   maxiter = the maximum number of iterations (default: 50)
% output:
%   root = the estimated root
%   fx = the function evaluated at the estimated root
%   ea = the approximate relative error (%)
%   iter = the number of iterations performed

% check number of inputs
if nargin < 3
    error('at least 3 input arguments required')
end
% set defaults
if nargin < 4 || isempty(es)
    es = 0.0001;
end
if nargin < 5 || isempty(maxiter)
    maxiter = 50;
end
% check bracket
test = f(xl) * f(xu);
if test > 0
    error('no sign change in bracket')
end
% initialize variables
iter = 0;
xr = xl;
ea = 100;
% loop until relative error is smaller than desired error or maxiter is reached
while ea > es && iter < maxiter
    xrold = xr;
    xr = (xl + xu) / 2;
    iter = iter + 1;
    if xr ~= 0
        ea = abs((xr - xrold) / xr) * 100;
    end
    test = f(xl) * f(xr);
    if test < 0
        xu = xr;
    elseif test > 0
        xl = xr;
    else
        ea = 0;
    end
end
% calculate function value at root
fx = f(xr);
% output results
root = xr;
end
1491 chars
59 lines

You can call this function with your desired function, lower bound xl, upper bound xu, desired relative error es, and maximum number of iterations maxiter. For example, to find the root of the function f(x) = x^2 - 2 within the bracket [1, 2] with a relative error of 0.1%, you can call the function like this:

main.m
f = @(x) x^2 - 2;
xl = 1;
xu = 2;
es = 0.001;
maxiter = 100;
[root, fx, ea, iter] = bisection(f, xl, xu, es, maxiter);
119 chars
7 lines

which will return the estimated root root, the function value fx at the root, the approximate relative error ea, and the number of iterations iter.

gistlibby LogSnag