While working on a little game in Python with PyGame, I stumbled upon a feature of the language which caught me by surprise.
In other languages, like C for example, when you divide an integer the result is truncated to give an integer result. That is, the part after the decimal point is chopped off. For example, 10 / 3 is 3.333333... An integer division will chop the decimal part off the end and give the result as 3. Similarly -10 / 3 is -3.333333... and in C, dividing the int -10 by the int -3 will give the answer -3. Divide it, chop off the decimal places, easy.
Python's integer division works in a subtly different way, however. In Python, integer division returns the floor of the result. That is, it rounds it down to the nearest integer. For 10 / 3, this still gives the answer 31. Where it differs is when we divide negative numbers. For example, it means that for -10 / 3 we get -4. If this doesn't immediately make sense, take a look at it visualised on a number line:
-3.333333... 3.333333...
| |
-4 V-3 -2 -1 0 1 2 3 V 4
-----|---+-|-----|-----|-----|-----|-----|-----|-+---|-----
|<--- |<-
round down round down
10 / 3 is 3.333333... and the next lowest integer is 3. Similarly -10 / 3 is -3.333333 and the next lowest integer is -4. This still catches me out from time to time, but I guess it sort of makes sense when you think about it.
It's worth noting that in Python 3, the '/' operator always performs float division. You should use the '//' operator to do an integer division.↩
Comments
Hi Mr. Frimston:
Nice explanation of Python(3)integer division with a negative number. It makes sense to me. Wonder if you could give an equally clear explanation of %. I understand why 17 % 10 -> 7 but why does -17 % 10 -> 3 or 17 % -10 -> -3?
I thank you in advance.
Dave P.
Hi Dave, thanks for your kind feedback :)
The modulus operator behaves this way for the same reason, as it gives the remainder after integer division.
17 / 10 is 1.7, the next lowest integer being 1. But 1 * 10 is actually 10, so the remaining difference is 7.
-17 / 10 is -1.7, the next lowest integer being -2. But -2 * 10 is actually -20, so the remaining difference is 3.
17 / -10 is -1.7, the next lowest integer being -2. But -2 * -10 is actually 20, so the remaining difference is -3.
Hope that helps!
your_ip_is_blacklisted_by sbl.spamhaus.org