JavaScript:计算数字的第 n 个根
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7308627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript: Calculate the nth root of a number
提问by Nathan
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...
我正在尝试使用 JavaScript 获取数字的第 n 个根,但我看不到使用内置Math
对象的方法。我是否忽略了什么?
如果不...
Is there a math library I can use that has this functionality?
If not...
我可以使用具有此功能的数学库吗?
如果不...
What's the best algorithm to do this myself?
自己做这件事的最佳算法是什么?
回答by Digital Plane
Can you use something like this?
你能用这样的东西吗?
Math.pow(n, 1/root);
eg.
例如。
Math.pow(25, 1/2) == 5
回答by Facebook Staff are Complicit
The n
th root of x
is the same as x
to the power of 1/n
. You can simply use Math.pow
:
的n
th 根与 的幂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)
回答by mplungjan
Use Math.pow()
使用 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/
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){}
}
回答by Somebody
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();
回答by GOTO 0
For the special cases of square and cubic root, it's best to use the native functions Math.sqrt
and Math.cbrt
respectively.
对于平方根和立方根的特殊情况,最好分别使用原生函数Math.sqrt
和Math.cbrt
。
As of ES7, the exponentiation operator **
can be used to calculate the nth root as the 1/nth power of a non-negative base:
从 ES7 开始,幂运算符**
可用于计算作为非负底数的1/ n次幂的n次方根:
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
回答by Oriol
The n
-th root of x
is a number r
such that r
to the power of 1/n
is x
.
的n
-th 根x
是一个数r
,其次方r
为1/n
is x
。
In real numbers, there are some subcases:
在实数中,有一些子情况:
- There are two solutions (same value with opposite sign) when
x
is positive andr
is even. - There is one positive solution when
x
is positive andr
is odd. - There is one negative solution when
x
is negative andr
is odd. - There is no solution when
x
is negative andr
is even.
- 当
x
为正数和r
偶数时,有两种解(同值反号)。 - 当
x
为正且r
为奇数时,有一个正解。 - 当
x
为负且r
为奇数时,有一个负解。 - 当
x
为负且r
为偶数时无解。
Since Math.pow
doesn't like a negative base with a non-integer exponent, you can use
由于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);
}
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)
回答by SwiftNinjaPro
Here's a function that tries to return the imaginary number. It also checks for a few common things first, ex: if getting square root of 0 or 1, or getting 0th root of number x
这是一个尝试返回虚数的函数。它还首先检查一些常见的事情,例如:如果得到 0 或 1 的平方根,或者得到数字 x 的第 0 个根
function root(x, n){
if(x == 1){
return 1;
}else if(x == 0 && n > 0){
return 0;
}else if(x == 0 && n < 0){
return Infinity;
}else if(n == 1){
return x;
}else if(n == 0 && x > 1){
return Infinity;
}else if(n == 0 && x == 1){
return 1;
}else if(n == 0 && x < 1 && x > -1){
return 0;
}else if(n == 0){
return NaN;
}
var result = false;
var num = x;
var neg = false;
if(num < 0){
//not using Math.abs because I need the function to remember if the number was positive or negative
num = num*-1;
neg = true;
}
if(n == 2){
//better to use square root if we can
result = Math.sqrt(num);
}else if(n == 3){
//better to use cube root if we can
result = Math.cbrt(num);
}else if(n > 3){
//the method Digital Plane suggested
result = Math.pow(num, 1/n);
}else if(n < 0){
//the method Digital Plane suggested
result = Math.pow(num, 1/n);
}
if(neg && n == 2){
//if square root, you can just add the imaginary number "i=√-1" to a string answer
//you should check if the functions return value contains i, before continuing any calculations
result += 'i';
}else if(neg && n % 2 !== 0 && n > 0){
//if the nth root is an odd number, you don't get an imaginary number
//neg*neg=pos, but neg*neg*neg=neg
//so you can simply make an odd nth root of a negative number, a negative number
result = result*-1;
}else if(neg){
//if the nth root is an even number that is not 2, things get more complex
//if someone wants to calculate this further, they can
//i'm just going to stop at *n√-1 (times the nth root of -1)
//you should also check if the functions return value contains * or √, before continuing any calculations
result += '*'+n+√+'-1';
}
return result;
}
回答by Zamy Arkre Nendmed
Well, I know this is an old question. But, based on SwiftNinjaPro's answer, I simplified the function and fixed some NaN issues. Note: This function used ES6 feature, arrow function and template strings, and exponentation. So, it might not work in older browsers:
好吧,我知道这是一个老问题。但是,根据 SwiftNinjaPro 的回答,我简化了函数并修复了一些 NaN 问题。注意:该函数使用了 ES6 特性、箭头函数和模板字符串以及指数。因此,它可能不适用于旧浏览器:
Math.numberRoot = (x, n) => {
return (((x > 1 || x < -1) && n == 0) ? Infinity : ((x > 0 || x < 0) && n == 0) ? 1 : (x < 0 && n % 2 == 0) ? `${((x < 0 ? -x : x) ** (1 / n))}${"i"}` : (n == 3 && x < 0) ? -Math.cbrt(-x) : (x < 0) ? -((x < 0 ? -x : x) ** (1 / n)) : (n == 3 && x > 0 ? Math.cbrt(x) : (x < 0 ? -x : x) ** (1 / n)));
};
Example:
例子:
Math.numberRoot(-64, 3); // Returns -4
Example (Imaginary number result):
示例(虚数结果):
Math.numberRoot(-729, 6); // Returns a string containing "3i".