MATLAB: Please help me in debugging the code

I wrote a code which finds roots using the bisection method but the problem is its just showing up my answer as zero so if you are willing to help me I am very happy.
first_function = @ (x) cos(x)-2*x;
x_upper = 4;
x_lower = -5;
x_mid = (x_lower + x_upper)/2;
i=0;
while abs(x_mid) > 10^-8
if (first_function(x_mid))*(first_function(x_lower))<0
x_lower=x_mid;
else
x_upper = x_mid;
end
x_mid = (x_lower + x_upper)/2;
i=i+1;
end
fprintf('The root is %g and the number of iteration is %g\n ', x_mid,i)

Best Answer

The bug is on these lines:
if (first_function(x_mid))*(first_function(x_lower))<0
x_lower = x_mid;
else
x_upper = x_mid;
end
Think about what that comparison actually does (don't just blindly implement some formula you found online): if the difference in sign is negative, then the intersect must be in between. So if you test the lower bound and the sign is negative, then you need to reassign the upper bound value. And vice versa. It really does not matter which way you code this (i.e. test the upper or test the lower, you might find both online), as long as you change the other bound if the sign is negative.
After I fixed this (and the ambiguous parentheses), the code worked perfectly:
f = @(x)cos(x)-2.*x;
a = +4;
b = -5;
h = (a+b)/2;
k = 0;
while abs(f(h)) > 1e-8
if (f(a)*f(h))<0
b = h;
else
a = h;
end
h = (a+b)/2;
k = k+1;
end
fprintf('The root is %g and the number of iteration is %d\n ',h,k)
Prints:
The root is 0.450184 and the number of iteration is 26