Cube root of a negative number

后端 未结 4 1992
情深已故
情深已故 2020-12-19 03:12

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));
相关标签:
4条回答
  • 2020-12-19 03:22

    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);
    
    0 讨论(0)
  • 2020-12-19 03:22

    http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Math.html#cbrt(double)

    System.out.println(Math.cbrt(-8));
    
    0 讨论(0)
  • 2020-12-19 03:34

    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.
    0 讨论(0)
  • 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.
    0 讨论(0)
提交回复
热议问题