MATLAB: Why is the while loop only looping once

while loop relative error

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

Best Answer

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.