简体   繁体   English

为什么计算的模/余数运算符对于大数是错误的?

[英]Why the modulo/remainder operator calculated is wrong for large numbers?

I am trying to understand why I am not able to calculate the right modulo using JavaScript.我试图理解为什么我无法使用 JavaScript 计算正确的模数。 The operation I have tried is:我试过的操作是:

Wrong answer错误的答案

28493595674446332150349236018567871332790652257295571471311614363091332152517 % 6 = 4

The result should be 1.结果应该是 1。

28493595674446332150349236018567871332790652257295571471311614363091332152517 % 6 = 1

I have tried to convert this number to BN but unfortunately I always get the same answer.我曾尝试将此数字转换为 BN,但不幸的是我总是得到相同的答案。 However if you use wolfram alpha or another math software it returns the right answer.但是,如果您使用 wolfram alpha 或其他数学软件,它会返回正确的答案。

What's going on?这是怎么回事? What have I been doing wrong?我做错了什么?

The integer number range in JavaScript is +/- 9007199254740991 (Number.MAX_SAFE_INTEGER). JavaScript 中的整数范围是 +/- 9007199254740991 (Number.MAX_SAFE_INTEGER)。 Your number is simply out of range for JS.您的数字超出了 JS 的范围。

You can also use the BigInt notation to get the right answer.您还可以使用 BigInt 表示法来获得正确答案。 28493595674446332150349236018567871332790652257295571471311614363091332152517n % 6n

See What is JavaScript's highest integer value that a number can go to without losing precision?请参阅什么是 JavaScript 的最高整数值,一个数字可以在不丢失精度的情况下达到?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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