Possible Duplicate:
Floating point comparison
I have some simple C code and the output seems to be unexpected, at least to me:
#include <stdio.h>
int main(void) {
float f1 = 1.0;
double f2 = 1.0;
if (f1 == f2)
puts("equal");
else
puts("unequal");
return 0;
}
Since float and double have different precision, I expected the output to be unequal but I instead get equal. Why is that the case?
Precision only matters when the number can’t be represented exactly. Since both floats and doubles (being IEEE 754 single and double precision values) can represent
1.0exactly, precision doesn’t come into it.1.0is basically a zero sign bit, all exponent bits except the highest set to 1, and no mantissa bits set. In single precision, that’s binary:and, for double precision:
Not all numbers are exactly representable in IEEE 754 – for example, the
1.1you mention in a comment is actually stored as1.100000023841858in single precision.Have a look at this answer for an example of decoding a floating point value.
Harald Schmidt’s online single-precision converter is an excellent site to play around with if you want to understand the formats. I liked it so much, I made a desktop version in case it ever disappeared (and was capable of doing double precision as well).