Math Class
The Math class is a built-in class in many programming languages, such as Java, Python, and C#. It provides a wide range of mathematical functions that can be used to perform various calculations. Here are some common methods of the Math class:
abs(x): Returns the absolute value of x.
sqrt(x): Returns the square root of x.
pow(x, y): Returns x raised to the power of y.
log(x): Returns the natural logarithm (base e) of x.
log10(x): Returns the base 10 logarithm of x.
exp(x): Returns e raised to the power of x.
sin(x): Returns the sine of x (where x is in radians).
cos(x): Returns the cosine of x (where x is in radians).
tan(x): Returns the tangent of x (where x is in radians).
asin(x): Returns the arcsine of x (where x is in radians).
acos(x): Returns the arccosine of x (where x is in radians).
atan(x): Returns the arctangent of x (where x is in radians).
floor(x): Returns the largest integer that is less than or equal to x.
ceil(x): Returns the smallest integer that is greater than or equal to x.
round(x): Rounds x to the nearest integer.
max(x, y): Returns the larger of x and y.
min(x, y): Returns the smaller of x and y.
random(): Returns a random double value between 0.0 and 1.0.
toRadians(x): Converts an angle in degrees to radians.
toDegrees(x): Converts an angle in radians to degrees.
Example of how to use the Math class in Java
refer to:aeditfigi.compublic class MathExample {
public static void main(String[] args) {
// Calculate the absolute value of a number
int absoluteValue = Math.abs(-5);
System.out.println("Absolute value of -5 is: " + absoluteValue);
// Calculate the square root of a number
double squareRoot = Math.sqrt(25);
System.out.println("Square root of 25 is: " + squareRoot);
// Calculate the power of a number
double power = Math.pow(2, 3);
System.out.println("2 to the power of 3 is: " + power);
// Calculate the maximum value between two numbers
int max = Math.max(10, 20);
System.out.println("The maximum value between 10 and 20 is: " + max);
// Calculate the minimum value between two numbers
int min = Math.min(10, 20);
System.out.println("The minimum value between 10 and 20 is: " + min);
// Generate a random number between 0 and 1
double random = Math.random();
System.out.println("A random number between 0 and 1 is: " + random);
}
}
In this example, we use the Math class to perform various mathematical operations.
