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
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With