clc, clear, close all;

function x = bisectionroot(f,x_l,x_u,iterations)
tol = 1e-6;
x_old = x_l;

if nargin < 4
    iterations = 10;
end
if (f(x_l)*f(x_u) > 0)
   warning('Initial interval is not guaranteed to contain a root.')
   x = (x_l + x_u)/2;
   return
end

for i = 1:iterations
   x_m = (x_l + x_u)/2;

   if (f(x_l)*f(x_u) > 0)
       break
   end

   if f(x_m) == 0
       x = x_m;
       return
   end

   if f(x_l) * f(x_m) < 0
       x_u = x_m;
   else
       x_l = x_m;
   end

   if abs((x_m-x_old)/x_m) < tol
       break
   end

   x_old = x_m;
end
x = x_m;
end

f = @(x) x.^3 - 0.165 * x.^2 + 3.993 * 10^-4;
x_l = 0;
x_u = 0.11;

x = bisectionroot(f,x_l,x_u);
disp(x);
disp(f(x));

t = linspace(x_l,x_u,100);
plot(t,f(t));
hold on;
plot([x_l, x, x_u],[f(x_l), f(x), f(x_u)], '.');