Integer division: is a//b == int(a/b) true for all integers a,b?
-
06-07-2021 - |
Question
I know that integer division will always return the same answer as truncation of a floating point result if the numbers are both positive. Is it true if one or both of them are negative?
I was just curious to know if there was an integer division expression that would return the same results in Python 2 and Python 3 (and yes, I know about from __future__ import division
).
P.S. Let's ignore floating point overflow for the moment.
Solution
It is not true in Python 3, and you can test it for yourself:
>>> int(-1/3) == -1//3
False
Integer division and modulo of a
and b
giving q
(quotient) and r
(remainder) respectively will always return numbers that satisfy b*q + r == a
and (a*b)>0 == q>0
(i.e. a*b
and q
have the same sign) and abs(r) < abs(q)
. The expression int(q)
simply always rounds towards 0 if q
is a floating point number.
It will always be true for Python 2 unless you do from __future__ import division
, but that's because a/b == a//b
if a
and b
are integers in Python 2.