Stopping my function from doing iteration (infinite while loop)

2 vues (au cours des 30 derniers jours)
A K
A K le 21 Déc 2012
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 commentaire
A K
A K le 21 Déc 2012
woops forgot to add the top line of the script:
function y = mysqrt(x,y0,tol)function

Connectez-vous pour commenter.

Réponse acceptée

Azzi Abdelmalek
Azzi Abdelmalek le 21 Déc 2012
Modifié(e) : Azzi Abdelmalek le 21 Déc 2012
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 commentaires
A K
A K le 21 Déc 2012
No, i mean by setting that as the condition. Is it possible?
Azzi Abdelmalek
Azzi Abdelmalek le 21 Déc 2012
It's not clear

Connectez-vous pour commenter.

Plus de réponses (1)

John Petersen
John Petersen le 21 Déc 2012
Modifié(e) : John Petersen le 21 Déc 2012
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.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by