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
A == B returns a logical array with elements set to logical 1 ( true ) where arrays A and B are equal; otherwise, the element is logical 0 ( false ). The test compares both real and imaginary parts of numeric arrays.
It is possible to have multiple MATLAB installations on the same computer. Be sure to install each version in a different directory.
It's used to compare two variables (numbers, arrays, etc.) and say whether they match or not. This is different than a single = sign, which is an assignment. In a==b you'll get a single true or false value, or an array of them if a and b are arrays.
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.
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""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With