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.