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.
It is not true in Python 3, and you can test it for yourself:
Integer division and modulo of
aandbgivingq(quotient) andr(remainder) respectively will always return numbers that satisfyb*q + r == aand(a*b)>0 == q>0(i.e.a*bandqhave the same sign) andabs(r) < abs(q). The expressionint(q)simply always rounds towards 0 ifqis a floating point number.It will always be true for Python 2 unless you do
from __future__ import division, but that’s becausea/b == a//bifaandbare integers in Python 2.