1. b.93z.org
  2. Notes

Number division in Python

We all know about PEP 238, but forget about it in some situations. Let’s recall what from __future__ import division does. In Python 2.7 code without mentioned compiler directive we have following behaviour:

int / int → int (1 / 2 = 0)
int // int → int (1 // 2 = 0)
int / float → float (1 / 2.0 = 0.5)
int // float → float (1 // 2.0 = 0.0)

But with it we have following (look at first line):

int / int → float (1 / 2 = 0.5)
int // int → int (1 // 2 = 0)
int / float → float (1 / 2.0 = 0.5)
int // float → float (1 // 2.0 = 0.0)

And here’s how Python 3.* version works:

int / int → float (1 / 2 = 0.5)
int // int → int (1 // 2 = 0)
int / float → float (1 / 2.0 = 0.5)
int // float → float (1 // 2.0 = 0.0)

As you can see, only first line changed when we turned on division compiler directive, and such behaviour matches one of Python 3.*.

Python 2.7:
int / int = int (1 / 2 = 0)
int // int = int (1 // 2 = 0)
int / float = float (1 / 2.0 = 0.5)
int // float = float (1 // 2.0 = 0.0)
Python 2.7 (__future__):
int / int = float (1 / 2 = 0.5)
int // int = int (1 // 2 = 0)
int / float = float (1 / 2.0 = 0.5)
int // float = float (1 // 2.0 = 0.0)
Python 3.2:
int / int = float (1 / 2 = 0.5)
int // int = int (1 // 2 = 0)
int / float = float (1 / 2.0 = 0.5)
int // float = float (1 // 2.0 = 0.0)

© 2008–2017 93z.org