Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do integer div and mod round towards zero?

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.

like image 778
maaartinus Avatar asked Apr 15 '11 21:04

maaartinus


1 Answers

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.

like image 65
Oliver Charlesworth Avatar answered Sep 28 '22 16:09

Oliver Charlesworth