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 say to use Math.pow(num, 1 / root)
, but this does not work for negative numbers.
I have tried this:
public static double root(double num, double root) {
if (num < 0) {
return -Math.pow(Math.abs(num), (1 / root));
}
return Math.pow(num, 1.0 / root);
}
but, it does not work for all numbers as the root can be a decimal. For example root(-26, 0.8)
returns -58.71
, but that is an invalid input. This will also give the wrong answer for even roots. For example root(-2, 2)
returns -1.41421
, but -2 does not have a square root.