The result of running the following code:
#include <cstdio>
//i define printBits elsewhere but that's not relevant to my question
void printBits(const float f);
void printBits(const double f);
int main(int argc, char **argv) {
float f=4.2;
double d=4.2;
printf("float: %20.20f\n",f);
printBits(f);
printf("double: %50.50f\n",d);
printBits(d);
return 0;
}
Is:
float: 4.19999980926513671875
0 10000001 00001100110011001100110
double: 4.20000000000000017763568394002504646778106689453125
0 10000000001 0000110011001100110011001100110011001100110011001101
Notice how I set both f
and d
to 4.2, but the float value is slightly less than 4.2 and the double value is slightly more than 4.2. I understand why the float value is less than 4.2; the 4.2 value gets truncated to a value ~2^-21 less than 4.2. However, I don't understand why the double value is slightly greater than 4.2. I thought that float and double values would just truncate, but it seems that the double value is rounding up rather than down.
In general, do floats and doubles round to the nearest representable value? Do floats and doubles round differently? I've tried searching for this but couldn't find anything relevant.