JavaScript では、% 演算子は非常に奇妙な動作をしているようです。私は次のことを試しました:
>>> (0 - 11) % 12
-11
(Python のように) 1 ではなく -11 を返すのはなぜですか?
私は何か間違ったことをしている、または期待していると確信していますが、ドキュメントは何を教えてくれません。
JavaScript では、% 演算子は非常に奇妙な動作をしているようです。私は次のことを試しました:
>>> (0 - 11) % 12
-11
(Python のように) 1 ではなく -11 を返すのはなぜですか?
私は何か間違ったことをしている、または期待していると確信していますが、ドキュメントは何を教えてくれません。
It's behaving correctly according to the way the language is specified (e.g. ECMA 262), where it's called the remainder operator rather than the modulus operator. From the spec:
The result of an ECMAScript floating-point remainder operation is determined by the rules of IEEE arithmetic:
- If either operand is NaN, the result is NaN.
- The sign of the result equals the sign of the dividend.
- If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.
- If the dividend is finite and the divisor is an infinity, the result equals the dividend.
- If the dividend is a zero and the divisor is nonzero and finite, the result is the same as the dividend.
- In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder
r
from a dividendn
and a divisord
is defined by the mathematical relationr = n - (d * q)
whereq
is an integer that is negative only ifn/d
is negative and positive only ifn/d
is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient ofn
andd
.r
is computed and rounded to the nearest representable value using IEEE 754 round-to-nearest mode.
In your case n/d
is negative, so the result is negative.
See the Wikipedia entry on modulo for more details, including a list of languages with the behaviour in terms of the sign of the result.
モジュロと剰余の 2 つの同様の演算があります。モジュロはより数学的な使用法を表し、残りはより多くの IT 使用法を表します。
2 つの整数 a と b があるとします。
MOD(a, b) は、b と同じ符号を持つ結果を返します。
REM(a, b) は、a と同じ符号を持つ結果を返します。- これは C/C++/C# で % 演算子として実装されているもので、混乱を招くように "mod" と呼ばれることがよくあります。
これも次のように考えることができます。
MOD(a, b) は、a より小さい b の最大の整数倍 (「c」と呼びます) を見つけ、(a - c) を返します。
例: MOD(-340,60) c = -360 は、-340 より小さい 60 の最大の倍数です。したがって、(-340 - (-360)) = 20 となります。
REM(a, b) は、(DIV(a,b) * b) + REM(a, b) = a のような値を返します。ここで、DIV() は整数除算を表します。
したがって、r = REM(-340, 60) の場合
-340 = DIV(-340,60) * 60 + r = -5 * 60 + r = r - 300
これを解くと、r = -40 が得られます。
MOD(a,b) は b と同じ符号の結果を返すと言いますが、c が a より小さい場合に (ac) を返すと言います。この 2 番目の定義は、常に正の数を返すことを意味します。それはどれですか?
-11 < 12, so i 'suppose' they don't actually divide: So -11 = 0x12 -11
Have a try with (0-13) % 12
math モジュールの fmod は、Python で正しく動作します。
>>> from math import *
>>> fmod(-11, 12)
-11.0
-11 が正解です。