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)
小智 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)
对于平方根和立方根的特殊情况,最好分别使用本机函数Math.sqrt
和Math.cbrt
。
从 ES7 开始,求幂运算符**
可用于计算非负底数的1 / 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\nlet root3 = (-32) ** 5; // NaN\n
Run Code Online (Sandbox Code Playgroud)\n
n
的次方根是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);
}
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)
你可以用
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)