For example, using IEEE-754 32-bit binary floating points, let's represent the value of 1 / 3
. It cannot be done exactly, but 0x3eaaaaab
produces the closest value to 1 / 3
. You might want to write the value in decimal, and let the compiler to convert the decimal literal to a binary floating point number.
0.333333f -> 0x3eaaaa9f (0.333332986)
0.3333333f -> 0x3eaaaaaa (0.333333313)
0.33333333f -> 0x3eaaaaab (0.333333343)
0.333333333f -> 0x3eaaaaab (0.333333343)
You can see that 8 (significant) decimal digits is enough to represent the value as correct as possible (closest to the actual value).
I tested with π and e (base of the natural log), and both needed 8 decimal digits for the correctest.
3.14159f -> 0x40490fd0 (3.14159012)
3.141593f -> 0x40490fdc (3.14159298)
3.1415927f -> 0x40490fdb (3.14159274)
3.14159265f -> 0x40490fdb (3.14159274)
2.71828f -> 0x402df84d (2.71828008)
2.718282f -> 0x402df855 (2.71828198)
2.7182818f -> 0x402df854 (2.71828175)
2.71828183f -> 0x402df854 (2.71828175)
However, √2
appears to need 9 digits.
1.41421f -> 0x3fb504d5 (1.41420996)
1.414214f -> 0x3fb504f7 (1.41421402)
1.4142136f -> 0x3fb504f4 (1.41421366)
1.41421356f -> 0x3fb504f3 (1.41421354)
1.414213562f -> 0x3fb504f3 (1.41421354)
https://godbolt.org/z/W5vEcs695
Looking at these results, it's probably right that a decimal floating-point literal with 9 significant digits is sufficient to produce a most correct 32-bit binary floating point value, and in practice something like 12~15 digits would work for sure if space for storing the extra digits doesn't matter.
But I'm interested in the math behind it. How can one be sure that 9 digits is enough in this case? What about double
or even arbitrary precision, is there a simple formula to derive the number of digits needed?
The current answers and the links in the comments confirm that 9
digits is enough for most cases, but I've found a counterexample where 9
digits is not enough. In fact, infinite precision in the decimal format is required to be always correctly converted (rounded to the closest) to some binary floating point format (IEEE-754 binary32 floats for the discussion).
8388609.499
represented with 9
significant decimal digits is 8388609.50
. This number converted to float
has the value of 8388610
. On the other hand, the number represented with 10
or more digits will always preserve the original value, and this number converted to float
has the value 8388609
.
You can see 8388609.499
needs more than 9
digits to be most accurately converted to float
. There are infinitely many such numbers, placed very close to the half point of two representable values in the binary float format.
float
having about 7 digits accuracy, any value > 9999999 has zero accuracy in its decimal places. If you want the mentioned 12~15 digits accuracy, usedouble
.float
, ever (it isn't 1980 any more) unless you have a very good reason why you need to usefloat
.float
. Use%a
if you want to round-trip.