Can we use for loop in bisection method for root finding instead of while loop

f = @ (x) x.^2+5.*x-10 ;
xl=0;
xu=10;
xm = (xl+xu)/2;
tol = 1e-10;
iter = 0;
while(abs(f(xm))>tol) %do bisection till f(xm) is small enough
if (f(xl)*f(xm)<0) % determine which bracket root exists
xu = xm;
else
xl = xm;
end
iter = iter+1; %increase iteration value
xm = (xl+xu)/2 %new mean value
end
iter

回答 (2 件)

Bjorn Gustavsson
Bjorn Gustavsson 2019 年 6 月 11 日

0 投票

Yes it is possible, but why? You could use the break trick to exit the for-loop at convergence, but why bother, code should be clearly written - in the long-term vastly benefitial to marginal gains for a simple root-finding function.
HTH
Walter Roberson
Walter Roberson 2019 年 6 月 11 日

0 投票

Yes, a for loop makes sense to put an upper limit on iterations in case something goes wrong with the convergence. if/break works fine to leave the loop early.

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2019 年 6 月 11 日

回答済み:

2019 年 6 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by