Skip to content Skip to sidebar Skip to footer

What Is The Result Of 'x Modulo Y'?

Citing the ECMAScript spec Section 5.2: The notation “x modulo y” (y must be finite and nonzero) computes a value k of the same sign as y (or zero) such that abs(k) < ab

Solution 1:

The notation x modulo y is used internally within the spec to describe the result of certain operations. So yes, the result k of x modulo y is (by definition) of the same sign as y. It is not claimed that the % operator is equivalent to modulo.

If you're interested, the actual spec for % can be found under section 11.5.3. Interestingly, it makes no use of modulo.


Solution 2:

Copy pasting from my previous answer here:

Take a % b

1. When both +ve, Modulo & Remainder are one and the same
2. When a is -ve, they are not the same

For example;

a = -10, b = 3

Remainder of -10 % 3 = -1

for Modulo, add a greater multiple of 3 to your 'a' and calculate the remainder.

-10 + 12 = 2

2 % 3 = 2 is your answer


Solution 3:

The modulo operation is defined as the mathematical modulo operation:

Mathematical operations such as addition, subtraction, negation, multiplication, division, and the mathematical functions defined later in this clause should always be understood as computing exact mathematical results on mathematical real numbers, which do not include infinities and do not include a negative zero that is distinguished from positive zero.

Your question:

ToInt32(-1) equals ToInt32(1)

Well, no:

Let posInt be sign(number) * floor(abs(number)).

posInt = sign(-1) * floor(abs(-1)) = -1;

Let int32bit be posInt modulo 2; that is, a finite integer value k of Number type with positive sign and less than 2 in magnitude such that the mathematical difference of posInt and k is mathematically an integer multiple of 2.

int32bit = posInt mod 4294967296 = -1 mod 4294967296 = 4294967295

(wolfram alpha link for mathematical result)

If int32bit is greater than or equal to 2, return int32bit − 2, otherwise return int32bit.

Because 4294967295 >= 2147483648, we return 4294967295 - 4294967296, I.E. -1.

If we run the same steps for ToInt32(1), we get 1. So they don't have the same result.


Post a Comment for "What Is The Result Of 'x Modulo Y'?"