Java는 음수로 모듈러스 계산을 어떻게 수행합니까?
모듈러스를 잘못하고 있습니까? Java -13 % 64
에서는 평가해야 -13
하지만 51
.
음수의 계수에 대한 두 정의가 모두 사용됩니다. 일부 언어는 하나의 정의를 사용하고 일부는 다른 정의를 사용합니다.
음수 입력에 대해 음수를 얻으려면 다음을 사용할 수 있습니다.
int r = x % n;
if (r > 0 && x < 0)
{
r -= n;
}
마찬가지로 음수 입력에서 음수를 반환하는 언어를 사용하고 있고 양수를 선호하는 경우 :
int r = x % n;
if (r < 0)
{
r += n;
}
"수학적으로"둘 다 정확하기 때문에 :
-13 % 64 = -13 (on modulus 64)
-13 % 64 = 51 (on modulus 64)
옵션 중 하나는 Java 언어 개발자가 선택해야했으며 다음을 선택했습니다.
결과의 부호는 배당금의 부호와 같습니다.
Java 사양에서 다음과 같이 말합니다.
https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3
Java로 작업하고 있습니까? Java는 예상대로 -13 % 64 = -13을 제공하기 때문입니다. 배당금의 징조!
Java에 대한 결과가 잘못되었습니다. 어떻게 도달했는지 (귀하의 프로그램, 구현 및 Java 버전) 컨텍스트를 제공하십시오.
로부터 Java 언어 사양
15.17.3 나머지 연산자 %
[...]
이진 숫자 승격 (§5.6.2) 후 정수인 피연산자에 대한 나머지 연산은 (a / b) * b + (a % b)가 다음과 같은 결과 값을 생성합니다. ㅏ.
15.17.2 나누기 연산자 /
[...]
정수 나누기는 0으로 반올림합니다.
/는 0으로 반올림되므로 (결과는 0)이 경우 %의 결과는 음수 여야합니다.
당신이 사용할 수있는
(x % n) - (x < 0 ? n : 0);
당신의 대답은 위키피디아에 있습니다 : 모듈로 연산
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.
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);
}
}
'developer tip' 카테고리의 다른 글
@OneToMany List <> 대 Set <> 차이점 (0) | 2020.09.12 |
---|---|
Java를 사용하여 멀티 파트 / 양식 데이터 POST 요청을하려면 어떻게해야합니까? (0) | 2020.09.11 |
EF 4.1 예외 "공급자가 ProviderManifestToken 문자열을 반환하지 않았습니다." (0) | 2020.09.11 |
NOT IN을 사용하는 NSPredicate가있는 NSArray (0) | 2020.09.11 |
자바 스크립트 : .forEach ()와 .map ()의 차이점 (0) | 2020.09.11 |