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.
Integer division is division in which the fractional part (remainder) is discarded is called integer division and is sometimes denoted .
The result of integer division is always an integer. Integer division determines how many times one integer goes into another. The remainder after integer division is simply dropped, no matter how big it is.
Integer division ( // ) The integer division operation // is used when you want your answer to be in whole numbers. Since it is very common for the result of dividing two integers to be a decimal value, in Python3 integers, division rounds the result to the lower bound.
In Python, there are two kinds of division: integer division and float division. Integer division returns the floor of the division. That is, the values after the decimal point are discarded. It is written as '//' in Python 3.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With