The Java Math Class is a collection of constants called fields and mathematical methods that perform numerical computations. The mathematical constants contained in the math class are π and e. The code below shows how to implement each and their respective outputs.
Students taking the AP Computer Science A Exam should be familiar with the Exam Appendix - Java Quick Reference sheet. It provides the following method details:
class java.lang.Math
• static int abs(int x)
• static double abs(double x)
• static double pow(double base, double exponent)
• static double sqrt(double x)
• static double random() // returns a double in the range [0.0, 1.0)
The following code and output samples show simple implementations of these methods. Notice that each is called by first naming the class to which it belongs.
CLASS NAME . METHOD NAME
So to call the absolute value method you must type Math.abs(x) in order to evaluate the absolute value of x. Likewise for the other math class methods and fields.
The following link is to the Oracle Help Center for the Java Math Class and provides the full list of available methods including details for implementation.
https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html
Sample excerpt from Oracle documentation:
New programmers should take the time to explore some of the methods in the Math class. Learn to read the Oracle documentation and implement some of the methods. Programmers must develop the ability to lookup methods and read about their implementation in order to keep expanding their ability to code complex problems efficiently.
Math.random() Example
Since the random() method returns a double between [0, 1) (including zero but not including one), we can multiple the output by a scalar to increase the range of numbers in generates.
10*Math.random() would generate decimal values from 0 to 9.999...
We can use casting to limit the output to integers:
(int)(10*Math.random()) would generate integer values from 0 to 9.
However, we can add a constant to start the generated values from a value different from zero.
(int)(25*Math.random()) + 1 would generate integer values from 1 to 25.
[1] Write an expression that raises the square root of pi to the fourth power:
[2] Write an expression that calculates the amount after $1000 is invested for 8 years,
with an interest rate of 3% with continually compounded interest.
[3] Write an expression that randomly generates integer values that are multiples of 5 between [5, 100]
(The brackets around [5, 100] means including 5 and including 100.)
[1] Math.pow(Math.sqrt(Math.PI),4);
[2] (1000)*Math.pow(Math.E,(0.03)*(8));
[3] 5*((int)(20*Math.random())+1)