필터 지우기
필터 지우기

Stopping my function from doing iteration (infinite while loop)

조회 수: 2 (최근 30일)
A K
A K 2012년 12월 21일
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일
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일
No, i mean by setting that as the condition. Is it possible?

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

추가 답변 (1개)

John Petersen
John Petersen 2012년 12월 21일
편집: John Petersen 2012년 12월 21일
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.

카테고리

Help CenterFile 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