In this article, we will give a brief overview of the Math class in Java. Let's talk about the methods of this class and how to use them. The Math class resides in the java.lang package and provides a set of static methods for performing a number of different mathematical calculations. The following are examples of calculations for which the Math class may be useful:
- Calculation of absolute values (modulo values)
- Calculation of values of trigonometric functions (sines, cosines, etc.)
- Elevation to various degrees
- Extracting roots of various degrees
- Random number generation
- Rounding
- Etc.
- static double abs(double a)
- static float abs(float a)
- static int abs(int a)
- static long abs(long a)
public static void main(String[] args) {
System.out.println(Math.abs(-1)); // 1
System.out.println(Math.abs(-21.8d)); // 21.8
System.out.println(Math.abs(4532L)); // 4532
System.out.println(Math.abs(5.341f)); // 5.341
}
Calculating the values of trigonometric functions
The Math class allows you to calculate various trigonometric functions - sines, cosines, tangents, etc. A complete list of methods can be found on the official documentation website . Below is a list of these methods:- static double sin(double a)
- static double cos(double a)
- static double tan(double a)
- static double asin(double a)
- static double acos(double a)
- static double atan(double a)
- static double toDegrees(double angrad)
- static double toRadians(double angdeg)
public static void main(String[] args) {
System.out.println(Math.sin(Math.toRadians(0)));
System.out.println(Math.sin(Math.toRadians(30)));
System.out.println(Math.sin(Math.toRadians(90)));
System.out.println(Math.cos(Math.toRadians(0)));
System.out.println(Math.cos(Math.toRadians(30)));
System.out.println(Math.cos(Math.toRadians(90)));
}
The program will output:
0.0
0.49999999999999994
1.0
1.0
0.8660254037844387
6.123233995736766E-17
Which does not quite correspond to the tables of sines and cosines, partly due to errors in the conversion from degrees to radians.
Exponentiation
To raise a number to a power, the Math class provides a pow method, which has the following signature:static double pow(double a, double b)
This method raises the parameter `a` to the power `b`. Examples:
public static void main(String[] args) {
System.out.println(Math.pow(1,2)); // 1.0
System.out.println(Math.pow(2,2)); // 4.0
System.out.println(Math.pow(3,2)); // 9.0
System.out.println(Math.pow(4,2)); // 16.0
System.out.println(Math.pow(5,2)); // 25.0
System.out.println(Math.pow(1,3)); // 1.0
System.out.println(Math.pow(2,3)); // 8.0
System.out.println(Math.pow(3,3)); // 27.0
System.out.println(Math.pow(4,3)); // 64.0
System.out.println(Math.pow(5,3)); // 125.0
}
Root extraction
The Math class provides methods for taking square and cube roots. The following methods are responsible for this procedure:- static double sqrt(double a)
- static double cbrt(double a)
public static void main(String[] args) {
System.out.println(Math.sqrt(4)); // 2.0
System.out.println(Math.sqrt(9)); // 3.0
System.out.println(Math.sqrt(16)); // 4.0
System.out.println(Math.cbrt(8)); // 2.0
System.out.println(Math.cbrt(27)); // 3.0
System.out.println(Math.cbrt(125)); // 5.0
}
Random number generation
To generate random numbers, the Math class provides the random method. This method generates a random positive real (double) number in the range from 0.0 to 1.0. The method signature looks like this:public static double random()
Let's look at examples:
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(Math.random());
}
}
After executing the main method, the following was displayed on the console:
0.37057465028778513
0.2516253742011597
0.9315649439611121
0.6346725713527239
0.7442959932755443
With a little manipulation, you can use the random method of the Math class to obtain integer random numbers lying in a certain range. Here is an example of a function that takes two arguments min and max and returns a random integer that lies in the range from min (inclusive) to max (inclusive):
static int randomInARange(int min, int max) {
return (int) (Math.random() * ((max - min) + 1)) + min;
}
Let's write a Main method in which we will test the randomInARange method:
public class MathExample {
public static void main(String[] args) {
// Карта, в которой мы будем хранить количество выпадений Howого-то числа
Map<Integer, Integer> map = new TreeMap<>();
// За 10000 операций
for (int i = 0; i < 10000; i++) {
// Сгенерируем рандомное число от -10 включительно до 10 включительно
final Integer randomNumber = randomInARange(-10, 10);
if (!map.containsKey(randomNumber)) {
// Если карта еще не содержит "выпавшего случайного числа"
// Положим его в карту с кол-вом выпадений = 1
map.put(randomNumber, 1);
} else {
// Иначе, увеличим количество выпадений данного числа на 1
map.put(randomNumber, map.get(randomNumber) + 1);
}
}
// Выведем на экран содержимое карты в формате ключ=[meaning]
for (Map.Entry<Integer, Integer> entry : map.entrySet()){
System.out.println(String.format("%d=[%d]", entry.getKey(), entry.getValue()));
}
}
static int randomInARange(int min, int max) {
return (int) (Math.random() * ((max - min) + 1)) + min;
}
}
After running the main method, the output might look like this:
-10=[482]
-9=[495]
-8=[472]
-7=[514]
-6=[457]
-5=[465]
-4=[486]
-3=[500]
-2=[490]
-1=[466]
0=[458]
1=[488]
2=[461]
3=[470]
4=[464]
5=[463]
6=[484]
7=[479]
8=[459]
9=[503]
10=[444]
Process finished with exit code 0
Rounding
For rounding numbers in Java, one of the tools is the methods of the Math class. More precisely, the round, ceil and floor methods:- static long round(double a)
- static int round(float a)
- static double floor(double a)
- static double ceil(double a)
public static void main(String[] args) {
System.out.println(Math.round(1.3)); // 1
System.out.println(Math.round(1.4)); // 1
System.out.println(Math.round(1.5)); // 2
System.out.println(Math.round(1.6)); // 2
System.out.println(Math.floor(1.3)); // 1.0
System.out.println(Math.floor(1.4)); // 1.0
System.out.println(Math.floor(1.5)); // 1.0
System.out.println(Math.floor(1.6)); // 1.0
System.out.println(Math.ceil(1.3)); // 2.0
System.out.println(Math.ceil(1.4)); // 2.0
System.out.println(Math.ceil(1.5)); // 2.0
System.out.println(Math.ceil(1.6)); // 2.0
}
Conclusion
In this article, we took a superficial look at the Math class. We looked at how using this class you can:- Calculate values modulo;
- Calculate values of trigonometric functions;
- Raise numbers to powers;
- Extract square and cube roots;
- Generate random numbers;
- Round numbers.
GO TO FULL VERSION