```
function r=bisection(f,a,b,tol,nmax)
% function r=bisection(f,a,b,tol,nmax)
% inputs: f: function handle or string
% a,b: the interval where there is a root
% tol: error tolerance
% nmax: max number of iterations
% output: r: a root
c=(a+b)/2;
nit=1;
if f(a)*f(b)>0
r=NaN;
fprintf("The bisection method failed \n")
else
while(abs(f(c))>=tol && nit<nmax)
if (f(c)*f(a))<0
c=(a+c)/2;
elseif (f(c)*f(b))<0
c=(a+b)/2;
elseif f(c)==0
break;
end
nit=nit+1;
end
r=c;
end
```

Above are my code for the Bisection method. I am confused about why that code don't work well. The result of `f(c)`

is repeated every three times when running this. Does anyone can tell me why this code won't work?

Read more here: https://stackoverflow.com/questions/64397486/bisection-method-in-matlab

### Content Attribution

This content was originally published by hehex4 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.