Will - 1 year ago 90

Java Question

I am working on a way to calculate the n^{th} root of a number. However, I am having problems with the n^{th} root of negative numbers.

Most people say to use

`Math.pow(num, 1 / root)`

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)`

`-58.71`

`root(-2, 2)`

`-1.41421`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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`

.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**