Python can't divide??!?!

Dan Bishop danb_83 at yahoo.com
Thu Feb 5 22:05:05 EST 2004


"Dan Williams" <dan at ithium.net> wrote in message news:<mailman.1252.1076003166.12720.python-list at python.org>...
> Ummmm...
> 
> This is weird. Sorry if it's known about (how can it NOT be, I wonder?) but
> I haven't seen any reference to it anywhere.

Then you haven't been looking hard enough.
 
> I'm running the latest Python (2.3.3) on Windows XP Pro, i386 architecture.
> 
> Fire up python or whatever.
> 
> Do this:     Result:
> 
> 3 / 5        0                       Fair enough, int / int = int

This is for bug-compatibility with old versions of Python.  It is
strongly recommended that all new Python scripts use "from __future__
import division".

> 3 / 5.0      0.59999999999999998     eh?
> 3.0 / 3      0.59999999999999998     ummmm...
> 3.0 / 5.0    0.59999999999999998     how did I guess...

It makes perfect sense when you remember that computers do math in
binary.  In binary, 3/5 is equal to 0.1 0011 0011 0011 0011 0011
0011..., which is rounded to (C99 notation) 0x1.33333333333333333p-1. 
The exact decimal equivalent of this is
0.59999999999999997779553950749686919152736663818359375.  In the
default 17 significant digits format, this rounds to
0.59999999999999998.

> That's just an example. Python cannot divide. Period.

It's off by only 37 parts per quintillion.

> If you try 1.0 / 3 you get 0.33333333333333331,

More precisely, you get 0x1.5555555555555p-2, or
0.333333333333333314829616256247390992939472198486328125.

> and from this, the above example, and a few tests,
> I speculate that *something* is subtracting 2 from the last digit *after*
> the division is done.

*Nothing* is subtracting from the last digit because your floating
part hardware has no concept of decimal digits, only bits.
 
> Now, is this just me, or can someone else duplicate it?

Everyone in the world who has binary floating part hardware can
duplicate it, whether they're using Python or not.



More information about the Python-list mailing list