Help with bisection method

조회 수: 20 (최근 30일)
Lauren Holm
Lauren Holm 2022년 3월 11일
댓글: Lauren Holm 2022년 3월 11일
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

답변 (1개)

David Hill
David Hill 2022년 3월 11일
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
Lauren Holm
Lauren Holm 2022년 3월 11일
I can't say thank you enough!!!!!! THANK YOU :)))))))!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by