简体   繁体   中英

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) < abs(y) and x−k = q × y for some integer q.

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

and if my understanding is right, ToInt32(-1) equals ToInt32(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 .

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

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 32 ; that is, a finite integer value k of Number type with positive sign and less than 2 32 in magnitude such that the mathematical difference of posInt and k is mathematically an integer multiple of 2 32 .

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

( wolfram alpha link for mathematical result )

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM