Help with bisection method
조회 수: 20 (최근 30일)
이전 댓글 표시
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
답변 (1개)
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!