Is this a Matlab bug? Do you have the same issue? [duplicate]
My Matlab version is R2012a
Why in Matlab 1.1-0.2 is not equal to 0.9!!!!!?
This is awful!
>>1.1-0.2 == 0.9
ans =
0
Solution 1:
It is not a Matlab issue; it is a floating point issue. You'll get the same result in C++ (or any programming language that conforms to IEEE754 for that matter):
#include <iostream>
int main(int, char **) {
std::cout << (1.1-0.2==0.9) << std::endl;
return 0;
}
output:
0
This is because 1.1 and 0.9 cannot be represented exactly in binary. It's like expressing 1/3 in decimal: you'll have to write
0.33333333333333333333333333333333333333333333333...
and continue indefinitely. But no matter how long you continue, you'll never get it right.
In floating point, you only have so many digits you can store, so the calculation will have to stop somewhere. The result of the calculation is actually
>> 1.1-0.2
ans =
9.000000000000001e-01
which is pretty close, but not quite correct.
Because of this, you should always think twice before using ==
to compare two floating-point numbers; it is rare that the ==
operator can be applied without some "strange" consequences like the one you just encountered.
It is better to use a round-off specific tolerance, like
abs(1.1-0.2 - 0.9) <= eps(0.9)
where eps
is a Matlab function which returns the spacing-between-doubles for a specific double value. But really, this is not a catch-all-end-all solution; correctly comparing floating points is a tricky business.
Solution 2:
http://matlab.wikia.com/wiki/FAQ#Why_is_0.3-0.2-0.1_not_equal_to_zero_.28or_similar.29.3F
Scroll to "Why is 0.3 - 0.2 - 0.1 (or similar) not equal to zero?"
"Some floating point numbers can not be represented exactly in binary form....If you're trying to compare two floating-point numbers, be very careful about using == to do so. An alternate comparison method is to check if the two numbers you're comparing are "close enough""
Solution 3:
A good function to use for these sorts of things to see what is going on is num2strexact
from file exchange
num2strexact(1.1-0.2)
0.9000000000000001332267629550187848508358001708984375
num2strexact(0.9)
0.90000000000000002220446049250313080847263336181640625
You see, they are not the same.
Look at the different when using double vs. syms
num2strexact((1.1-0.2)-0.9)
1.1102230246251565404236316680908203125e-16
sym('(1.1-0.2)-0.9')
1.8367099231598242312011508394098e-40