Help with bisection method

20 vues (au cours des 30 derniers jours)
Lauren Holm
Lauren Holm le 11 Mar 2022
Commenté : Lauren Holm le 11 Mar 2022
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

Réponses (1)

David Hill
David Hill le 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
  1 commentaire
Lauren Holm
Lauren Holm le 11 Mar 2022
I can't say thank you enough!!!!!! THANK YOU :)))))))!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by