Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

A Guide to the Java Math Class

$
0
0

1. Introduction

In this tutorial, we’re going to describe the Math class that provides helpful static methods for performing numeric operations such as exponential, logarithm, etc.

2. Basic Math Functions

The first set of methods we’ll cover are the basic math functions such as the absolute value, the square root, the maximum or the minimum between two values.

2.1. abs()

The abs() method returns the absolute value of a given value:

Math.abs(-5); // returns 5

Likewise, of others that we’ll see next, abs() accepts as a parameter an int, long, float or double and returns the relative one.

2.2. pow()

Calculates and returns the value of the first argument raised to the power of the second one:

Math.pow(5,2); // returns 25

We discuss this method in more detail in here.

2.3. sqrt()

Returns the rounded positive square root of a double:

Math.sqrt(25); // returns 5

If the argument is NaN or less than zero, the result is NaN.

2.4. cbrt()

Similarly, cbrt() returns the cube root of a double:

Math.cbrt(125); // returns 5

2.5. max()

As the method’s name suggests, it returns the maximum between two values:

Math.max(5,10); // returns 10

Here again, the method accepts int, long, float or double.

2.6. min() 

In the same way, min() returns the minimum between two values:

Math.min(5,10); // returns 5

2.7. random()

Returns a pseudorandomly double greater than or equal to 0.0 and less than 1.0:

double random = Math.random()

To do this, the method creates a single instance of java.util.Random() number generator when it is called for the first time. 

After that, for all calls to this method, the same instance is used. Note that, the method is synchronized, thus can be used by more than one thread.

We can find more examples of how to generate a random in this article.

2.8. signum()

Is useful when we have to know the value’s sign:

Math.signum(-5) // returns -1

This method returns 1.0 if the argument is greater than zero or -1.0 otherwise. If the argument is zero positive or zero negative, the result is the same as the argument.

The input can be a float or a double.

2.9. copySign()

Accepts two parameters and returns the first argument with the sign of the second argument:

Math.copySign(5,-1); // returns -5

Arguments can also be float or double.

3. Exponential and Logarithmic Functions

In addition to the basic math functions, the Math class contains methods to solve exponential and logarithmic functions.

3.1. exp()

The exp() method receives a double argument and returns Euler’s number raised to the power of the argument (ex):

Math.exp(1); // returns 2.718281828459045

3.2. expm1()

Similar to the above method, expm1() computes the Euler’s number raised to the power of the argument received, but it adds -1 (ex -1):

Math.expm1(1); // returns 1.718281828459045

3.3. log()

Returns the natural logarithm of a double value:

Math.log(Math.E); // returns 1

3.4. log10()

It returns the logarithm in base 10 of the argument:

Math.log10(10); // returns 1

3.5. log1p()

Likewise the log(), but it adds 1 to the argument ln(1 + x):

Math.log1p(Math.E); // returns 1.3132616875182228

4. Trigonometric Functions

When we have to work with geometric formulas, we always need trigonometric functions; the Math class provides these for us.

4.1. sin()

Receives a single, double argument that represents an angle (in radians) and returns the trigonometric sine:

Math.sin(Math.PI/2); // returns 1

4.2. cos()

In the same way, cos() returns the trigonometric cosine of an angle (in radians):

Math.cos(0); // returns 1

4.3. tan()

Returns the trigonometric tangent of an angle (in radians):

Math.tan(Math.PI/4); // returns 1

4.4. sinh(), cosh(), tanh()

They return respectively the hyperbolic sine, hyperbolic cosine and hyperbolic tangent of a double value:

Math.sinh(Math.PI);

Math.cosh(Math.PI);

Math.tanh(Math.PI);

4.5. asin()

Returns the arc sine of the argument received:

Math.asin(1); // returns pi/2

The result is an angle in the range –pi/2 to pi/2.

4.6. acos()

Returns the arc cosine of the argument received:

Math.acos(0); // returns pi/2

The result is an angle in the range 0 to pi.

4.7. atan()

Returns the arc tangent of the argument received:

Math.atan(1); // returns pi/4

The result is an angle in the range –pi/2 to pi/2.

4.8. atan2()

Finally, atan2() receives the ordinate coordinate y and the abscissa coordinate x, and returns the angle ϑ from the conversion of rectangular coordinates (x,y) to polar coordinates (r, ϑ):

Math.atan2(1,1); // returns pi/4

4.9. toDegrees()

This method is useful when we need to convert radians to degrees:

Math.toDegrees(Math.PI); // returns 180

4.10. toRadians()

On the other hand toRadians() is useful to do the opposite conversion:

Math.toRadians(180); // returns pi

Remember that most of the methods we have seen in this section accept the argument in radians, thus, when we have an angle in degrees, this method should be used before using a trigonometric method.

For more examples, have a look in here.

5. Rounding and Other Functions

Finally, let’s have a look at rounding methods.

5.1. ceil()

ceil() is helpful when we have to round an integer to the smallest double value that is greater than or equal to the argument:

Math.ceil(Math.PI); // returns 4

In this article, we use this method to round up a number to the nearest hundred.

5.2. floor()

To round a number to the largest double that is less than or equal to the argument we should use floor():

Math.floor(Math.PI); // returns 3

5.3. getExponent()

Returns an unbiased exponent of the argument.

The argument can be a double or a float:

Math.getExponent(333.3); // returns 8

Math.getExponent(222.2f); // returns 7

5.4. IEEEreminder()

Computes the division between the first (dividend) and the second (divisor) argument and returns the remainder as prescribed by the IEEE 754 standard:

Math.IEEEremainder(5,2); // returns 1

5.5. nextAfter()

This method is useful when we need to know the neighboring of a double or a float value:

Math.nextAfter(1.95f,1); // returns 1.9499999

Math.nextAfter(1.95f,2); // returns 1.9500002

It accepts two arguments, the first is the value of which you want to know the adjacent number and the second is the direction.

5.6. nextUp()

Likewise the previous method, but this one returns the adjacent value only in the direction of a positive infinity:

Math.nextUp(1.95f); // returns 1.9500002

5.7. rint()

Returns a double that is the closest integer value of the argument:

Math.rint(1.95f); // returns 2.0

5.8. round()

Equally to the above method, but this one returns an int value if the argument is a float and a long value if the argument is a double:

int result = Math.round(1.95f); // returns 2

long result2 = Math.round(1.95) // returns 2

5.9. scalb()

Scalb is an abbreviation for a “scale binary”. This function executes one shift, one conversion and a , double multiplication:

Math.scalb(3, 4); // returns 3*2^4

5.10. ulp()

The ulp() method returns the distance from a number to its nearest neighbors:

Math.ulp(1); // returns 1.1920929E-7
Math.ulp(2); // returns 2.3841858E-7
Math.ulp(4); // returns 4.7683716E-7
Math.ulp(8); // returns 9.536743E-7

5.11. hypot()

Returns the square root of the sum of squares of its argument:

Math.hypot(4, 3); // returns 5

The method calculates the square root without intermediate overflow or underflow.

In this article, we use this method to calculate the distance between two points.

6. Java 8 Math Functions

The Math class has been revisited in Java 8 to include new methods to perform the most common arithmetic operations.

We discussed these methods in another article.

7. Constants Fields

In addition to the methods, Math class declares two constant fields:

public static final double E

public static final double PI

Which indicate the closer value to the base of the natural logarithms, and the closer value to pi, respectively.

8. Conclusion

In this article, we’ve described the APIs that Java provides for mathematical operations.

As usual, all code snippets presented in here are available over on GitHub.


Viewing all articles
Browse latest Browse all 4535

Trending Articles