Why this x == g gave me logic 0?

2 vues (au cours des 30 derniers jours)
Zhipeng
Zhipeng le 21 Fév 2019
Commenté : Zhipeng le 23 Fév 2019
g = 0.1;
x = 0.102;
x = x - 0.001;
x = x - 0.001;
x == g
This is a simple code and I didn't know why matlab give me logic 0 for compare x==g
ans =
logical
0

Réponse acceptée

Stephen23
Stephen23 le 21 Fév 2019
Modifié(e) : Stephen23 le 21 Fév 2019
"Why this x == g gave me logic 0?"
Simply because those values are NOT the same.
The values that you are trying to compare cannot be exactly represented using binary floating point numbers. What you see printed in the command window is the closest representation to 5 or 16 significant digits, depending on your current format setting. To see the "real" value download James Tursa's FEX submission:
Use James Tursa's num2strexact and you will see that none of those values really have the exact values 0.1 or 0.001. All you are looking at is a representation of those floating point numbers displayed in the command window, to the precision defined by your format setting. Just because you see 0.1 is displayed tells you nothing about the "real" floating point number's value.
Note that you can change how the value is displayed by changing the format.
To compare floating point values always compare the absolute difference against a tolerance:
abs(A-B)<tol
You need to learn about the limits of floating point numbers. Start by reading these:
This is worth reading as well:
  1 commentaire
Zhipeng
Zhipeng le 23 Fév 2019
Thank you!!

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by