Relational Operators Issue - 1 is not equal to 1.000

5 vues (au cours des 30 derniers jours)
usr0815
usr0815 le 29 Mai 2012
Hey there,
the following CODE (MATLAB 2011b) results in an unexpected problem, which I'd like to know the reason for:
x = 0;
y = 1;
for i = 1:10
x = x + 0.1;
end
Result:
x = 1.0000
y = 1
The use of some relational operators to compare x and y
a = y == x;
b = y < x;
c = y > x;
Results:
a = 0
b = 0
c = 1
It seems as if the value of x after passing the for-loop is less than 1, even though the workspace displays x = 1.0000... and y = 1.
Actually I experienced this problem in some measurement automation loop and solved it by using
d = y == round(x*100000)/100000;
Result:
d = 1
The question arises: Is this the only/best way to solve this problem or is there a better work-around - maybe a generalized solution - that avoids such problems in advance!
Additional information: Both variables x and y are DOUBLE after the creation.
Thanks for your help!

Réponse acceptée

Thomas
Thomas le 29 Mai 2012
  1 commentaire
Walter Roberson
Walter Roberson le 29 Mai 2012
Yes, see that FAQ.
You are only displaying a few digits after the decimal place, and for *display* purposes the value you are displaying rounds to 1.000 but that does not mean that the value *is* 1

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by