Integer division: Results are language-specific

about | archive

[ 2012-December-28 09:02 ]

Today I was surprised to discover that integer division with negative numbers produces different results for different programming languages. I was doing some calculation in Python, and was surprised to see that -5 / 3 == -2. I was expecting it to be -1 (as in Java, and C). It turns out there are multiple ways of handling the case where the division of integers produces a real number (i.e. when the dividend is not an exact multiple of the divisor). There are only two variants used in the programming languages I care about. For computing q = D / d:

Example outputs for ±5 / ±3 and ±5 % ±3:

Truncated (C)Floored (Python)
5 /  3 12 12
-5 /  3 -1-2 -21
5 / -3 -12 -2-1
-5 / -3 1-2 1-2

Basically, mathematicians prefer the properties of floored division over truncated division, and hence the "mathy" languages use it. Personally, I am more familiar with truncated division and prefer it. I find it less surprising since changing the signs of the inputs only changes the signs of the outputs, whereas with floored division, changing the signs of the inputs can change the absolute values of the outputs. But I am not a mathematician, so I don't really understand the differences.

For an in-depth yet easily understood discussion of this issue, I recommend reading "Division and Modulus for Computer Scientists." Wikipedia's Modulo operator article is also useful.