可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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 not...
Is there a math library I can use that has this functionality?
If not...
What's the best algorithm to do this myself?
回答1:
Can you use something like this?
Math.pow(n, 1/root);
eg.
Math.pow(25, 1/2) == 5
回答2:
The n
th root of x
is the same as x
to the power of 1/n
. You can simply use Math.pow
:
var original = 1000; var fourthRoot = Math.pow(original, 1/4); original == Math.pow(fourthRoot, 4); // (ignoring floating-point error)
回答3:
Use Math.pow()
Note that it does not handle negative nicely - here is a discussion and some code that does
http://cwestblog.com/2011/05/06/cube-root-an-beyond/
function nthroot(x, n) { try { var negate = n % 2 == 1 && x 0 == n > 0)) return negate ? -possible : possible; } catch(e){} }
回答4:
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:
- There are two solutions (same value with opposite sign) when
x
is positive and r
is even. - There is one positive solution when
x
is positive and r
is odd. - There is one negative solution when
x
is negative and r
is odd. - There is no solution when
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
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)
回答5:
You could use
Math.nthroot = function(x,n) { //if x is negative function returns NaN return this.exp((1/n)*this.log(x)); } //call using Math.nthroot();
回答6:
For the special cases of square and cubic root, it's best to use the native functions Math.sqrt
and Math.cbrt
respectively.
As of ES7, the exponentiation operator **
can be used to calculate the nth root as the 1/nth power of a non-negative base:
let root1 = Math.PI ** (1 / 3); // cube root of π let root2 = 81 ** 0.25; // 4th root of 81
This doesn't work with negative bases, though.
let root3 = (-32) ** 5; // NaN