# double/float precision question

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Apr 1 23:34:40 CEST 2009

```On Wed, 01 Apr 2009 19:13:33 +0200, TP wrote:

> Hi everybody,
>
> Try the following python statements:
>
>>>> "%.40f" % 0.2222222222222222222222222222222
> '0.2222222222222222098864108374982606619596'
>>>> float( 0.2222222222222222222222222222222)
> 0.22222222222222221

Remove the leading quote from the first one, and you'll see that the two
numbers look pretty similar:

0.2222222222222222098864108374982606619596
0.22222222222222221

By the way, calling float(0.2222...2) is redundant, because 0.222...2 is
already a float. Calling float again just wastes CPU cycles, because the
same object is returned again.

>>> x = 0.2222222222222222222222222222222222
>>> x is float(x)  # check for object identity (same memory address)
True

We can see that floats have more precision than they display by default:

>>> x
0.22222222222222221
>>> x - 0.2222222222222222 == 0  # Sixteen of digit 2
True
>>> x - 0.222222222222222  # Fifteen of digit 2
2.2204460492503131e-16

Notice that doing this reveals more significant digits than were apparent
from just printing x.

> My problem is the following:
> * the precision "40" (for example) is given by the user, not by the
> programmer.
> * I want to use the string conversion facility with specifier "e", that
> yields number is scientific format; so I cannot apply float() on the
> result of "%.40e" % 0.2222222222222222222222222222222, I would lost the
> scientific format.

No, this is confused. The float you create is the exact same object
whether you use scientific format or not.

>>> a = 0.0123
>>> b = 1.23e-2
>>> a == b
True
>>> a
0.0123
>>> b
0.0123

*All* floats contain mantissa and an exponent, but in binary, not decimal:

>>> math.frexp(a)
(0.78720000000000001, -6)
>>> 0.78720000000000001 * 2**-6
0.0123

> Is there any means to obtain the full C double in Python

Floats in Python *are* C doubles.

--
Steven

```

More information about the Python-list mailing list