%estimates a root of f in the interval [a,b] via the bisection method

f = @(x) x^3+2*x+cos(x);
a = -1;            %left endpoint
b = 0;             %right endpoint
n = 10;            %number of iterations

x = zeros(n+1,2);    
x(1,:) = [a,b];    %ith row of x = interval [a,b] at (i-1)st iteration

for i=1:n
    c = 0.5*(a+b);                 %midpoint
    if sign(f(c)) ~= sign(f(a))
        b = c;                     %f(a)f(c)<0 means the root is in [a,c]
    else
        a = c;                     %f(a)f(c)>0 means the root is in [c,b]
    end
    x(i+1,:) = [a,b];              %sequence of intervals [a,b]
end

disp('the intervals are...')
x

disp('estimate of root is...')
a
        

