5

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.

maaartinus
  • 44,714
  • 32
  • 161
  • 320
  • that's how it's done in the hardware. one small thing, try to keep you array.length a power of 2 and use &(array.length-1) – bestsss Apr 15 '11 at 21:50

2 Answers2

6

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.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • That's true, however, such a definition is a common source of errors and doing it otherwise would not be that expensive. I still wonder if there's anybody having taken any advantage of this (strange but standard) definition? – maaartinus Apr 21 '11 at 20:49
  • 1
    @maaartinus: The first thing that comes to mind is that round-toward-zero will give unbiased quantization error (assuming data is evenly distributed between +ve and -ve), whereas round-toward-minus-infinity will result in a bias. – Oliver Charlesworth Apr 21 '11 at 22:26
1

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

aij
  • 5,903
  • 3
  • 37
  • 41