'Integer division in Python
I'm confused about the following integer math in python:
-7/3 = -3
since (-3)*3 = -9 < -7
. I understand.
7/-3 = -3
I don't get how this is defined. (-3)*(-3) = 9 > 7
. In my opinion, it should be -2, because (-3)*(-2) = 6 < 7
.
How does this work?
Solution 1:[1]
From the documentation:
For (plain or long) integer division, the result is an integer. The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0.
The rounding towards -inf
explains the behaviour that you're seeing.
Solution 2:[2]
This is how it works:
int(x)/int(y) == math.floor(float(x)/float(y))
Solution 3:[3]
Expanding on the answers from aix and robert.
The best way to think of this is in terms of rounding down (towards minus infinity) the floating point result:
-7/3 = floor(-2.33) = -3
7/-3 = floor(-2.33) = -3
Solution 4:[4]
Python rounds down. 7/3 = 2 (2+1/3) -7/3 = -3 (-2+1/3)
Solution 5:[5]
/ is used for floating point division // is used for integer division(returns a whole number)
And python rounds the result down
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | NPE |
Solution 2 | robert |
Solution 3 | amicitas |
Solution 4 | Rhand |
Solution 5 | BattleDrum |