why is my while loop only looping once?

5 ビュー (過去 30 日間)
Brandon
Brandon 2014 年 9 月 15 日
コメント済み: Brandon 2014 年 9 月 21 日
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

採用された回答

Mischa Kim
Mischa Kim 2014 年 9 月 15 日
編集済み: Mischa Kim 2014 年 9 月 15 日
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 件のコメント
Brandon
Brandon 2014 年 9 月 21 日
It worked! Thank you!

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

その他の回答 (0 件)

カテゴリ

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