nth root implementation

Viewed 58751

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.

8 Answers

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;
}

I'm not too sure about the exact code, but add an extra if statement to clarify between odd and even roots. something along the lines of

public static double root(double num, double root) {
    if (num < 0) {
        if(root%2==1) {
            return -Math.pow(Math.abs(num), (1 / root));
        }
    }
    return Math.pow(num, 1.0 / root);
}

Not entirely sure if this will work with your other code, but I hope it can help

Related