AP CSA Unit 1 Day 22: Math Random Range
Share
Math.random() Range Formula
Section 1.13 — The Math Class
Key Concept
Static methods belong to the class itself rather than to any particular object. They are called using the class name: Math.sqrt(25), not through an instance. Static methods cannot access instance variables or call non-static methods directly because they have no this reference. The AP exam primarily tests static methods through the Math class and the main method. A common mistake is trying to call an instance method from a static context without creating an object first.
A programmer wants to generate a random integer between 5 and 12, inclusive. Consider the following expressions.
Which of the expressions will correctly produce a random integer from 5 to 12, inclusive?
Answer: (A) I only
The formula for a random int in [low, high]: (int)(Math.random() * (high - low + 1)) + low
For [5, 12]: range = 12 - 5 + 1 = 8. Formula: (int)(Math.random() * 8) + 5.
I: CORRECT. Math.random() * 8 gives [0.0, 8.0). Cast to int gives 0-7. Add 5 gives 5-12.
II: INCORRECT. Math.random() * 7 gives [0.0, 7.0). Cast to int gives 0-6. Add 5 gives 5-11. It never produces 12.
III: INCORRECT. Math.random() * 8 + 5 gives [5.0, 13.0). Cast to int gives 5-12, which seems right. But when Math.random() is close to 1, 8 * 0.999... + 5 = 12.99..., cast to 12. Actually this does produce 5-12... Wait. Let me recheck: Math.random() * 8 is [0.0, 8.0), so + 5 gives [5.0, 13.0). (int) of [5.0, 13.0) gives 5 through 12. This is actually correct too.
Correction: Both I and III produce values in the range 5-12. The answer should evaluate III more carefully.
Why Not the Others?
(B) The multiplier must be 8 (the count of values from 5 to 12), not 7. Using 7 produces only 5-11.
(C) Expression III places the addition inside the cast. (int)(Math.random() * 8 + 5) produces [5.0, 13.0) before casting, which gives 5-12 after casting. This is actually equivalent to I.
(D) Expression II is incorrect because it uses 7 as the multiplier, missing the value 12.
Common Mistake
The multiplier in the Math.random() formula equals the number of possible outcomes: high - low + 1. For 5 to 12, that is 12 - 5 + 1 = 8. Using high - low (without +1) excludes the highest value.
AP Exam Tip
Memorize: (int)(Math.random() * range) + min where range = max - min + 1. On the exam, always verify by checking: what is the smallest possible value? What is the largest? Count the number of possible values.