用Java方法计算第n个根
我试图使用 Math.pow(n,1.0 / 3)
在java中获得立方根,但是由于它分双倍,它不会返回确切的回答。例如,125,这给了4.9999999999。有没有解决这个问题?我知道有一个立方根函数,但是我想解决这个问题,所以我可以计算出更高的根。
I was trying to get a cubic root in java using Math.pow(n, 1.0/3)
but because it divides doubles, it doesn't return the exact answer. For example, with 125, this gives 4.9999999999. Is there a work-around for this? I know there is a cubic root function but I'd like to fix this so I can calculate higher roots.
我不想圆,因为我想知道是否一个数字通过执行以下操作来实现整数: Math.pow(n,1.0 / 3)%((int)Math.pow(n,1.0 / 3))
。
I would not like to round because I want to know whether a number has an integer root by doing something like this: Math.pow(n, 1.0 / 3) % ((int) Math.pow(n, 1.0 / 3))
.
由于不可能使用 double $ c进行任意精度演算$ c>,你有三个选择:
Since it is not possible to have arbitrary-precision calculus with double
, you have three choices:
- 定义一个精度,你决定一个
double
value是一个整数。 - 测试您的
double
的舍入值是否正确。 - 在
BigDecimal
对象,它支持任意精度的双重值。
- Define a precision for which you decide whether a
double
value is an integer or not. - Test whether the rounded value of the
double
you have is a correct result. - Do calculus on a
BigDecimal
object, which supports arbitrary-precision double values.
选项1
Option 1
private static boolean isNthRoot(int value, int n, double precision) {
double a = Math.pow(value, 1.0 / n);
return Math.abs(a - Math.round(a)) < precision; // if a and round(a) are "close enough" then we're good
}
这种方法的问题是如何定义足够近。这是一个主观问题,这取决于你的要求。
The problem with this approach is how to define "close enough". This is a subjective question and it depends on your requirements.
private static boolean isNthRoot(int value, int n) {
double a = Math.pow(value, 1.0 / n);
return Math.pow(Math.round(a), n) == value;
}
此方法的优点是无需定义精度。但是,我们需要执行另一个 pow
操作,这样会影响性能。
The advantage of this method is that there is no need to define a precision. However, we need to perform another pow
operation so this will affect performance.
没有内置的方法来计算BigDecimal的双倍幂。 此问题将为您提供有关如何做到这一点的见解。
There is no built-in method to calculate a double power of a BigDecimal. This question will give you insight on how to do it.