简体   繁体   English

Math.pow 给出错误的结果

[英]Math.pow gives wrong result

I was trying to repeat a character N times, and came across the Math.pow function.我试图重复一个字符N次,但遇到了Math.pow函数。

But when I use it in the console, the results don't make any sense to me:但是当我在控制台中使用它时,结果对我来说没有任何意义:

Math.pow(10,15) - 1 provides the correct result 999999999999999 Math.pow(10,15) - 1提供正确结果999999999999999

But why does Math.pow(10,16) - 1 provide 10000000000000000 ?但是为什么Math.pow(10,16) - 1提供10000000000000000

You are producing results which exceed the Number.MAX_SAFE_INTEGER value, and so they are not accurate any more up to the unit.您正在生成超过Number.MAX_SAFE_INTEGER值的结果,因此它们不再准确到单位。

This is related to the fact that JavaScript uses 64-bit floating point representation for numbers, and so in practice you only have about 16 (decimal) digits of precision.这与 JavaScript 使用 64 位浮点数表示数字的事实有关,因此实际上您只有大约 16(十进制)位的精度。

Since the introduction of BigInt in EcmaScript, you can get an accurate result with that data type, although it cannot be used in combination with Math.pow .由于在 EcmaScript 中引入了BigInt ,您可以使用该数据类型获得准确的结果,尽管它不能与Math.pow结合使用。 Instead you can use the ** operator.相反,您可以使用**运算符。

See how the use of number and bigint (with the n suffix) differ:查看 number 和 bigint(带有n后缀)的使用有何不同:

10  ** 16  - 1  // == 10000000000000000
10n ** 16n - 1n // ==  9999999999999999n

Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc.与许多其他编程语言不同,JavaScript 没有定义不同类型的数字,如整数、短整数、长整数、浮点数等。

JavaScript numbers are always stored as double-precision floating-point numbers, following the international IEEE 754 standard. JavaScript 数字始终存储为双精度浮点数,遵循国际 IEEE 754 标准。

This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign-in bit 63:这种格式以 64 位存储数字,其中数字(小数)存储在 0 到 51 位,指数存储在 52 到 62 位,以及登录位 63:

Integers (numbers without a period or exponent notation) are accurate up to 15 digits.整数(没有句点或指数符号的数字)精确到 15 位。

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

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