首页 文章

为什么Math.pow()(有时)在JavaScript中不等于**?

提问于
浏览
110

我刚刚发现ECMAScript 7功能 a**b 作为 Math.pow(a,b)MDN Reference)的替代品,并在that post中进行了讨论,其中他们显然表现不同 . 我已在Chrome 55中对其进行了测试,并确认结果不同 .

Math.pow(99,99) 返回 3.697296376497263e+197

99**99 返回 3.697296376497268e+197

因此记录差异 Math.pow(99,99) - 99**99 会导致 -5.311379928167671e+182 .

到目前为止可以说,它只是另一种实现,但将它包装在一个函数中的行为又不同了:

function diff(x) {
  return Math.pow(x,x) - x**x;
}

调用 diff(99) 返回 0 .

为什么会这样?

正如xszaboj指出的那样,这可以缩小到这个问题:

var x = 99;
x**x - 99**99; // Returns -5.311379928167671e+182

1 回答

  • 120

    99**99evaluated at compile time("constant folding"),编译器的pow routineruntime one不同 . 在运行时评估 ** 时,结果与 Math.pow 相同 - 难怪因为 ** 实际上是compiledMath.pow 调用:

    console.log(99**99);           // 3.697296376497268e+197
    a = 99, b = 99;
    console.log(a**b);             // 3.697296376497263e+197
    console.log(Math.pow(99, 99)); // 3.697296376497263e+197
    

    其实

    9999 = 369729637649726772657187905628805440595668764281741102430259972423552570455277523421410650010128232727940978889548326540119429996769494359451621570193644014418071060667659301384999779999159200499899

    所以第一个结果是更好的近似,仍然不应该发生恒定和动态表达之间的这种差异 .

    此行为看起来像V8中的错误 . 它has been reported并希望很快得到解决 .

相关问题