double/float precision question
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
>>>> float( 0.2222222222222222222222222222222)
Remove the leading quote from the first one, and you'll see that the two
numbers look pretty similar:
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)
We can see that floats have more precision than they display by default:
>>> x - 0.2222222222222222 == 0 # Sixteen of digit 2
>>> x - 0.222222222222222 # Fifteen of digit 2
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
> * 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
*All* floats contain mantissa and an exponent, but in binary, not decimal:
>>> 0.78720000000000001 * 2**-6
> Is there any means to obtain the full C double in Python
Floats in Python *are* C doubles.
More information about the Python-list