Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating nth root in Java using power method

Tags:

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.

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)).

like image 362
Sara Alaa Khodeir Avatar asked Sep 13 '15 18:09

Sara Alaa Khodeir


People also ask

How do you find the nth root in Java?

pow(n, 1.0 / 3) % ((int) Math. pow(n, 1.0 / 3)) . Use BigDecimal class, which is decimal representation of real numbers with arbitrary precision. Of course there's no method to calculate nth roots in the BigDecimal class.

How is root power calculated?

To calculate powers of numbers, multiply the base, or a, by itself, or the exponent or power designated by b. The square root of a number x (denoted √x) is a number multiplied by itself two times in order to get x, while a cubed root is a number multiplied by itself three times.


1 Answers

Since it is not possible to have arbitrary-precision calculus with double, you have three choices:

  1. Define a precision for which you decide whether a double value is an integer or not.
  2. Test whether the rounded value of the double you have is a correct result.
  3. Do calculus on a BigDecimal object, which supports arbitrary-precision double values.

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.

Option 2

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.

Option 3

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.

like image 144
Tunaki Avatar answered Sep 28 '22 11:09

Tunaki