The expression -1 % 7
in JavaScript is giving me -1
as the result. Whereas in Python and Haskell, I found the result to be 6
.
Can anyone explain why both have different behaviors? Which one is correct?
Division (/)The division operator ( / ) produces the quotient of its operands where the left operand is the dividend and the right operand is the divisor.
To obtain a modulo in JavaScript, in place of n % d , use ((n % d) + d) % d . In JavaScript, the modulo operation (which doesn't have a dedicated operator) is used to normalize the second operand of bitwise shift operators ( << , >> , etc.), making the offset always a positive value.
Description. The MAX_SAFE_INTEGER constant has a value of 9007199254740991 (9,007,199,254,740,991 or ~9 quadrillion). The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent integers between -(253 – 1) and 253 – 1.
In JavaScript, we can get the quotient and remainder of a division using the bitwise operators. For example, we can get the quotient of a division using the bitwise NOT ~~ or bitwise OR |0 , which converts the floating-point number to an integer. And to get the remainder, we can use the % character.
I'm going to give a slightly different answer. As others have said, functions can do whatever you define them to and m - x = -x
mod m
. As a prelude, I'll note that Haskell has two "mod" functions, mod
and rem
which differ in just this aspect. You can make a case that the mod
one is preferable mathematically. The rem
one corresponds to what you'd get on an x86 processor. There is, in fact, a third one, the Euclidean one, which may be even better as well as described by Raymond Boute in The Euclidean Definitions of the Functions Div and Mod. The third form always returns a positive modulus. (There are, in fact, at least two other choices that can be made.)
So, Javascript's definition is what you get from most machine mod
opcodes. In this sense, it might be preferable as this would make it more efficient to implement. Mathematically, Haskell's and Python's definition is better than Javascript's. There's also a third definition which may be slightly better.
One key property that the Euclidean and Haskell/Python definitions both possess is x mod m = y mod m
is equivalent to x = y
mod m
which Javascript's definition lacks. You can verify by calculating 6 % 7
in Javascript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With