Mod in Java produces negative numbers
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. :)
Source: https://stackoverflow.com/a/25830153/2311557
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)