why is my while loop only looping once?
3 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Mischa Kim
on 15 Sep 2014
Edited: Mischa Kim
on 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.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!