Lesson 5: Mathematical Functions in Java
Understanding and using mathematical methods from the Math class in Java programming.
Introduction to Math Class
Java provides many useful methods in the Math class for performing common mathematical functions. A method is a group of statements that perform a specific task.
Important Constants:
The Math class provides two useful double constants:
-
▶
Math.PI— the π constant (approximately 3.14159) -
▶
Math.E— the base of natural logarithms (approximately 2.71828)
These constants can be used in any program using Math.PI and Math.E.
Note: The Math class is in the java.lang package, which is automatically imported in all Java programs. You don't need to import it explicitly.
Trigonometric Methods
The Math class contains methods for performing trigonometric functions:
| Method | Description |
|---|---|
sin(radians) |
Returns trigonometric sine of an angle in radians |
cos(radians) |
Returns trigonometric cosine of an angle in radians |
tan(radians) |
Returns trigonometric tangent of an angle in radians |
toRadians(degree) |
Converts angle from degrees to radians |
toDegrees(radians) |
Converts angle from radians to degrees |
asin(a) |
Returns angle in radians for arcsine |
acos(a) |
Returns angle in radians for arccosine |
atan(a) |
Returns angle in radians for arctangent |
Important Notes:
-
▶
Parameters for
sin(),cos(), andtan()are angles measured in radians - ▶ 1 degree = π/180 radians, 90° = π/2 radians, 30° = π/6 radians
-
▶
Return value range:
asin()andatan()between -π/2 and π/2;acos()between 0 and π
Examples:
Math.toDegrees(Math.PI / 2) // returns 90.0
Math.toRadians(30) // returns 0.5236 (π/6)
Math.sin(0) // returns 0.0
Math.sin(Math.toRadians(270)) // returns -1.0
Math.sin(Math.PI / 6) // returns 0.5
Math.cos(0) // returns 1.0
Math.acos(0.5) // returns 1.0472 (π/3)
Math.atan(1.0) // returns 0.785398 (π/4)
Exponential Methods
The Math class provides five exponential methods:
| Method | Description |
|---|---|
exp(x) |
Returns e raised to the power x (ex) |
log(x) |
Returns natural logarithm of x (ln(x) = loge(x)) |
log10(x) |
Returns base-10 logarithm of x (log10(x)) |
pow(a, b) |
Returns a raised to the power b (ab) |
sqrt(x) |
Returns square root of x (√x) for x ≥ 0 |
Examples:
Math.exp(3.5) // returns 33.11545 (e³·⁵)
Math.log(3.5) // returns 1.25276 (ln(3.5))
Math.log10(3.5) // returns 0.544 (log₁₀(3.5))
Math.pow(2, 3) // returns 8.0 (2³)
Math.pow(4.5, 2.5) // returns 42.9567 (4.5²·⁵)
Math.sqrt(4) // returns 2.0 (√4)
Math.sqrt(10.5) // returns 3.24 (√10.5)
Rounding Methods
The Math class contains four rounding methods:
| Method | Description |
|---|---|
ceil(x) |
Rounds x upward to nearest integer. Returns as double. |
floor(x) |
Rounds x downward to nearest integer. Returns as double. |
rint(x) |
Rounds x to nearest integer. If equally distant, returns even integer as double. |
round(x) |
If x is float: returns (int)Math.floor(x + 0.5) If x is double: returns (long)Math.floor(x + 0.5) |
Examples:
Math.ceil(2.1) // returns 3.0
Math.ceil(-2.1) // returns -2.0
Math.floor(2.1) // returns 2.0
Math.floor(-2.1) // returns -3.0
Math.rint(2.1) // returns 2.0
Math.rint(2.5) // returns 2.0
Math.rint(3.5) // returns 4.0
Math.round(2.6f) // returns 3 (int)
Math.round(-2.6) // returns -3 (long)
Math.round(-2.4) // returns -2 (long)
Min, Max, Abs, and Random Methods
min() and max() methods:
Return minimum and maximum of two numbers (int, long, float, or double).
Math.max(2, 3) // returns 3
Math.min(2.5, 4.6) // returns 2.5
Math.max(Math.max(2.5, 4.6),
Math.min(3, 5.6)) // returns 4.6
abs() method:
Returns absolute value of a number (int, long, float, or double).
Math.abs(-2) // returns 2
Math.abs(-2.1) // returns 2.1
random() method:
Generates a random double value greater than or equal to 0.0 and less than 1.0 (0 ≤ Math.random() < 1.0).
General formula for random numbers in any range:
a + Math.random() * b returns a random number between a and a + b, excluding a + b.
(int)(Math.random() * 10) // random integer 0-9
50 + (int)(Math.random() * 50) // random integer 50-99
5.5 + Math.random() * 50.0 // random double 5.5-55.5
Laboratory Work
Lab 1: Calculating Triangle Angles
Objective: Write a program that calculates and displays the angles of a triangle in degrees based on entered Cartesian coordinates of its vertices.
[File name and class name: L5Lab1.java]
Mathematical Formulas:
Distance between two points: C = √((x₂ - x₁)² + (y₂ - y₁)²)
Angle in radians (Law of Cosines): α = arccos(-(a² - b² - c²) / (2bc))
Problem Analysis:
Input data:
double x1, y1, x2, y2, x3, y3; // Cartesian coordinates of three vertices
Program variables:
double a, b, c; // lengths of three sides of triangle
Output data:
double d, e, f; // three angles of triangle in degrees
Methods to use: sqrt() for square root, acos() for arccosine, toDegrees() for radians to degrees conversion.
Algorithm:
- Create a new Java file named
L5Lab1.java. - Import the Scanner class for user input (not needed for Math class as it's in java.lang).
- Define the class
L5Lab1with a main method. - Step 1: Get Cartesian coordinates of three vertices from user:
// Create Scanner object Scanner scanner = new Scanner(System.in); // Get coordinates for first vertex System.out.print("Enter x1: "); double x1 = scanner.nextDouble(); System.out.print("Enter y1: "); double y1 = scanner.nextDouble(); // Repeat for vertices 2 and 3... - Step 2: Calculate lengths of three sides using distance formula:
-
▶
a = Math.sqrt((x2 - x3)² + (y2 - y3)²)(side between vertices 2 and 3) -
▶
b = Math.sqrt((x1 - x3)² + (y1 - y3)²)(side between vertices 1 and 3) -
▶
c = Math.sqrt((x1 - x2)² + (y1 - y2)²)(side between vertices 1 and 2)
-
▶
- Step 3: Calculate three angles in degrees using Law of Cosines:
-
▶
Angle opposite side a:
d = Math.toDegrees(Math.acos((a² - b² - c²) / (-2 * b * c))) -
▶
Angle opposite side b:
e = Math.toDegrees(Math.acos((b² - a² - c²) / (-2 * a * c))) -
▶
Angle opposite side c:
f = Math.toDegrees(Math.acos((c² - b² - a²) / (-2 * a * b)))
-
▶
Angle opposite side a:
- Step 4: Display the three angles rounded to hundredths:
// Round to 2 decimal places using Math.round() double roundedD = Math.round(d * 100.0) / 100.0; double roundedE = Math.round(e * 100.0) / 100.0; double roundedF = Math.round(f * 100.0) / 100.0; System.out.printf("Angle A: %.2f degrees%n", roundedD); System.out.printf("Angle B: %.2f degrees%n", roundedE); System.out.printf("Angle C: %.2f degrees%n", roundedF); - Close the Scanner object.
- Test the program with different triangle coordinates to verify calculations.
- Add the task description as a comment at the beginning of the program.
Independent Work Tasks
Task 1: Degrees to Radians Converter
Objective: Write a program that converts entered degrees to radians and displays the result.
Expected Output:
Input: 35 Output: 0.610865
Hint: Use Math.toRadians() method for conversion.
[File name and class name: L5Task1.java]
Task 2: Random Number Generator
Objective: Write a program that generates random numbers:
- ▶ Integer from 34 to 55 (excluding 55)
- ▶ Integer from 0 to 999
- ▶ Number from 5.5 to 55.5 (excluding 55.5)
Expected Output:
Output: 42 562 32.7
Hint: Use Math.random() with appropriate formulas for each range.
[File name and class name: L5Task2.java]