When I calculate int i = -1 % 2
I get -1
in Java. In Python, I get 1
as the result of -1 % 2
.
What do I have to do to get the same behavior in Java with the modulo function?
5 Answers
The problem here is that in Python the % operator returns the modulus and in Java it returns the remainder. These functions give the same values for positive arguments, but the modulus always returns positive results for negative input, whereas the remainder may give negative results. There's some more information about it in this question.
You can find the positive value by doing this:
int i = (((-1 % 2) + 2) % 2)
or this:
int i = -1 % 2;
if (i<0) i += 2;
(obviously -1 or 2 can be whatever you want the numerator or denominator to be)
-
2
-
1
-
5@Cachapa please provide an example to support that statement. I believe the OP's solution is general already, consider that
(((-3 % 4) + 4) % 4) = 1
(the intended result) and also that(((3 % 4) + 4) % 4) = 3
(also the intended result). It works with both positive and negative dividends.– The111Commented Jan 5, 2013 at 8:54 -
2@The111 Imagine the range of your integer is [-8, 7], (((5 % 6) + 6) % 6) = ((5 + 6) % 6) = (-5 % 6) = -5, but 5 % 6 is supposed to be positive. Substitute appropriately large numbers for 32 bit ints like 536887296 and 1610612736 and it is clear the second method is the better one. Commented Jan 2, 2014 at 20:23
-
4@pgreze imagine the case where
n=-1000
andm=3
, the correct answer would be2
, but in your formula the answer is still negative. Commented Sep 26, 2018 at 11:17
Since Java 8 you can use the Math.floorMod() method:
Math.floorMod(-1, 2); //== 1
Note: If the modulo-value (here 2
) is negative, all output values will be negative too. :)
-
Splendid answer, of course you can then call
Math.abs()
on the output ofMath.floorMod()
to guarantee that the result is always non negative.– rdxdkrCommented Apr 14 at 19:15
if b > 0:
int mod = (mod = a % b) < 0 ? a + b : a;
Doesn't use the %
operator twice.
-
How does the speed of this compare to the version with two % operators? Commented Jan 8, 2017 at 15:18
-
That's a good question. I perform a lot of premature optimization. I assume it saves a couple of CPU cycles.– DicoCommented Jan 9, 2017 at 17:26
-
1@Dice : If you make a good case that this solution is better than the currently accepted solution, that would be valuable for people who browse this question. Commented Jan 10, 2017 at 13:27
-
2Whether an
if
is faster than a%
depends on your CPU and the data you feed it, due to branch prediction--if
s are faster if the condition has a predictable pattern.– VitruvieCommented Jun 23, 2017 at 21:37 -
2This is almost certainly slower because it has a branch, unless you know that the input will mostly be positive. If its random, then the branch prediction penalty will cost more clock cycles than an extra remainder calculation on most CPUs. Or, if you want to conditionally add a value based on whether an int is negative or not, try
(maybeNegative >> 31) ^ thingToMaybeAdd + thingToAddTo
Commented Sep 28, 2018 at 17:26
If you need n % m
then:
int i = (n < 0) ? (m - (abs(n) % m) ) %m : (n % m);
mathematical explanation:
n = -1 * abs(n)
-> n % m = (-1 * abs(n) ) % m
-> (-1 * (abs(n) % m) ) % m
-> m - (abs(n) % m))
-
This expression didn't work for me. For negative values I was getting values between 1:m instead of the expected 0:m-1, as in the case where n is positive. The solution from andrewmu functioned as expected.– CachapaCommented Dec 16, 2012 at 13:42
If the modulus is a power of 2 then you can use a bitmask:
int i = -1 & ~-2; // -1 MOD 2 is 1
By comparison the Pascal language provides two operators; REM takes the sign of the numerator (x REM y
is x - (x DIV y) * y
where x DIV y
is TRUNC(x / y)
) and MOD requires a positive denominator and returns a positive result.
%
operator as producing the remainder, but names it the modulus operator. Confusingly, en.wikipedia.org/wiki/Modulo_operation says that the modulo operation produces the remainder, both in computing and in mathematics... but also claims "The range of numbers for an integer modulo of n is 0 to n − 1."!