Mathematical Method_Functions in Java
Mathematical Method_Functions in Java
in
Java
Objectives
• Discuss some of the common mathematical functions used in Java
such as minimum, maximum, square root, absolute value and random
number.
• Demonstrate how to use these functions in programming.
Introduction
• Java provides many useful methods in the Math class for performing
common mathematical functions.
• Java Math class provides several methods to work on math
calculations like min(), max(), avg(), sin(), cos(), tan(), round(), ceil(),
floor(), abs() etc.
● Class methods:
– Exponent Methods
– Rounding Methods
– min, max, abs, and random Methods
Math.sqrt(x)
• The Math.sqrt(x) method returns the square root
of x:
• Example:
Math.sqrt(64);
System.out.println(Math.sqrt(64)); //returns 8.0
Math.abs(x)
• The Math.abs(x) method returns the absolute (positive)
value of x.
• Example:
Math.abs(-4.7); //returns 4.7
Math.min(x,y)
• It is used to return the Smallest of two values.
• Examples:
• Math.min(a,b);
int minNum = (int) Math.min(a,b);
Math.max(x,y)
• It returns the Largest of two values.
• Examples:
• Math.max(5,2);
• int maxNum = (int) Math.max(5,2);
Math.round()
10
min, max, and abs
● max(a, b)and Examples:
min(a, b)
Returns the maximum or Math.max(2, 3) returns 3
minimum of two parameters. Math.max(2.5, 3) returns
3.0
● abs(a)
Math.min(2.5, 3.6)
Returns the absolute value of the
returns 2.5
parameter.
Math.abs(-2) returns 2
● random() Math.abs(-2.1) returns
Returns a random double value 2.1
in the range [0.0, 1.0).
11
The random Method
Generates a random double value greater than or equal to 0.0 and less
than 1.0 (0 <= Math.random() < 1.0).
Examples:
In general,
12
Try this code: