MATLAB: I’m not sure how to set the stop criterion in the bisecting method

270-06homework

This is what I have so far..
f=@(x) (x^3)-(3*x^2)-(x)+9;
a=-2;
b=-1;
for i=1:1000
c=(a+b)/2;
if f(c)>0
b=c;
else a=c;
end
end
fprintf('Root of given equation is %f',c)

Best Answer

Inside the loop you can use this:
if( abs(a-b) <= epsilon )
break;
end
Where epsilon is a value you set prior to the loop (e.g., 0.001 for this problem).
Suggestion: You should check to see that at the start of your code f(a)<=0 and f(b)>=0, because if that isn't the case then your code will not work. You may have to swap a and b or you may have to throw an error depending on the situation. You might also want to print out the value of abs(a-b) to make sure your algorithm converged to the desired tolerance.