JavaScript:计算数字的第n个根

Nat*_*han 72 javascript algorithm math

我正在尝试使用JavaScript获取数字的第n个根,但我没有看到使用内置Math对象的方法.我忽略了什么吗?
如果不...

有没有我可以使用的具有此功能的数学库?
如果不...

我自己做的最好的算法是什么?

Dig*_*ane 124

你能用这样的东西吗?

Math.pow(n, 1/root);
Run Code Online (Sandbox Code Playgroud)

例如.

Math.pow(25, 1/2) == 5
Run Code Online (Sandbox Code Playgroud)

  • 它可以但不处理负数 (2认同)
  • 一个小笔记。pow 函数近似于答案。因此,对于较大的值,此近似值可能会返回非常错误的数字。[[参考](http://stackoverflow.com/questions/9956471/wrong-result-by-java-math-pow)]。JS 实现也是如此。[参考](http://www.ecma-international.org/ecma-262/6.0/#sec-math.pow) (2认同)
  • 如何处理`Math.pow(-32, 1/5)`? (2认同)

小智 20

所述n的次方根x是一样x到的功率1/n.你可以简单地使用Math.pow:

var original = 1000;
var fourthRoot = Math.pow(original, 1/4);
original == Math.pow(fourthRoot, 4); // (ignoring floating-point error)
Run Code Online (Sandbox Code Playgroud)


mpl*_*jan 11

使用Math.pow()

请注意,它不能很好地处理否定 - 这是一个讨论和一些代码

http://cwestblog.com/2011/05/06/cube-root-an-beyond/

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){}
}
Run Code Online (Sandbox Code Playgroud)


GOT*_*O 0 9

对于平方根和立方根的特殊情况,最好分别使用本机函数Math.sqrtMath.cbrt

\n\n

从 ES7 开始,求幂运算符**可用于计算非负底数的1 / n次方的n次方根:

\n\n
let root1 = Math.PI ** (1 / 3); // cube root of \xcf\x80\n\nlet root2 = 81 ** 0.25;         // 4th root of 81\n
Run Code Online (Sandbox Code Playgroud)\n\n

但这不适用于负碱基。

\n\n
let root3 = (-32) ** 5;         // NaN\n
Run Code Online (Sandbox Code Playgroud)\n


Ori*_*iol 6

n的次方根是x一个数,其幂r为。r1/nx

在实数中,有一些子情况:

  • x当为正且为偶数时,有两种解(同值异号)r
  • x当为正且为奇数时,有一个r正解。
  • x当为负且为奇数时,有一个负解r
  • x当为负数且为偶数时无解r

由于Math.pow不喜欢带有非整数指数的负基数,因此您可以使用

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);
}
Run Code Online (Sandbox Code Playgroud)

例子:

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)
Run Code Online (Sandbox Code Playgroud)


Som*_*ody 5

你可以用

Math.nthroot = function(x,n) {
    //if x is negative function returns NaN
    return this.exp((1/n)*this.log(x));
}
//call using Math.nthroot();
Run Code Online (Sandbox Code Playgroud)