MATLAB: HELP! Bisection method fails to found zero

bisectionbisection failmathematicsMATLABzero

I tried to calculate the zero for the function , but the zero isn't found in . I have the same problem for other function like .
I paste here my code (part of my function) :
TOLF = eps;
nit= 0; % number of iterations
m = xo(1)+0.5*diff(xo); % midpoint
while(abs(diff(xo))> p.Results.TOL*max(abs(xo)) && ...
abs(fun(m))>TOLF && nit<p.Results.NMAX) % stopping condition
if(fun(m)*fun(xo(1))<0)
xo(2)= m;
else
xo(1)= m;
end
nit=nit+1;
m = xo(1)+0.5*diff(xo);
end

Best Answer

Simply use the debugger to test, what's going on:
You can check programmatically also, why the loop is stoped:
ready = false;
while ~ready
...
readyTOL = (abs(diff(xo)) >= TOLX;
readyABS = abs(fun(m)) >= TOLF;
readyNIT = nit<p.Results.NMAX;
ready = (readyTOL || readyABS || readINT);
end
output.stopped = [readyTOL, readyABS, readINT];
...
Now you can see, which condition has stopped the loop.
By the way, this test is not useful:
if (abs(diff(xo))> p.Results.TOL*max(abs(xo)) && ...
abs(fun(m))>TOLF && ...
nit==p.Results.NMAX)
warning("limit reached... calculation stopped!");
end
It is very unlikly, that the maximum iteration number was reached and the absolute tolerance and the relative tolerance for the interval length at the same time.
I assume you want this:
if nit == p.Results.NMAX
warning("Maximum number of iterations reached!");
end
This warns, if the found solution is not accurate, because the process stopped by the iteration counter.
What about replacing:
if(max(abs(xo))>realmin/p.Results.TOL)
TOLX = p.Results.TOL * max(abs(xo));
else
TOLX = realmin;
end
by
TOLX = max(p.Results.TOL * mmax(abs(xo)), realmin);