JavaRush /Java Blog /Random EN /Java Math class and its methods

Java Math class and its methods

Published in the Random EN group
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.
Below we will try to look at how the Java Math class helps solve the problems listed above. Java Math class and its methods - 1Let's start analyzing the class with methods that allow you to calculate a value modulo. The abs method is responsible for this. This method is overloaded and the Math class has the following differences:
  • static double abs(double a)
  • static float abs(float a)
  • static int abs(int a)
  • static long abs(long a)
Usage example:
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)
Methods calculate: sine, cosine, tangent, arcsine, arccosine, arctangent. Each method calculates a value for angle `a`. This parameter is passed to each method and in each case is measured in radians (and not in degrees, as we are used to). There are two news here, good and bad. Let's start with the good one. The Math class has methods for converting radians to degrees and degrees to radians:
  • static double toDegrees(double angrad)
  • static double toRadians(double angdeg)
Here the toDegrees method will convert the angle angrad, measured in radians, to degrees. The toRadians method, on the contrary, converts the angle angdeg, measured in degrees, into radians. The bad news is that this happens with some error. Here is an example of calculating sines and cosines:
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)
The sqrt method takes the square root, and the cbrt method takes the cube root. Examples:
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)
The round method - rounds as usual to the average person. If the fractional part of a number is greater than or equal to 0.5, then the number will be rounded up, otherwise rounded down. The floor method always, regardless of the values ​​of the fractional part, rounds the number down (toward negative infinity). The ceil method, on the contrary, regardless of the values ​​of the fractional part, rounds numbers up (towards positive infinity). Let's look at examples:
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.
There are a lot of other interesting methods in this class. Which can be found on the official documentation website . Well, for the first acquaintance, the methods listed above are quite sufficient.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION