我想用JavaScript获取数字的第n个根,但我没有看到使用内置Math
对象的方法。我可以忽略一些东西吗
如果不是...JavaScript:计算一个数字的第n个根
是否有一个数学库我可以使用具有此功能?
如果不是...
什么是自己做这个最好的算法?
我想用JavaScript获取数字的第n个根,但我没有看到使用内置Math
对象的方法。我可以忽略一些东西吗
如果不是...JavaScript:计算一个数字的第n个根
是否有一个数学库我可以使用具有此功能?
如果不是...
什么是自己做这个最好的算法?
你可以使用这样的事情?
Math.pow(n, 1/root);
例如,
Math.pow(25, 1/2) == 5
这将工作,如果pow函数可以采取分数指数。不知道,但它_should_ :) –
它确实,但不处理负数 – mplungjan
小记。 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) –
n
x
的th根与x
的1/n
的幂相同。你可以简单地使用Math.pow
:
var original = 1000;
var fourthRoot = Math.pow(original, 1/4);
original == Math.pow(fourthRoot, 4); // (ignoring floating-point error)
使用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){}
}
的n
- th x
的根号是r
的数字,这样r
的功率为1/n
是x
。
在实数,还有一些子情况:
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)
“nthRoot(-4,2); // NaN(没有解决方法)“ ...至少不是实数 – Moritz
你可以使用
Math.nthroot = function(x,n) {
//if x is negative function returns NaN
return this.exp((1/n)*this.log(x));
}
//call using Math.nthroot();
对于方形和立方根的特殊情况,最好分别使用本机功能Math.sqrt
和Math.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
你想要多少根?仅仅是最明显的,还是全部? –