The static method Math.pow(double a, double b)
can be used to raise the value specified in the a
, the first argument, (the base), to the power of the value specified in b
, the second argument, (the exponent). The exponent tells us how many times the base should be multiplied by itself. So, if I have the number of 5, and I want to raise it to the 3rd power, it means that I have to multiply 5 by itself for 3 times.
There are some special cases for the Math.pow()
method, as you can read in the Javadocs, here four of them taken from the Javadocs:
- If the second argument is positive or negative zero, then the result is 1.0.
- If the second argument is 1.0, then the result is the same as the first argument.
- If the second argument is NaN, then the result is NaN.
- If the first argument is NaN and the second argument is nonzero, then the result is NaN.
You can read more detail about the Math.pow()
method on the following Javadocs, Math.pow().
Let’s see a code snippet as an example:
package org.kodejava.math;
public class PowerExample {
public static void main(String[] args) {
double cubeRoot = 5d;
// Get the cubed number of cube root
// x cubed = x^3 (multiplication three times)
double cubed = Math.pow(cubeRoot, 3);
System.out.println(cubeRoot + " cubed is " + cubed);
// Raised to zero
System.out.println("Math.pow(2, 0): " + Math.pow(2, 0));
// Raised to one
System.out.println("Math.pow(2, 1): " + Math.pow(2, 1));
// Raised to NaN
System.out.println("Math.pow(2, Double.NaN): " + Math.pow(2, Double.NaN));
// NaN raised to the nonzero exponent
System.out.println("Math.pow(Double.NaN, 2): " + Math.pow(Double.NaN, 2));
}
}
Our program print the following output:
5.0 cubed is 125.0
Math.pow(2, 0): 1.0
Math.pow(2, 1): 2.0
Math.pow(2, Double.NaN): NaN
Math.pow(Double.NaN, 2): NaN
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
What is -1 raise to the power of pi?