The instructions of the problem are: Use bisection method to find a root of the function $$ \sin x + x \cos x = 0 $$ Indicate your initial condition and how many steps it requires to reach the tolerate of error to be within 10^−6 .
My problem is, I don't know how integrate into the code the tolerance and calculate the steps
f=@(x) sin(x)+x.*cos(x)
xO=0
a=-5;
b=5;
for i=1:100
c=(a+b)/2;
if f(c)>0
b=c;
else
a=c;
end
end
a=-5;
b=5;
p=c;
for i=1:100
c=(a+b)/2;
er(i)=f(c)-f(p);
if f(c)>0
b=c;
else
a=c;
end
end
fprintf('Root of given equation is %f',c)
plot(er);
title('Plot of error')
xlabel('Number of iterations')
ylabel('Error')
In the bisection method, and any root-finder that brackets the root, you can take the error to be half the distance between your brackets. This is because you can report the center of the interval as the root and you know the true root is no farther away than this. You can stop when the length of the interval is less than $2\cdot 10^{-6}$, so make that a test to exit the loop. For bisection, as the bracket is cut in half each step, you can also just compute in advance how many halvings are required. It looks like your interval starts as $10$, so you need $2^{-n} \cdot 10 \lt 2 \cdot 10^{-6}$ and can solve for $n$