I have a simple C++ program compiled using gcc 4.2.4 on 32-bit Ubuntu 8.04. It has a for
-loop in which a double
variable is incremented from zero t
When using floating point values not every value is exactly representable, 0.95+0.05 > 1
because 0.95
is not exactly representable by a double
value.
See what Wikipedia has to say about floating point accuracy.
If you look at the IEEE floating point converter you'll see that the value of 0.95
in 64 bit floating point (double
) is 0-01111111110-1110011001100110011001100110011001100110011001100110
by entering this in a floating point calculator you get the value is 0.95000016
and adding 0.05
to that takes you over the 1.0
mark.
This is why you should never use floating points in loops (or more generally compare the result of floating point calculation to an exact value).