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.

추가 답변 (0개)

카테고리

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