JavaEssential standard classesStandard classes for computations

Math library

1 minute read

Methods

The standard class Math contains a lot of methods for performing basic numeric operations including exponential, modulus, trigonometric functions, finding max/min of two numbers and so on.

The most common methods are listed below.

  • Math.abs(...) returns the absolute value of its argument;

  • Math.sqrt(...) returns the square root of its argument;

  • Math.cbrt(...) returns the cube root of its argument;

  • Math.pow(..., ...) returns the value of the first argument raised to the power of the second argument;

  • Math.min(..., ...) returns the smaller value of two arguments;

  • Math.max(..., ...) returns the greater value of two arguments;

  • Math.toRadians(...) converts an angle measured in degrees to an angle measured in radians (approximately);

  • Math.sin(...) returns the trigonometric sin of the given angle in radians;

  • Math.cos(...) returns the trigonometric cos of the given angle in radians;

  • Math.random() returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0;

  • Math.floor(...) returns the largest double value that is less than or equal to its argument and is equal to an integer;

  • Math.ceil(...) returns the smallest double value that is greater than or equal to its argument and is equal to an integer.

More useful methods see in docs.

Also, this class has two useful constants:

  • Math.PI - the ratio of the circumference of a circle to its diameter;

  • Math.E - the base of the natural logarithm.

Examples

Let's see all the listed methods in practice.

int abs = Math.abs(-10); // abs is 10
double dabs = Math.abs(-10.33); // dabs is 10.33

double sqrt = Math.sqrt(2); // sqrt is 1.4142...
double cbrt = Math.cbrt(27.0); // cbrt is 3.0

double square = Math.pow(5, 2); // the square of 5 is 25.0
double cube = Math.pow(2, 3); // the cube of 2 is 8.0

int min = Math.min(11, 81); // min is 11
int max = Math.max(20, 30); // max is 30

double grad = Math.toRadians(30); // grad is 0.5235...

double pi = Math.PI; // pi is 3.1415...
double sin = Math.sin(pi / 2); // sin is 1.0
double cos = Math.cos(pi); // cos90 is -1.0

double random = Math.random(); // a random value >= 0.0 and < 1.0

double floor = Math.floor(3.78); // floor is 3.0
double ceil = Math.ceil(4.15); // ceil is 5.0

The length of hypotenuse

Let's assume we have a right triangle (one angle is 90 degree). We know lengths of both sides: a = 3 and b = 4.

To calculate the length of hypotenuse we can write the following code:

double a = 3, b = 4;
double c = Math.hypot(a, b); // c is 5.0

As you can see, the Math class has a lot of methods for performing numeric calculations.

How did you like the theory?
Report a typo