why is my while loop only looping once?

5 vues (au cours des 30 derniers jours)
Brandon
Brandon le 15 Sep 2014
Commenté : Brandon le 21 Sep 2014
f=@(x) (1/x)-37;
if f(a)>0 && f(b)>0 f(a)<0 && f(b)<0 error('does not bracket root') end
ea=1000; es=(.5 *10^(2-5)); %5 sig figs while es < ea root=(a+b)/2; oldroot=root; if f(root)>0 && f(a)>0 f(root)<0 && f(a)<0 a=root; else b=root; end
ea=abs(((root)-oldroot)/root)*100;
end %second end because it is a function i just did not include
end

Réponse acceptée

Mischa Kim
Mischa Kim le 15 Sep 2014
Modifié(e) : Mischa Kim le 15 Sep 2014
Brandon, check out
f = @(x)(1/x) - 37;
a = 0.001; b = 0.1; root = a;
if (f(a)>0 && f(b)>0) || (f(a)<0 && f(b)<0)
error('does not bracket root')
end
ea = 1000; es = (.5 *10^(2-5)); %5 sig figs
while es < ea
oldroot = root; % swapped command...
root = (a+b)/2; % ...with this one
if (f(root)>0 && f(a)>0) || (f(root)<0 && f(a)<0)
a = root;
else
b = root;
end
ea = abs(((root) - oldroot)/root)*100;
end %second end because it is a function i just did not include
You need to swap the two command lines as shown above: first save the old root, before you assign a new one. If you do it the other way oldroot will alway be equal to root , therefore ea = 0 and you exit the loop right away.
  1 commentaire
Brandon
Brandon le 21 Sep 2014
It worked! Thank you!

Connectez-vous pour commenter.

Plus de réponses (0)

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