Help with bisection method
39 views (last 30 days)
Show older comments
I am having trouble with this code for the bisection method. It keeps outputting an answer of 1 no matter how many iterations I put, but that is not the root of this equation. I also don't know how to output a table for each iteration.
function Bisect(xl, xu, es, imax, xr, it, ea)
f =@(x) exp(-x) - x;
it = 0;
fl = f(xl);
xrold = xr;
xr = (xl + xu) / 2;
fr = f(xr);
it = it + 1;
if xr ~= 0
ea = abs((xr - xrold) / xr) * 100;
end
if (fl * fr) < 0
xu = xr;
else if (fl * fr) > 0
xl = xr;
fl = fr;
else
ea = 0;
end
end
if ea < es, or iter >= imax
end
Bisect = xr
end
0 Comments
Answers (1)
David Hill
on 11 Mar 2022
function bisect= Bisect(f,xl, xu, es, imax)%recommend imputting the function
it=0;
ea=1;
xr = (xl + xu) / 2;
while ea>es && it<imax % you need a loop
fr = f(xr);fl = f(xl);
it = it + 1;
if (fl * fr) < 0
xu = xr;
elseif (fl * fr) > 0
xl = xr;
else
ea = 0;
end
xrold=xr;
xr = (xl + xu) / 2;
ea = abs((xr - xrold) / xr) * 100;
bisect(it)=xr;%index to maintain all interations of xr's
end
end
Then call the function Bisect(). Index whatever you want to provide in a table and assemble the table outside the loop.
bisect=Bisect(@(x)exp(-x)-x,0,1,1e-14,100);
bisect(end)
ans =
0.567143290409784
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!