Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 973
Ctor Avatar asked Jul 26 '18 14:07

Ctor


People also ask

What does math pow () do?

The Math. pow() method returns the value of x to the power of y (xy).

How is built in function pow () function different from function math pow ()?

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.

What is an exponential operator?

The exponentiation operator ( ** ) returns the result of raising the first operand to the power of the second operand.

What is math POW in Python?

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.


1 Answers

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

like image 178
T.J. Crowder Avatar answered Sep 29 '22 10:09

T.J. Crowder