Unlike in C, in Java is the result of x/y and x%y well-defined even for negative operands. Surprisingly, it's defined by rounding towards zero, and not by rounding down (i.e., towards negative infinity). Does anybody have taken any advantage of this definition?
In most cases I just don't care, but sometimes I had to work around this, e.g., when computing an index using modulo array.length.
This is no rant, I'm really interested if there are uses for this definition.
3 Answers 3
It's easier to implement a division routine if you can round toward zero. Often, a division involving a negative is sign-flipped, and then the division carried out on a positive equivalent, and then the answer flipped back again. So the effect is naturally going to be round toward zero.
2 Comments
Here's one example where it's useful, however slightly:
maxPage = (rows.length - 1) / ROWS_PER_PAGE
(No need to special case for maxPage = 0 when rows.length = 0, assuming ROWS_PER_PAGE > 1.)
Comments
The problem with division of two integers is that the result may be a non-integer. This is opposed to the three other standard arithmetic operators (+,-,*). So you have to resolve this.
There are multiple ways to do this (truncation / round towards zero, floor/ceil division, Euclidean division). From a mathematical point of view, floor division or the closely related Euclidean division seem the most useful.
However, a big drawback of floor division is that it "behaves" less as the real-numbered division operation. In particular, arithmetic rewriting rules allow one to reorder divisions and multiplications. E.g., -(x/y) is the same as (-x)/y or x/(-y) for real-numbered division. Floor division does not have this property: -(1/2) is not the same as (-1)/2, as the former yields 0 and the latter -1. Division that rounds towards zero does preserve this reordering property, allowing greater freedom to apply classic arithmetic rewriting rules.
-(x/y) == -x/y == y/-x == -(-x/-y)%is rem(ainder) not mod(ulo). In C integer division involving negative was originally implementation-defined and in practice whatever the hardware did, but since 1999 the standard has required toward-zero. FORTRAN has required toward-zero since 1977 at least, and AIUI was similarly based on early hardware. Though a language can choose to be different than hardware; python does.