Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Result of -1%7 is different in javascript(-1) and python(6)

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?

like image 891
Syed Suhail Ahmed Avatar asked Dec 20 '16 09:12

Syed Suhail Ahmed


People also ask

How do you divide numbers in JavaScript?

Division (/)The division operator ( / ) produces the quotient of its operands where the left operand is the dividend and the right operand is the divisor.

How do you do modulus in JavaScript?

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.

What is the range for JavaScript numbers?

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.

How do you find the quotient in JavaScript?

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.


1 Answers

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.

like image 87
Derek Elkins left SE Avatar answered Oct 02 '22 15:10

Derek Elkins left SE