Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: why 7 / -3 is -2?

Tags:

java

division

Why in java 7 / -3 isn't -3? It is -2. I was thinking the result of division is rounded down. In python 2 it is -3. Is there any other rule for division in java?

like image 504
roman-v1 Avatar asked Dec 08 '22 06:12

roman-v1


1 Answers

Is there any other rule for division in java?

As always, for questions like this you should go to the Java Language Specification. In this case, the relevant section is 15.17.2:

Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d ⋅ q| ≤ |n|. Moreover, q is positive when |n| ≥ |d| and n and d have the same sign, but q is negative when |n| ≥ |d| and n and d have opposite signs.

Note that this "rounding" isn't "midpoint rounding" as you might otherwise expect: -99/50 is -1, for example. Effectively it's truncation towards 0.

As for why Java chose to use this approach and Python chose to round down instead, that's something you'd probably need to ask the language designers. Each option is useful in some cases and a pain in others. You may well find that the remainder operator works differently in Python too - the two decisions are often linked, such that (from section 15.17.3):

The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a.

like image 171
Jon Skeet Avatar answered Dec 24 '22 10:12

Jon Skeet