Home > Blockchain >  Different result of modulo operation in JavaScript and Python
Different result of modulo operation in JavaScript and Python

Time:10-03

In javascript the modulo operation result is like this:

-9 % 19 = -9

while in python the same modulo operation yields this:

-9 % 19 = 10

now according to Finite Field python's answer is correct. can anyone please explain why JavaScript doesn't return result same as python?

CodePudding user response:

It is a matter of conventions (see here) and, for Python it is related to the result of integer divisions. Python works on the basis that you can reverse the modulo and get back to the original numerator by multiplying the quotient by the denominator and adding the modulo:

So, if N divided by D gives a quotient of Q and remainder or R (N mod D), then Q x D R = N

Applying the numbers (Python):

-9 / 19 --> Q = -1, R = 10  --> -1 x 19   10 = -9

this also means that 9 % -19 --> -10

9 / -19 --> Q = -1, R = -10 --> -1 x -19   -10 = 9

Javascript uses a different approach for modulo of negative numbers (applying the sign of the numerator to the remainder of the division between absolute values) that does not reverse correctly when applying the mathematical definition to numerator and denominator that have different signs:

Math.floor(-9/19)) --> -1
-9 % 19            --> -9
                   --> -1 x 19   -9 --> -28 

Math.floor(9/-19)) --> -1
9 % -19            --> 9
                   --> -1 x -19   9 --> 28 

CodePudding user response:

In JavaScript remainder operator % returns the remainder left over when one operand is divided by a second operand

Now look at the % examples on MDN documentation:

 12 % 5  //  2
-12 % 5 // -2

So, as you wish, it returns the correct answer(same as your python version). But sometimes it could be complex at first look (for example in your case).

let's take another example:

-1 % 2  // -1
 1 % -2 //  1
 1 % 2  //  1
 2 % 3  //  2

In the above situations, the right side number is bigger than the left side*(ignore the minus sign)* so the result will be the left side without any calculation.

Note: assume calculation without negative sign then apply the sign to the result.

  • Related