Strange behaviour with elseif
1 view (last 30 days)
Show older comments
Hi, I noticed something totally strange with a repeated elseif statement. Here is the code:
A = [0.0001:0.0001:0.0009];
for i=1:length(A)
x=A(i);
if x == 0.0001
x
elseif x == 0.0002
x
elseif x == 0.0003
x
elseif x == 0.0004
x
elseif x == 0.0005
x
elseif x == 0.0006
x
elseif x == 0.0007
x
elseif x == 0.0008
x
elseif x == 0.0009
x
else
display('Error')
end
end
When I run it, I get twice the "Error" displayed, for x=0.0003 and x=0.0008. I could reproduce it on two different Matlab version (R2009a & R2010a). Any idea? Thanks a lot.
0 Comments
Accepted Answer
Andreas Goser
on 24 Jan 2011
The behaviour you observe is not a bug, but a result of normal numerical effects on different installations (surely processors, OS; maybe releases). A bit background reading:
It is not a best practice to do comparisions like that. My guess is that there is a fundamentally different way for you to write the code, but in case you like it that way, I suggest introducing the comparison with a tolarance like that:
A=0.0001;
A_test=0.0001+eps;
if A==A_test
disp('equal')
else
disp('not equal')
end
if abs(A-A_test)<(2*eps)
disp('numerically equal')
else
disp('numerically not equal')
end
0 Comments
More Answers (0)
See Also
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!