Why two equal numbers are not equal?

132 views (last 30 days)
Hello everyone,
I had some difficulties comparing some numbers and the problem is simply summarized below :
So can someone tell me why and how this can happen? And how to avoid this kind of problem in the future if possible.
Thank you.

Accepted Answer

Adam on 14 Dec 2016
You should never test equality between floating point numbers. There are any number of places you could search online to see the reasons for this. Many floating point numbers can not be represented to 100% accuracy and maths done on them will often introduce small inaccuracies so you should always test equality within a tolerance, not directly. The difference may only be 1e-16 and so basically equivalent to 0 for all sensible usage, but it will still fail an == test.

More Answers (2)

James Tursa
James Tursa on 14 Dec 2016
Edited: James Tursa on 14 Dec 2016
Already answered by others, but here is a detailed decimal conversion of what is going on with your particular example:
>> num2strexact(0.65)
ans =
>> num2strexact(0.05)
ans =
>> num2strexact(0.05*17)
ans =
>> num2strexact(0.65+0.05*17)
ans =
>> num2strexact(0.3)
ans =
>> num2strexact(0.05)
ans =
>> num2strexact(0.05*24)
ans =
>> num2strexact(0.3+0.05*24)
ans =
So, you got lucky in one case and unlucky in the other case. You can find num2strexact on the FEX here:

michio on 14 Dec 2016
Also please refer to "Compare Floating-Point Numbers" example of the doc page: Determine equality.
It's usually recommended to compare floating-point numbers using a tolerance, tol, instead of using ==.

Community Treasure Hunt

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

Start Hunting!