最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Difference between Exponent operator ^ and Math.pow() - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Jul 26, 2018 at 15:12 Kalle Richter 8,72829 gold badges92 silver badges203 bronze badges asked Jul 26, 2018 at 14:11 CtorCtor 991 silver badge5 bronze badges 1
  • 4 The exponential operator is **, 100**49. – Ben Fortune Commented Jul 26, 2018 at 14:11
Add a comment  | 

1 Answer 1

Reset to default 24

^ isn't the exponentiation operator in JavaScript, ** is (and only recently). ^ is a bitwise XOR. More on JavaScript operators on MDN.

If you compare 100**49 to Math.pow(100,49), according to the specification, there should be no difference; from Math.pow:

  1. Return the result of Applying the ** operator with base and exponent as specified in 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.)

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.

If you use a variable, ** and Math.pow agree:

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).

发布评论

评论列表(0)

  1. 暂无评论