How does java do modulus calculations with negative numbers?
Am I doing modulus wrong? Because in Java -13 % 64
evaluates to -13
but I want to get 51开发者_如何学编程
.
Both definitions of modulus of negative numbers are in use - some languages use one definition and some the other.
If you want to get a negative number for negative inputs then you can use this:
int r = x % n;
if (r > 0 && x < 0)
{
r -= n;
}
Likewise if you were using a language that returns a negative number on a negative input and you would prefer positive:
int r = x % n;
if (r < 0)
{
r += n;
}
Since "mathematically" both are correct:
-13 % 64 = -13 (on modulus 64)
-13 % 64 = 51 (on modulus 64)
One of the options had to be chosen by Java language developers and they chose:
the sign of the result equals the sign of the dividend.
Says it in Java specs:
https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3
Are you sure you are working in Java? 'cause Java gives -13 % 64 = -13 as expected. The sign of dividend!
Note that this answer was for a previous, different version of the question.
Your result is wrong for Java. Please provide some context how you arrived at it (your program, implementation and version of Java).
From the Java Language Specification
15.17.3 Remainder Operator %
[...]
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.
15.17.2 Division Operator /
[...]
Integer division rounds toward 0.
Since / is rounded towards zero (resulting in zero), the result of % should be negative in this case.
you can use
(x % n) - (x < 0 ? n : 0);
Your answer is in wikipedia: modulo operation
It says, that in Java the sign on modulo operation is the same as that of dividend. and since we're talking about the rest of the division operation is just fine, that it returns -13 in your case, since -13/64 = 0. -13-0 = -13.
EDIT: Sorry, misunderstood your question...You're right, java should give -13. Can you provide more surrounding code?
Modulo arithmetic with negative operands is defined by the language designer, who might leave it to the language implementation, who might defer the definition to the CPU architecture.
I wasn't able to find a Java language definition.
Thanks Ishtar, Java Language Specification for the Remainder Operator % says that the sign of the result is the same as the sign of the numerator.
To overcome this, you could add 64
(or whatever your modulus base is) to the negative value until it is positive
int k = -13;
int modbase = 64;
while (k < 0) {
k += modbase;
}
int result = k % modbase;
The result will still be in the same equivalence class.
x = x + m = x - m
in modulus m
.
so -13 = -13 + 64
in modulus 64
and -13 = 51
in modulus 64
.
assume Z = X * d + r
, if 0 < r < X
then in division Z/X
we call r
the remainder.
Z % X
returns the remainder of Z/X
.
The mod function is defined as the amount by which a number exceeds the largest integer multiple of the divisor that is not greater than that number. So in your case of
-13 % 64
the largest integer multiple of 64 that does not exceed -13 is -64. Now, when you subtract -13 from -64 it equals 51 -13 - (-64) = -13 + 64 = 51
In my version of Java JDK 1.8.0_05 -13%64=-13
you could try -13-(int(-13/64)) in other words do division cast to an integer to get rid of the fraction part then subtract from numerator So numerator-(int(numerator/denominator)) should give the correct remainder & sign
In Java latest versions you get -13%64 = -13
. The answer will always have sign of numerator.
According to section 15.17.3 of the JLS, "The remainder operation for operands that are integers after binary numeric promotion produces a result value such that (a/b)*b+(a%b) is equal to a. This identity holds even in the special case that the dividend is the negative integer of largest possible magnitude for its type and the divisor is -1 (the remainder is 0)."
Hope that helps.
How to get only positive modulus numbers in C or C++ (since the %
operator allows negative numbers)
Java and C and C++ all appear to act similarly in this manner. Without opening a new question, I'd like to present the approach for C and C++ as well.
From modulus_of_positive_and_negative_integers.c in my eRCaGuy_hello_world repo:
/// A function to perform and return the mathematical modulus as returned by
/// programming calculators and Google. In other words, it will **always**
/// return a positive value, unlike the `%` remainder operator in C!
/// Example:
/// So, `-5 % 180` in C or C++ is `-5`, but `mathematical_modulo(-5, 180)`
/// is the same as "-5 mod 180" in a calculator or on Google, and is `175`.
int mathematical_modulo(int num1, int num2)
{
int mod = num1 % num2;
if (mod < 0)
{
mod += num2;
}
return mod;
}
Sample tests of the code above:
Notice that -10 % 180
produces -10
in C and C++ since the %
operator acts like a simple remainder, not a roll-over modulo, whereas mathematical_modulo(-10, 180)
produces 170
, since the underflow wraps back around to the max value of 180 in this case, and then down 10 steps again.
printf("-10 %% 180 = %4i\n", -10 % 180);
printf(" 0 %% 180 = %4i\n", 0 % 180);
printf(" 10 %% 180 = %4i\n", 10 % 180);
printf("\n");
printf("mathematical_modulo(-10, 180) = %4i\n",
mathematical_modulo(-10, 180));
printf("mathematical_modulo( 0, 180) = %4i\n",
mathematical_modulo( 0, 180));
printf("mathematical_modulo( 10, 180) = %4i\n",
mathematical_modulo( 10, 180));
printf("\n");
Sample output:
-10 % 180 = -10
0 % 180 = 0
10 % 180 = 10
mathematical_modulo(-10, 180) = 170
mathematical_modulo( 0, 180) = 0
mathematical_modulo( 10, 180) = 10
Calculator tool on Linux
In C or C++, -10 % 180
is -10
. But, on my Linux calculator, -10 mod 180
is 170
:
Google calculator in browser
On Google, -10 % 180
, or -10 mod 180
(same thing on Google) are both 170
as well:
References
- My own experimentation, learning, and self-study via my code linked-to above.
- JavaScript
%
(modulo) gives a negative result for negative numbers - This answer: How does java do modulus calculations with negative numbers?
I don't think Java returns 51 in this case. I am running Java 8 on a Mac and I get:
-13 % 64 = -13
Program:
public class Test {
public static void main(String[] args) {
int i = -13;
int j = 64;
System.out.println(i % j);
}
}
精彩评论