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. ↩