Lately, I have been in a math oriented mood. Yesterday, I was thinking about how the fact that you can take the square root of a number in JavaScript, but not the cube root, 4^{th} root, etc.. Naturally, I looked to Wikipedia to find the algorithm to find the n^{th} root of a number. I developed the following unnecessary function:

function bad_nthroot(x, n) { // If an error occurs, don't return anything. try { // If an error occurs // Loop through the nth root algorithm until no difference is found. var x2, A = x, n1 = n - 1, itersLeft = 99; do { x2 = x; x = (n1 * x2 + A / Math.pow(x2, n1)) / n; } while(x != x2 && itersLeft--); // If less than 100 iterations were done or if the difference between the // previous approximation and the current one is acceptable, return the // current one. if((itersLeft || (Math.abs(x - x2) < 1 && (x < 0) == (x2 < 0))) && isFinite(x)) return x; } catch(e){} }

After testing out the function a bit and taking a look at an online example, I realized that I could have done it with the `Math.pow()`

. After all, the cube root of a number is the same thing as that number to the power of ^{1}/_{3}. With this in mind, I redeveloped the function and came up with the following, more accurate function:

function nthroot(x, n) { try { var negate = n % 2 == 1 && x < 0; if(negate) x = -x; var possible = Math.pow(x, 1 / n); n = Math.pow(possible, n); if(Math.abs(x - n) < 1 && (x > 0 == n > 0)) return negate ? -possible : possible; } catch(e){} }

One notable difference is the fact that calling `bad_nthroot(8, 1/2)`

results in 63.99999999999999. On the other hand, `nthroot(8, 1/2)`

results in 64. There are many other differences as well.

The reason I created this function instead of using `Math.pow(x, 1 / n)`

is because of examples such as `Math.pow(-8, 1 / 3)`

. Even though the cube root of -8 is -2, `Math.pow(-8, 1 / 3)`

results in NaN. On the other hand, `nthroot(-8, 3)`

results in the expected value of `-2`

.

If you find something wrong with my nthroot function, please let me know.