Stopping my function from doing iteration (infinite while loop)

After achieving the desired result the loop continues, how can i stop this? if truefunction y = mysqrt(x,y0,tol) % this function calculates the square root of a number x as y given the % less appropriate guess y0. The function ceases to iterate when the the % difference between y0 and y is less than 1e-3.
y = (y0 + (x/y0))/2;
y = (y + (x/y))/2;
while abs(y-y0)>tol
y = (y + (x/y))/2
end

1 件のコメント

A K
A K 2012 年 12 月 21 日
woops forgot to add the top line of the script:
function y = mysqrt(x,y0,tol)function

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

 採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 12 月 21 日
編集済み: Azzi Abdelmalek 2012 年 12 月 21 日

1 投票

function y = mysqrt(x,y0,tol)
y = (y0 + (x/y0))/2;
y = (y + (x/y))/2;
while abs(y^2-x)>tol
y = (y + (x/y))/2
end

5 件のコメント

A K
A K 2012 年 12 月 21 日
ooooooooooooooooohhhhhhhhhhhhh that makes sense!!!! thanks!!!
A K
A K 2012 年 12 月 21 日
how about when 2 iterations are closer than tol?
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 12 月 21 日
The while loop will be skipped. The result will be fine
A K
A K 2012 年 12 月 21 日
No, i mean by setting that as the condition. Is it possible?
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 12 月 21 日
It's not clear

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

その他の回答 (1 件)

John Petersen
John Petersen 2012 年 12 月 21 日
編集済み: John Petersen 2012 年 12 月 21 日

1 投票

function y = mysqrt(x,y0,tol)
y = (y0 + (x/y0))/2;
while abs(y-y0)>tol
y0 = y;
y = (y + (x/y))/2;
end
Now I see Azzi's answer which is better because it tests against the desired result.

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by