The principal nth root of a positive real number

java

Newton’s method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static double nthroot(int n, double A) {
double r = nthroot(n, A, .001);
return BigDecimal.valueOf(r).setScale(3, RoundingMode.HALF_DOWN).doubleValue();
}

public static double nthroot(int n, double A, double p) {
if(A < 0) {
System.err.println("A < 0");// we handle only real positive numbers
return -1;
} else if(A == 0) {
return 0;
}
double x_prev = A;
double x = A / n; // starting "guessed" value...
while(Math.abs(x - x_prev) > p) {
x_prev = x;
x = ((n - 1.0) * x + A / Math.pow(x, n - 1.0)) / n;
}
return x;
}

Binary search strategy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static double root(double x, int n) {
double lower = 0;
double upper = x;
double r = 0;
double temp = 0;
while (upper - lower >= 0.001) {
r = (upper + lower) / 2;
temp = Math.pow(r, n);
if (temp > x) {
upper = r;
} else {
lower = r;
}
}

return BigDecimal.valueOf(r).setScale(3, RoundingMode.HALF_DOWN).doubleValue();
}

ref