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 g
Since it is not possible to have arbitrary-precision calculus with double
, you have three choices:
double
value is an integer or not.double
you have is a correct result.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;
}
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.
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.