Newton Raphson Method: while loop

15 ビュー (過去 30 日間)
Gianluca Borgna
Gianluca Borgna 2023 年 9 月 9 日
コメント済み: Torsten 2023 年 9 月 11 日
Hi,
Maybe it's a silly question but i don't know ho to stop a while loop.
The condition for my while is when alphanew(i) - aplhanew(i-1) <toll stop but the index i is not required for while loop so i don't really know what to impose. And also i don't know how to stop the while loop when there's no solution.
while condition ?
f=log(alpha)-psi(alpha)-log(Samplemean)+meanlnSample;
f1=1/alpha-psi(1,alpha);
alphanew=alpha-f/f1;
alpha=alphanew;
end
Thanks in advance for the help!

採用された回答

Voss
Voss 2023 年 9 月 9 日
tol = 1e-6;
while true
    f=log(alpha)-psi(alpha)-log(Samplemean)+meanlnSample;
    f1=1/alpha-psi(1,alpha);
    alphanew=alpha-f/f1;
    if abs(alphanew-alpha) < tol
        break
    end
    alpha=alphanew;
end
  2 件のコメント
Gianluca Borgna
Gianluca Borgna 2023 年 9 月 11 日
it works thanks!
Now last question, how to store value of iterations?
Torsten
Torsten 2023 年 9 月 11 日
tol = 1e-6;
iter = 1;
Alpha(1) = alpha;
while true
f=log(alpha)-psi(alpha)-log(Samplemean)+meanlnSample;
f1=1/alpha-psi(1,alpha);
alphanew=alpha-f/f1;
iter = iter + 1;
Alpha(iter) = alphanew;
if abs(alphanew-alpha) < tol
break
end
alpha=alphanew;
end
plot(iter,Alpha)

サインインしてコメントする。

その他の回答 (1 件)

John D'Errico
John D'Errico 2023 年 9 月 9 日
編集済み: John D'Errico 2023 年 9 月 9 日
There are many, MANY ways to stop a while loop. For example...
tol = 1e-8;
err = inf;
iter = 0;
itmax = 100;
while (abs(err) > tol) && (iter < itmax)
iter = iter + 1;
% do stuff that computes the error
...
end
The while loop will terminate IF the error ever drops below the tolerance, OR if the iteration counter is exceeded. A nice thing is, as long as you have the iteration counter in there, it cannot keep on running forever.
The alternative that is commonly used might be something like this:
tol = 1e-8;
err = inf;
iter = 0;
itmax = 100;
while true % Will run forever, UNLESS you break out of the loop
iter = iter + 1;
% do stuff that computes the error
...
if (iter >= itmax) || (abs(err) <= tol)
break
end
end
As you can see, both while loop styles are acceptable, and both will terminate when the time is right. Personally, I prefer the style where the test is in the while statement itself, as that makes it clear what will happen.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by