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.
The Math. pow() method returns the value of x to the power of y (xy).
The built-in pow(x,y [,z]) function has an optional third parameter as modulo to compute x raised to the power of y and optionally do a modulo (% z) on the result. It is same as the mathematical operation: (x ^ y) % z. Whereas, math. pow() function does not have modulo functionality.
The exponentiation operator ( ** ) returns the result of raising the first operand to the power of the second operand.
The math. pow() method returns the value of x raised to power y. If x is negative and y is not an integer, it returns a ValueError. This method converts both arguments into a float.
^
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With