C ++ double / floating internal representation

I can’t understand why C ++ division behaves the way it does. I have a simple program that divides 1 by 10 (using VS 2003)

double dResult = 0.0; dResult = 1.0/10.0; 

I expect dResult to be 0.1, but I get 0.10000000000000001

  • Why am I getting this value, what is the problem with the internal double / float representation
  • How can I get the correct value?

Thanks.

0
source share
3 answers

Since all, most modern processors use binary floating point, which cannot represent exactly 0.1 (there is no way to represent 0.1 as m * 2^e with integer m and e ).

If you want to see the "correct value", you can print it, for example:

 printf("%.1f\n", dResult); 
+3
source

Doubles and floats are not identical to real numbers, because there are infinite values ​​for real numbers, but only a finite number of bits to represent them in double / float.

You can read: what every computer scientist needs to know about floating point arithmetic

+2
source

The ubiquitous floating point format IEEE754 expresses floating point numbers in the base of scientific notation 2 notes with a finite mantissa. Since a fraction like 1/5 (and therefore 1/10) has no representation with a finite number of digits in binary scientific notation, you cannot accurately represent the value 0.1. More generally, the only values ​​that can be represented exactly are those that exactly correspond to binary scientific notation with a mantissa of several (for example, 24 or 53 or 64) binary digits and a suitable small indicator.

+2
source

All Articles