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));
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);
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.
NaN
.NaN
without actually putting in NaN
or infinity?
Nov 28, 2011 at 2:15
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Math.html#cbrt(double)
System.out.println(Math.cbrt(-8));
From http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html:
If the first argument is finite and less than zero
- if the second argument is a finite even integer, the result is equal to the result of raising the absolute value of the first argument to the power of the second argument
- if the second argument is a finite odd integer, the result is equal to the negative of the result of raising the absolute value of the first argument to the power of the second argument
- if the second argument is finite and not an integer, then the result is NaN.
System.out.println(Math.cbrt(-8.0));