简体   繁体   English

指数运算符 ^ 和 Math.pow() 之间的区别

[英]Difference between Exponent operator ^ and Math.pow()

What is the difference between:有什么区别:

100 ^ 49; // = 85

and

Math.pow(100, 49); // = 1e+98

JavaScript returns different results and I don't know why. JavaScript 返回不同的结果,我不知道为什么。

^ isn't the exponentiation operator in JavaScript, ** is (and only recently). ^不是 JavaScript 中的取幂运算符, **是(而且只是最近)。 ^ is a bitwise XOR. ^是按位异或。 More on JavaScript operators on MDN .更多关于 MDN上的 JavaScript 操作符。

If you compare 100**49 to Math.pow(100,49) , according to the specification, there should be no difference;如果将100**49Math.pow(100,49)进行比较,根据规范,应该没有区别; from Math.pow :来自Math.pow

  1. Return the result of Applying the ** operator with base and exponent as specified in 12.6.4.返回使用 12.6.4 中指定的基数指数的 ** 运算符的结果。

That may or may not be true of implementations at present, though, because again the exponentiation operator is quite new.不过,对于目前的实现来说,这可能是也可能不是,因为求幂运算符还是很新的。 For instance, as I write this, Chrome's V8 JavaScript engine returns very slightly different results for 100**49 and Math.pow(100,49) : (Edit: As of 26/08/2020, they have the same result.)例如,在我写这篇文章时,Chrome 的 V8 JavaScript 引擎为100**49Math.pow(100,49)返回的结果略有不同:(编辑:截至 2020 年 8 月 26 日,它们具有相同的结果。)

 console.log(100**49); console.log(Math.pow(100,49));

Presumably disparities will be resolved as the implementations mature.据推测,随着实现的成熟,差异将得到解决。 The discrepancy appears to be covered by this issue .该差异似乎已包含在此问题中 It appears to be that 100*49 is evaluated at compile-time (since both values are constants), whereas of course Math.pow is evaluated at runtime, and apparently the algorithms aren't identical.似乎100*49是在编译时计算的(因为两个值都是常量),而Math.pow当然是在运行时计算的,显然算法并不相同。

If you use a variable, ** and Math.pow agree:如果使用变量, **Math.pow一致:

 let a = 100; console.log(a**49); console.log(Math.pow(a,49)); console.log(a**49 === Math.pow(a, 49));

On Firefox and Edge, the values are identical (even with constants).在 Firefox 和 Edge 上,这些值是相同的(即使是常量)。

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

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