There are various trade-offs with the different kinds of rounding in integer division. And as Jake McArthur mentioned, this is not the only ones. For example, there's also rounding to the nearest integer.
Another consideration is that integer division and remainder go hand-in-hand. The quotient * divisor + remainder = dividend
law holds. So different types of division rounding will produce different types of remainder. For example:
- Division rounding towards zero, produces a remainder that always has the same sign as the dividend. For example, in C and Java,
(-5) % 3 = -2
(because (-5) / 3 = -1
, and (-1) * 3 + (-2) = -5
); whereas 5 % (-3) = 2
(because 5 / (-3) = -1
, and (-1) * (-3) + 2 = 5
).
- Division rounding towards negative infinity, produces a remainder that always has the same sign as the divisor. For example, in Python and Ruby,
(-5) % 3 = 1
(because (-5) / 3 = -2
, and (-2) * 3 + 1 = -5
); whereas 5 % (-3) = -1
(because 5 / (-3) = -2
, and (-2) * (-3) + (-1) = 5
).
- Division rounding towards the nearest integer, produces a remainder (out of the two possible ones) that is the smallest (closest to zero).
Having a remainder with the same sign as the divisor is often the most useful in math and computer science. One often needs to compute the remainder with a fixed divisor. For example, x % 2
. In languages where the remainder has the sign of the dividend, like C and Java, this expression could evaluate to -1, 0, or 1, depending on x
. However, in languages where the remainder has the sign of the divisor, like Python and Ruby, this expression could only evaluate to 0 (if even) or 1 (if odd). This is probably much more in line with what is intended.
I believe that many processor architectures, including the x86 architecture, contains an instruction for integer division that rounds towards zero. So it may be more efficient to compute this on most computers. I am not sure if there is an instruction for integer division that rounds towards negative infinity.