Java Math class provides 'cbrt' method to compute the cube root of a double value.
Signature
public static double cbrt(double a)
Example
Math.cbrt(val1)
Points to note
a. Cube root of a negative value is the negative of the cube root of that value's magnitude, i.e, cbrt(-x) == -cbrt(x)
b. If the argument is NaN, then the result is NaN.
c. If the argument is infinite, then the result is an infinity with the same sign as the argument.
d. If the argument is zero, then the result is a zero with the same sign as the argument.
Find the below working application.
CubeRootDemo.java
package com.sample.app;
public class CubeRootDemo {
public static void main(String[] args) {
double val1 = 64;
System.out.printf("Cube root of %f is %f\n\n", val1, Math.cbrt(val1));
// cbrt(-x) == -cbrt(x)
System.out.printf("cbrt(-%f) : %f\n", val1, Math.cbrt(-val1));
System.out.printf("-cbrt(%f) : %f\n\n", val1, -Math.cbrt(val1));
// If the argument is NaN, then the result is NaN.
System.out.println("cbrt(NaN) : " + Math.cbrt(Double.NaN) +"\n");
// If the argument is infinite, then the result is an infinity with the same sign as the argument
System.out.println("cbrt(NEGATIVE_INFINITY) : " + Math.cbrt(Double.NEGATIVE_INFINITY) );
System.out.println("cbrt(POSITIVE_INFINITY) : " + Math.cbrt(Double.POSITIVE_INFINITY) +"\n\n");
// If the argument is zero, then the result is a zero with the same sign as the argument.
System.out.println("cbrt(0.0) : " + Math.cbrt(0.0));
System.out.println("cbrt(-0.0) : " + Math.cbrt(-0.0));
}
}
Output
Cube root of 64.000000 is 4.000000 cbrt(-64.000000) : -4.000000 -cbrt(64.000000) : -4.000000 cbrt(NaN) : NaN cbrt(NEGATIVE_INFINITY) : -Infinity cbrt(POSITIVE_INFINITY) : Infinity cbrt(0.0) : 0.0 cbrt(-0.0) : -0.0
Previous Next Home
No comments:
Post a Comment