[Numpy-discussion] problem with float64's str()
Bruce Southey
bsouthey at gmail.com
Fri Apr 4 10:55:13 EDT 2008
Hi,
Note that at least under Python 2.5.1:
>>> a=0.0012
>>> a
0.0011999999999999999
>>> str(a)
'0.0012'
>>> repr(a)
'0.0011999999999999999'
From Python docs, repr(): 'Return a string containing a printable
representation of an object' and str(): 'Return a nice string
representation of the object'. In this case the object is a Python
float that approximates the base 10 number of 0.0012. This is not
equivalent to convert the base 10 number 0.0012 to a string because
computer numbers are base 2. Thus, repr() converts a Python object into
a string but nothing about the numerical precision whereas str() tries
to do something about maing a 'nice string'.
The only consistent way to get 0.0012 (or any number that can not be
represented exactly) is to use a Python object that stores 0.0012
exactly. For example, the Decimal module was introduced in Python 2.4:
http://www.python.org/doc/2.5/lib/module-decimal.html
>>> str(Decimal('0.0012'))
'0.0012'
>>> float(Decimal('0.0012'))
0.0011999999999999999
Also, see PEP 3141 'A Type Hierarchy for Numbers'
(http://www.python.org/dev/peps/pep-3141/).
Regards
Bruce
Dag Sverre Seljebotn wrote:
> Bruce Southey wrote:
>
>> Hi,
>> This topic has come up many times and the only problem is the lack of
>> understanding how computers store numbers and computer numerical precision.
>>
>> The NumPy output is consistent with Python on my x86_64 linux system
>> with Python 2.5.1:
>> >>> a=0.0012
>> >>> a
>> 0.0011999999999999999
>>
>>
> Wasn't this discussion about the repr vs. str functions?
>
> >>> repr(0.0012)
> '0.0011999999999999999'
> >>> str(0.0012)
> '0.0012'
>
>
>
> Dag Sverre
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion at scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>
>
More information about the NumPy-Discussion
mailing list