I\'m trying to get the nth root of a number using JavaScript, but I don\'t see a way to do it using the built in Math
object. Am I overlooking something?
If
The n
-th root of x
is a number r
such that r
to the power of 1/n
is x
.
In real numbers, there are some subcases:
x
is positive and r
is even.x
is positive and r
is odd.x
is negative and r
is odd.x
is negative and r
is even.Since Math.pow
doesn't like a negative base with a non-integer exponent, you can use
function nthRoot(x, n) {
if(x < 0 && n%2 != 1) return NaN; // Not well defined
return (x < 0 ? -1 : 1) * Math.pow(Math.abs(x), 1/n);
}
Examples:
nthRoot(+4, 2); // 2 (the positive is chosen, but -2 is a solution too)
nthRoot(+8, 3); // 2 (this is the only solution)
nthRoot(-8, 3); // -2 (this is the only solution)
nthRoot(-4, 2); // NaN (there is no solution)
Can you use something like this?
Math.pow(n, 1/root);
eg.
Math.pow(25, 1/2) == 5
I have written an algorithm but it is slow when you need many numbers after the point:
https://github.com/am-trouzine/Arithmetic-algorithms-in-different-numeral-systems
NRoot(orginal, nthRoot, base, numbersAfterPoint);
The function returns a string.
E.g.
var original = 1000;
var fourthRoot = NRoot(original, 4, 10, 32);
console.log(fourthRoot);
//5.62341325190349080394951039776481