Reading the documentation

Chris Angelico rosuav at gmail.com
Fri Aug 25 00:21:36 EDT 2017


On Fri, Aug 25, 2017 at 1:23 PM, Rustom Mody <rustompmody at gmail.com> wrote:
> Early in my python classes I show this:
>
> $ python
> Python 2.7.13 (default, Jan 19 2017, 14:48:08)
> [GCC 6.3.0 20170118] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> .1 + .1 == .2
> True
>>>> .1 + .1 + .1 == .3
> False
>>>>
> --
> https://mail.python.org/mailman/listinfo/python-list

Aside from the fact that I show it with Python 3 (or sometimes
Node.js) instead, I've demonstrated something similar - but then go on
to make the point that 0.1 is not "one tenth". The problem isn't with
addition, which is completely correct here; the problem is with the
assumption that writing "0.1" in your source code indicates the number
"one tenth". If you want the details, Python is very helpful here:

>>> "%d/%d" % (0.1).as_integer_ratio()
'3602879701896397/36028797018963968'
>>> "%d/%d" % (0.2).as_integer_ratio()
'3602879701896397/18014398509481984'
>>> "%d/%d" % (0.3).as_integer_ratio()
'5404319552844595/18014398509481984'

Or in hex:

>>> "%x/%x" % (0.1).as_integer_ratio()
'ccccccccccccd/80000000000000'
>>> "%x/%x" % (0.2).as_integer_ratio()
'ccccccccccccd/40000000000000'
>>> "%x/%x" % (0.3).as_integer_ratio()
'13333333333333/40000000000000'


Clearly the second one is exactly double the first. And equally
clearly, the first two have been rounded up, while the second is
rounded down. But you don't need that much detail to understand what's
going on; most people can follow this analogy:

0.6667 + 0.6667 + 0.6667 != 2.000

since, in grade school, most of us learned that the decimal expansion
for two-thirds gets rounded up. It's the same thing, just in binary.

In fact, the ONLY way to create this confusion is to use (some
derivative of) one fifth, which is a factor of base 10 but not of base
2. Any other fraction will either terminate in both bases (eg "0.125"
in decimal or "0.001" in binary), or repeat in both (any denominator
with any other prime number in it). No other rational numbers can
produce this apparently-irrational behaviour, pun intended.

ChrisA



More information about the Python-list mailing list