Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nth root implementation

Tags:

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.

like image 476
Will Avatar asked Jun 13 '11 01:06

Will


2 Answers

(num) ^ (1/root) is similar to exp( (1/root) * log(num) ), so you can do it like:

public static double root(double num, double root)
{
    return Math.pow(Math.E, Math.log(num)/root);
} 
like image 95
Eng.Fouad Avatar answered Sep 20 '22 03:09

Eng.Fouad


What are you trying to do? Unless you're planning to fully and properly handle complex numbers you cannot take the nth root of a negative number.

For example, while (-8)^(1/3) has a principal branch of -2, the only branches of (-4)^(1/2) are 2i and -2i.

To handle this properly you need to transform the number into its polar form and then take the required root in that form.

So -8 is the complex number 8*exp(i*pi). The 1/3 roots of that are 2*exp(i*pi/3), 2*exp(i*pi), and 2*exp[i*(-pi)/3]. Then you can use de Moivre' formula to compute the roots in the form a + bi.

like image 43
QuantumMechanic Avatar answered Sep 19 '22 03:09

QuantumMechanic