%
%  Problem 3.1.1(d):
%  Solving x = exp(-x) using the Bisection Method w/ 10^-4 accuracy
%
%  Math 340 * Victor Matveev * February 11, 2012
%  See solution to homework #3 for details

epsilon = 0.0001;      % Define the tolerance (error, accuracy)
f = @(x) x - exp(-x);  % Define the equation to solve

a = 0; b = 1;          % Initial interval bracketing the root
fa = f(a); fb = f(b);  
c = (a + b) / 2;

% Print the header:
fprintf('\n      a:      |       b:      |       c:      |     f(c):    ');
fprintf('\n-----------------------------------------------------------\n');

while (b - c) > epsilon
    fc = f(c);
    fprintf(' %.9f  |  %.9f  |  %.9f  |  %.3e\n', a, b, c, fc);

    if fc == fa || fc == fb % This ensures the iteration won't run forever
        break;
    elseif fc*fa < 0
        b = c;
        fb = fc;
    else
        a = c;
        fa = fc;
    end
    c = (a + b)/2;
end
