Convert from double to unsigned int

I am having a problem converting a value from Double to int. I am trying to run the following code:

int main() { double val_d= 6.25e-05; cout << (1/val_d) << endl; unsigned int val_ui = (unsigned int ) (1/val_d); cout << val_ui << endl; } 

converting from double to int can remove the decimal part, but should the integer part remain like this?

The output I get is: 16000 15999

So why is o / p here? This only happens in Fedora. On windows and Ubuntu it works fine. (Both exits - 16000)

I modified the above code and got the following results:

 int main() { double val_d= 6.25e-05; cout << (1/val_d) << endl; double val_intermediate = (1/val_d) ; cout << val_intermediate << endl; unsigned int val_ui = (unsigned int ) val_intermediate; cout << val_ui << endl; } 

NEW OUTPUT 16000 16000 16000

+7
source share
3 answers

When the source text "6.25e-05" is interpreted as a decimal digit and converted to double, it is not accurately represented, since floating point values ​​have limited precision, and each bit has a value that is a force of two, not a decimal digit. The IEEE 754 double-precision value that is closest to 6.25e-5 is 6.25000000000000013010426069826053208089433610439300537109375e-05 or in hexadecimal floating point 0x1.0624dd2f1a9fcp-14.

When the converse is taken, the exact mathematical result is again not exactly representable, so it needs to be rounded up again. The closest double precision value is 16000 or 0x1.f4p + 13.

The C ++ standard allows implementations to evaluate floating point expressions with greater precision than the nominal type requires. Some implementations use advanced precision, in particular, the 80-bit version of Intel's floating point, which has 64-bit significance. (Regular double precision has 53-bit significance.) In this advanced precision, the inverse is 0xf.9ffffffffffff89p + 10 or 15999.99999999999966693309261245303787292949957275390625.

Obviously, when the result is truncated to an integer with extended precision, the result is 15999.

Rounding a double double result will result in 16000. (You can do this with an explicit cast to double, you do not need to assign an intermediate value to the double object.)

+15
source

difference in rounding .

  • (1 / val_d) - double is rounded to the nearest possible number , which can be represented with double precision; (e.g.: 3,6999999999999999 == 3.7)
  • (unsigned int) (1 / val_d) - when casting in int decimal, the part is truncated, which leads to rounding (for example: int (3.6) == 3
+6
source

Converting a floating point value to an integral value removes the fractional part if the result can be represented in an integral type (i.e. the value is not too large to match). Insertion into the stream of rounds a value that may lead to a different result.

+1
source

All Articles