I was playing around with Math.pow()
today in JavaScript, when I noticed that:
Math.pow(8, 1/3)
and Math.pow(27, 1/3)
return 2 and 3, respectivelyMath.pow(64, 1/3)
and all other higher perfect squares return long approximate floating point numbers, such as 3.99999999999999996.I've heard of floating point precision and how some decimals can appear inexact, but this stood out to me because it only happens beginning at four cubed (64). Can anyone please explain why this happens?
First of all, ECMA-262 does not make any guarantees regarding the precision of result returned by Math.pow
. It states:
Returns an implementation-dependent approximation to the result of raising x to the power y.
So what you are getting might be different for different implementations.
I assume that the deviation in cube roots of 1, 8 and 27 from the exact 1, 2 and 3 respectively is so small that it doesn't reflect as a fraction in the result. But when the number under consideration becomes large, so does the error associated with it.
Notice:
Math.pow(1000,1/3)
-> 9.999999999999998
Math.pow(1000000,1/3)
->99.99999999999997
It will keep on deviating from the whole number value.