Java - Math Functions
Java provides a number of built-in math functions in its math library that can be used for performing mathematical operations in your programs. Here are 10 commonly used math functions in Java:
Math.abs() - This function returns the absolute value of a number, which is its value without the sign.
int num = -5;
int absNum = Math.abs(num);
System.out.println(absNum); // output: 5
Math.pow() - This function returns the value of the first argument raised to the power of the second argument.
double base = 2.0;
double exponent = 3.0;
double result = Math.pow(base, exponent);
System.out.println(result); // output: 8.0
Math.sqrt() - This function returns the square root of a number.
double num = 25.0;
double sqrtNum = Math.sqrt(num);
System.out.println(sqrtNum); // output: 5.0
Math.ceil() - This function returns the smallest integer that is greater than or equal to the given number.
double num = 3.7;
double ceilNum = Math.ceil(num);
System.out.println(ceilNum); // output: 4.0
Math.floor() - This function returns the largest integer that is less than or equal to the given number.
double num = 3.7;
double floorNum = Math.floor(num);
System.out.println(floorNum); // output: 3.0
Math.round() - This function returns the closest integer to the given number.
double num = 3.4;
long roundNum = Math.round(num);
System.out.println(roundNum); // output: 3
Math.max() - This function returns the larger of two numbers.
int num1 = 5;
int num2 = 7;
int maxNum = Math.max(num1, num2);
System.out.println(maxNum); // output: 7
Math.min() - This function returns the smaller of two numbers.
int num1 = 5;
int num2 = 7;
int minNum = Math.min(num1, num2);
System.out.println(minNum); // output: 5
Math.random() - This function returns a random number between 0.0 and 1.0.
double randNum = Math.random();
System.out.println(randNum); // output: a random decimal number between 0.0 and 1.0
Math.sin() - This function returns the sine of an angle in radians.
double angle = 45.0;
double sinAngle = Math.sin(Math.toRadians(angle));
System.out.println(sinAngle); // output: 0.7071067811865475