Math.pow(64, 1/3) returns 不精确 4

Math.pow(64, 1/3) returns inexact 4

我今天在 JavaScript 玩 Math.pow(),当时我注意到:

  1. Math.pow(8, 1/3)Math.pow(27, 1/3) return 分别为 2 和 3
  2. Math.pow(64, 1/3) 和所有其他更高的完全平方 return 长近似浮点数,例如 3.99999999999999996.

我听说过浮点精度以及一些小数如何显得不精确,但这对我来说很突出,因为它只发生在四立方 (64) 处。谁能解释一下为什么会这样?

首先,ECMA-262不对Math.pow返回结果的精度做任何保证。它指出:

Returns an implementation-dependent approximation to the result of raising x to the power y.

所以对于不同的实现,您得到的可能会有所不同。

我假设 1、8 和 27 的立方根分别与精确的 1、2 和 3 的偏差很小,以至于它不会在结果中反映为分数。但是当考虑的数字变大时,与之相关的错误也会变大。

通知:

Math.pow(1000,1/3)
-> 9.999999999999998

Math.pow(1000000,1/3)
->99.99999999999997

会一直偏离整数值