What is the result of "x modulo y"?

Referring to the ECMAScript Specification 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), so abs (k) abs (y) and xk = q × y for some integer q.

therefore, if y is positive, the result k of 'x modulo y' is positive regardless of the sign of x.

and if my understanding is correct, ToInt32 (-1) is equal to ToInt32 (1)?

+3
source share
3 answers

The modulo operation is defined as a mathematical operation modulo:

Mathematical operations such as addition, subtraction, negation, multiplication, division, and mathematical functions defined later in this section should always be understood as calculating exact mathematical results from mathematical real numbers that do not include infinity and do not include a negative zero, which is equal to different from positive zero.

Your question:

ToInt32 (-1) is equal to ToInt32 (1)

Oh no:

Let posInt be the sign (number) * gender (abs (number)).

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

Let int32bit be posInt modulo 2 32 ; those. the final integer k is a type of positive signed number and less than 2 32 in magnitude such that the mathematical difference between posInt and k is a mathematical integer multiple of 2 32 .

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

( wolfram alpha link for math result )

If int32bit is greater than or equal to 2 31, return int32bit - 2 32 otherwise return int32bit.

Since 4294967295 >= 2147483648 , we return 4294967295 - 4294967296 , IE -1 .

If we ToInt32(1) the same steps for ToInt32(1) , we get 1 . Thus, they do not have the same result.

-one
source

The designation x modulo y used inside the specification to describe the result of certain operations. So, yes, the result is k of x modulo y (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 specification for % can be found in section 11.5.3. Interestingly, he does not use modulo .

+5
source

Copy the paste from my previous answer here:

Take% b

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

For instance:

a = -10, b = 3

Balance -10% 3 = -1

for Modulo, add the larger number of 3 to your 'a' and calculate the remainder.

-10 + 12 = 2

2% 3 = 2 - your answer

0
source

Source: https://habr.com/ru/post/1497286/


All Articles