MATLAB: 1.1 + 0.1 == 1.2 returns false

bugdouble precisionfloating pointnot a bug

Very strange.
Apparently this is related to the precision of the double type as
1.1 + 0.1 - 1.2 = 2.2204e-16
What can I do to counter this behavior? Thanks!

Best Answer

See the FAQ: http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F It has strategies to deal with this situation, such as comparing the value to a tolerance.
% instead of a == b
% use:
areEssentiallyEqual = abs(a-b) < tol
% for some small value of tol relative to a and b
% perhaps defined using eps(a) and/or eps(b)