float / rounding question

Piet van Oostrum piet at cs.uu.nl
Mon Mar 10 11:24:56 EDT 2008


>>>>> Dennis Lee Bieber <wlfraed at ix.netcom.com> (DLB) wrote:

>DLB> On Fri, 07 Mar 2008 23:12:27 +0100, Piet van Oostrum <piet at cs.uu.nl>
>DLB> declaimed the following in comp.lang.python:


>>> Sorry to come in so late in this discussion. Although it is correct to say
>>> that many real numbers that have an exact decimal representation cannot be
>>> exactly represented in binary, that is no excuse to print 53.6 as
>>> 53.600000000000001. This is just lousy printing and the fact that this kind
>>> of question comes up every week shows that it is confusing to many people.
>>> 
>>>>> 53.6
>DLB> 53.600000000000001
>>>>> print 53.6
>DLB> 53.6
>>>>> print str(53.6)
>DLB> 53.6
>>>>> print repr(53.6)
>DLB> 53.600000000000001
>>>>> 

>DLB> 	Looks like "print" already does what you expect.

No, what you see is not the behaviour of `print' but of `str'. `print' uses
`str' to do the formatting instead of `repr' whereas the interactive prompt
uses `str'. `str' is meant to please the human reader, and `repr' is
supposed to give you something that you can use as input and get exactly
the same value. But `str' does it by just giving you less accuracy, thus
sweeping the problem under the carpet:

>>> str(53.59999999999)
53.6

>>> 53.59999999999==53.6
False

>>> repr(53.59999999999)
'53.599999999989997'

>>> 53.599999999989997==53.59999999999
True

>>> repr(53.6)
'53.600000000000001'

>>> 53.600000000000001==53.6
True

-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list