Two values ​​are apparently the same, but matlab says that they are not

advertisements

This question already has an answer here:

  • What is -0.0 in matlab? 1 answer

I cannot explain this. I have two variables having the same value, yet they are not identical. Can anybody tell me what I'm missing here?

>> y
y =
3.4000
>> x
x =
3.4000
>> y==x
ans =
 0
>> whos x
 Name      Size            Bytes  Class     Attributes
 x         1x1                 8  double
>> whos y
 Name      Size            Bytes  Class     Attributes
 y         1x1                 8  double

It's really puzzling for me and I swear it's not a joke.


It's because of floating point precision. Try

format long g

and then look at x and y again. It's better to compare x-y to some small tolerance value rather than doing an equality test on floating point numbers