I am working on a way to calculate the nth root of a number. However, I am having problems with the nth root of negative numbers.
Most people s
I use the method below. Maybe it's not the most accurate, but it works well in my case.
public double root(double num, double root) {
double d = Math.pow(num, 1.0 / root);
long rounded = Math.round(d);
return Math.abs(rounded - d) < 0.00000000000001 ? rounded : d;
}
public double root(double num, double root) {
double y=1;
double x;
while(Math.pow(x, root) != num) {
if(Math.pow(x, root) > num) {
x=x-y;
y=y/10;
} else {
x=x+y;
}
}
return x;
}
This should work fine for you, although it isn't compact it uses as little math functions as possible.