Strange behaviour with elseif

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.

 Respuesta aceptada

Andreas Goser
Andreas Goser el 24 de En. de 2011

1 voto

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

Más respuestas (0)

Categorías

Más información sobre Scope Variables and Generate Names en Centro de ayuda y File Exchange.

Productos

Etiquetas

Preguntada:

el 24 de En. de 2011

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by