0

I was playing around with Math.pow() today in JavaScript, when I noticed that:

  1. Math.pow(8, 1/3) and Math.pow(27, 1/3) return 2 and 3, respectively
  2. Math.pow(64, 1/3) and all other higher perfect squares return long approximate floating point numbers, such as 3.99999999999999996.

Test in Google Chrome's Developer Tools' Console

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?

Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94
  • It is a general problem with floating pioint precision http://stackoverflow.com/questions/11695618/dealing-with-float-precision-in-javascript also http://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript – Arun P Johny Feb 22 '16 at 03:51
  • @ArunPJohny I was just wondering why it didn't happen with `Math.pow()` to find the cube roots of 1, 8, and 27, but only with the others? – Jonathan Lam Feb 22 '16 at 03:53
  • Because it's not a cube root, it's a power of `0.(3)` – zerkms Feb 22 '16 at 03:55
  • "why it didn't happen with Math.pow() to find the cube roots of 1, 8, and 27, but only with the others" --- error accumulates. – zerkms Feb 22 '16 at 03:56
  • @zerkms A power of `0.(3)` or `1/3` is equivalent to the cube root. – Jonathan Lam Feb 22 '16 at 03:56
  • 2
    @JonathanLam it is not. `0.333333333333333333...` is not exactly equal to the fraction `1/3`. JS does not have a type to represent fractions. – zerkms Feb 22 '16 at 03:57
  • @zerkms That clears it up. Thanks. – Jonathan Lam Feb 22 '16 at 03:59

1 Answers1

3

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.

Akshay Arora
  • 1,953
  • 1
  • 14
  • 30