floating point in 2.0

Paul Boddie paul at boddie.net
Tue Jun 5 04:45:39 EDT 2001


msoulier at storm.ca (Michael P. Soulier) wrote in message news:<WlYS6.134798$eK2.32222284 at news4.rdc1.on.home.com>...
> Greetings people. 
> 
>     My apologies if this has been covered. 
> 
>     In Python 1.5.2, I could do this:
> 
> good = (0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0)
> 
>     I could then get back exactly this when I output the value of "good".

Yes, but what was actually stored was what you see now, at least when
you ask about it at Python's interactive prompt. Python was doing some
rounding in the *output* of your stored numbers, I believe.

> However, with Python 2.0, I get this:
> 
> >>> good
> (0.0, 0.10000000000000001, 0.20000000000000001, 0.29999999999999999,
> 0.40000000000000002, 0.5, 0.59999999999999998, 0.69999999999999996,
> 0.80000000000000004, 0.90000000000000002, 1.0)
> 
>     Now, I'm assuming that this has something to do with the way that Python
> 2.0 stores floating-point numbers, but this could get confusing during
> debugging.

It's really the way that floating point numbers are stored on any
particular platform, although such a naive statement needs
clarification that I am not prepared to give. ;-)

>     Could someone explain this behaviour?

Floating point numbers are stored in such a way that not all decimal
numbers can be represented exactly and, as you can see from your test,
certain numbers come out "all weird". It's a bit like 1/3 not being
representable exactly in the decimal number system within a finite
number of digits: it comes out as 0.3333... Of course, someone will
undoubtedly correct me, but that is a reasonable way of thinking about
this kind of situation.

Take a look at Python 2.0's release notes on http://www.python.org for
more information. The big change was in the built-in 'repr' function.
Basically, the formatting of numbers was changed in 'repr' between
1.5.2 and 2.0.

Regards,

Paul



More information about the Python-list mailing list