Reputation: 99
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.
Upvotes: 7
Views: 4450
Reputation: 1075427
^
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
:
- 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).
Upvotes: 24