They are not interchangeable. There are some subtle differences.
The differences depend on the size and types of the values and the version of Python.
Internally, Python has two different concepts of division: floor division (floordiv) and true division (truediv). Floor division returns the quotient of the division. True division returns the "as accurate as possible" result.
The
//
operator is always floor division in all versions of Python. In Python 2,
/
can be either floor division or true division. It depends on the types of the arguments. In Python 3,
/
is always true division.
Here are some examples showing the differences.
Python 2
>>> from operator import floordiv, truediv
>>> from math import floor
>>> repr(floordiv(10,3)); repr(truediv(10,3)); repr(10//3); repr(10/3);floor(10/3)
'3'
'3.3333333333333335'
'3'
'3'
3.0
>>> repr(floordiv(10.0,3)); repr(truediv(10.0,3)); repr(10.0//3); repr(10.0/3);floor(10.0/3)
'3.0'
'3.3333333333333335'
'3.0'
'3.3333333333333335'
3.0
Python 3
>>> from operator import floordiv, truediv
>>> from math import floor
>>> repr(floordiv(10,3)); repr(truediv(10,3)); repr(10//3); repr(10/3);floor(10/3)
'3'
'3.3333333333333335'
'3'
'3.3333333333333335'
3
>>> repr(floordiv(10.0,3)); repr(truediv(10.0,3)); repr(10.0//3); repr(10.0/3);floor(10.0/3)
'3.0'
'3.3333333333333335'
'3.0'
'3.3333333333333335'
3
Here is an example where it is not true:
>>> floor(10**200/10**100) == 10**100
False
>>> 10**200//10**100 == 10**100
True
What is actually happening behind the scenes?
Let's define
FLOOR
as follows:
- If the argument to
FLOOR
is an integer, it returns that integer unchanged.
- If the argument to
FLOOR
is a float, then it returns a float equal to the mathematical floor of the argument.
Let's assume
a
and
b
are integers.
In Python 2,
math.floor(a/b)
is equivalent to
FLOOR(float(floordiv(a,b)))
.
In Python 3,
math.floor(a/b)
is equivalent to
int(FLOOR(truediv(a,b)))
.
In both versions,
a/b
is converted to float; either after the
floordiv
or during the
truediv
. Python 2 returns a float so you can recognize that the conversion has occurred. Python 3 always returns an integer. The result can give an artificial sense of accuracy. The conversion to float limit the accuracy of
math.floor(a/b)
to a maximum of 53 bits while
a//b
uses arbitrary precision integer arithmetic and is always 100% accurate.
Summary
If you are working with integers and want integer results for division, use
//
on both Python 2 and 3. And beware of implicit conversions to float in the math module.
casevh