AP CSA Unit 1 Day 14: Math Random Analysis
Share
Math.random() Range Analysis
Section 1.13 — The Math Class
Key Concept
Analyzing Math.random() range requires working backward from the desired output to verify the formula. Given (int)(Math.random() * a) + b, the minimum output is b (when Math.random() returns 0.0) and the maximum is a + b - 1 (when Math.random() approaches 1.0). The AP exam presents completed formulas and asks you to determine the range, or gives a desired range and asks which formula produces it. Always verify by substituting both boundary values of Math.random().
A game requires a random even number between 10 and 20, inclusive. Consider the following expressions.
Which of the expressions always produces a random even number from 10 to 20, inclusive?
Answer: (A) I and II only
The even numbers from 10 to 20 are: 10, 12, 14, 16, 18, 20 (6 values).
I: (int)(Math.random() * 6) gives 0-5. Multiply by 2: 0, 2, 4, 6, 8, 10. Add 10: 10, 12, 14, 16, 18, 20. CORRECT.
II: (int)(Math.random() * 6) gives 0-5. Multiply by 2: 0, 2, 4, 6, 8, 10. Add 10: 10, 12, 14, 16, 18, 20. CORRECT. Same result as I (multiplication is commutative here since we cast to int first).
III: (int)(Math.random() * 11) gives 0-10. Add 10: 10-20. This produces ALL integers 10-20, including odd numbers like 11, 13, 15, etc. INCORRECT.
Why Not the Others?
(B) Expression II also works. (int)(Math.random() * 6) * 2 + 10 produces the same values as I because the cast happens before multiplication in both cases.
(C) Expression I also works. Both I and II generate 0-5, multiply by 2 to get even steps, then shift by 10.
(D) Expression III generates all integers from 10 to 20, including odd numbers. It does not guarantee even results.
Common Mistake
To generate random even numbers, multiply the random range by 2 before adding the offset. This ensures only even values are produced. Simply generating a range that includes even numbers does not exclude odd numbers.
AP Exam Tip
For constrained random number questions: (1) Count how many valid values exist. (2) Generate that many random integers starting from 0. (3) Transform (multiply, add) to match the desired pattern. For even numbers: multiply by 2.