2011-09-05 149 views
52

我想用JavaScript獲取數字的第n個根,但我沒有看到使用內置Math對象的方法。我可以忽略一些東西嗎
如果不是...JavaScript:計算一個數字的第n個根

是否有一個數學庫我可以使用具有此功能?
如果不是...

什麼是自己做這個最好的算法?

+0

你想要多少根?僅僅是最明顯的,還是全部? –

回答

92

你可以使用這樣的事情?

Math.pow(n, 1/root); 

例如,

Math.pow(25, 1/2) == 5 
+1

這將工作,如果pow函數可以採取分數指數。不知道,但它_should_ :) –

+0

它確實,但不處理負數 – mplungjan

+1

小記。 pow函數接近答案。所以,對於大數值,這個近似值可能會返回非常錯誤的數字。 [參考](http://stackoverflow.com/questions/9956471/wrong-result-by-java-math-pow)]。 JS實現也是如此。 [ref](http://www.ecma-international.org/ecma-262/6.0/#sec-math.pow) –

16

nx的th根與x1/n的冪相同。你可以簡單地使用Math.pow

var original = 1000; 
var fourthRoot = Math.pow(original, 1/4); 
original == Math.pow(fourthRoot, 4); // (ignoring floating-point error) 
9

使用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){} 
} 
2

n - th x的根號是r的數字,這樣r的功率爲1/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); 
} 

例子:

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) 
+0

「nthRoot(-4,2); // NaN(沒有解決方法)「 ...至少不是實數 – Moritz

2

你可以使用

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

對於方形和立方根的特殊情況,最好分別使用本機功能Math.sqrtMath.cbrt

作爲ES7的,所述exponentiation operator **可以用來計算Ñ次方根作爲非負鹼/Ñ次方:

let root1 = Math.PI ** (1/3); // cube root of π 

let root2 = 81 ** 0.25;   // 4th root of 81 

這並未儘管如此,我還是沒有消極的基礎。

let root3 = (-32) ** 5;   // NaN