Math Functions
Math Functions
Objectives
Java provides many useful methods in the Math class for performing
common mathematical
functions.
For example,
Math.max(2, 3) returns 3
Math.max(2.5, 3) returns 3.0
Math.min(2.5, 4.6) returns 2.5
Math.abs(-2) returns 2
Math.abs(-2.1) returns 2.1
For example,
Math.sqrt(4) returns 2.0
Math.sqrt(10.5) returns 3.24037034920393
Math.pow(2, 3) returns 8.0
Math.pow(3, 2) returns 9.0
Math.pow(4.5, 2.5)
Math.ceil(2.1) returns 3.0
Math.ceil(2.0) returns 2.0
Math.ceil(-2.0) returns -2.0
Math.ceil(-2.1) returns -2.0
Math.floor(2.1) returns 2.0
Math.floor(2.0) returns 2.0
Math.floor(-2.0) returns –2.0
Math.floor(-2.1) returns -3.0
Math.rint(2.1) returns 2.0
Math.rint(-2.0) returns –2.0
Math.rint(-2.1) returns -2.0
Math.rint(2.5) returns 2.0
Math.rint(2.6) return 3.0
Math.rint(4.5) returns 4.0
Math.rint(-2.5) returns -2.0
Math.round(2.6f) returns 3 // Returns int
Math.round(2.0) returns 2 // Returns long
Math.round(-2.0f) returns -2 // Returns int
Math.round(-2.6) returns -3 // Returns long
Math.round(-2.4) returns -2 // Returns long
Java provides support for generating random numbers primarily through the
java.lang.Math and java.util.Random classes.
Random Numbers Using the Math Class
Java provides the Math class in the java.util package to generate
random numbers.
The Math class contains the static Math.random() method to generate
random numbers of the double type
The random() method returns a double value with a positive sign,
greater than or equal to 0.0 and less than 1.0.
double x=Math.random();
System.out.println(x);
}
}
You can use the java.util.Random class to generate random numbers of different types,
such as int, float, double, long, and boolean.
To generate random numbers, first, create an instance of the Random class and then call
one of the random value generator methods, such as nextInt(), nextDouble(), or
nextLong().