Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cube root of a negative number

Tags:

java

math

I'm trying to find the cube root of a negative number but I get a NaN. Any help?

System.out.println(Math.pow(-8, 1.0 / 3.0));
like image 830
Chro Avatar asked Nov 28 '11 02:11

Chro


2 Answers

The Java documentation for Math.pow states:

If the first argument is finite and less than zero [...] [and] if the second argument is finite and not an integer, then the result is NaN.

You could use Math.cbrt to get the cube root:

double result = Math.cbrt(-8.0);
like image 196
Etienne de Martel Avatar answered Sep 30 '22 03:09

Etienne de Martel


Remember that mathematically, there are 3 cube-roots. Assuming you want the root that is real, you should do this:

x = 8;  //  Your value

if (x > 0)
    System.out.println(Math.pow(x, 1.0 / 3.0));
else
    System.out.println(-Math.pow(-x, 1.0 / 3.0));

EDIT : As the other answers mention, there is Math.cbrt(x). (which I didn't know existed)

The reason why pow returns NaN with a negative base and non-integral power is that powering is usually done by angle-magnitude in the complex plane.

  • For positive real numbers, the angle is zero, so the answer will still be positive and real.
  • For negative real numbers, the angle is 180 degrees, which (after multiplying by a non-integral power) will always produce a complex number - hence a NaN.
like image 45
Mysticial Avatar answered Sep 30 '22 03:09

Mysticial