Math Class
Skill 2.CSkill 4.A
Big idea: The Math class gives you absolute value, powers, square roots, and random numbers. All its methods are static, and most return doubles.
- Develop code to write expressions that incorporate calls to built-in mathematical libraries and determine the value that is produced as a result.
The four methods you need
| Call | Returns | Example |
|---|---|---|
Math.abs(x) | Same type as x | Math.abs(-7) → 7 |
Math.pow(base, exp) | double | Math.pow(2, 10) → 1024.0 |
Math.sqrt(x) | double | Math.sqrt(49) → 7.0 |
Math.random() | double in [0.0, 1.0) | 0.0 ≤ value < 1.0 |
System.out.println(Math.abs(-7));
System.out.println(Math.abs(-2.5));
System.out.println(Math.pow(2, 10));
System.out.println(Math.sqrt(49));
System.out.println(Math.sqrt(3 * 3 + 4 * 4));Output7 2.5 1024.0 7.0 5.0
Random integers in a range
Math.random() returns a double from 0.0 up to (but not including) 1.0. Multiply to stretch the range, cast to int to drop the fraction, then add to shift it.
For integers from min to max inclusive, there are max - min + 1 possible values:
// int r = (int) (Math.random() * (max - min + 1)) + min;
int die = (int) (Math.random() * 6) + 1; // 1..6
int r = (int) (Math.random() * 11) + 10; // 10..20
int coin = (int) (Math.random() * 2); // 0 or 1
System.out.println(die >= 1 && die <= 6);
System.out.println(r >= 10 && r <= 20);Outputtrue true
Reverse it: what range does this produce?
Exam questions often show the expression and ask for the range. In (int) (Math.random() * N) + K, the smallest value is K and the largest is K + N - 1.
// (int) (Math.random() * 5) + 3 gives 3, 4, 5, 6, 7
// (int) (Math.random() * 10) - 5 gives -5 .. 4
System.out.println(3 + 5 - 1);Output7Mathis injava.langand has only static methods.Math.powandMath.sqrtalways returndouble.- Random int in [min, max]:
(int) (Math.random() * (max - min + 1)) + min.
int x = Math.sqrt(16);does not compile: a double can't go into an int without a cast.- Cast the whole product:
(int) Math.random() * 6is always0.
- For range questions, plug in the extremes: 0.0 for the smallest and something like 0.999 for the largest.
Write an expression for a random int from 5 to 12 inclusive.
Show answer
(int) (Math.random() * 8) + 5, since 12 - 5 + 1 = 8.
What type is Math.pow(3, 2)?
Show answer
double (9.0).