简体   繁体   中英

C++ not truncating doubles?

My code :

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.

Floating point values are not truncated , they're rounded to the nearest representable value. You've discovered an interesting example where the rounding goes in a different direction depending on the size of the floating point, but this is not uncommon; you can expect the rounding to go up about 50% of the time and down 50% of the time, with some small number of values being exactly representable and not rounded at all. For example 4.25 would be exact.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM