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?
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
andd
that are integers after binary numeric promotion (§5.6.2) is an integer valueq
whose magnitude is as large as possible while satisfying|d ⋅ q| ≤ |n|
. Moreover, q is positive when|n| ≥ |d|
andn
andd
have the same sign, butq
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 toa
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With