AP® Computer Science Principles · Big Idea 3 · Topic 3.15
Random Values
RANDOM(a, b) returns every integer from a to b with equal likelihood, so a program using it can behave differently each run and still be correct, as long as each outcome is possible and fairly chosen.
Most algorithms you trace give the same output every time you run them with the same input. RANDOM breaks that pattern on purpose. RANDOM(a, b) is a command that returns a randomly selected integer from a to b, inclusive, where every integer in that range has an equal chance of being picked. A program that calls RANDOM is still correct even though its output changes run to run, because correctness here means the output always falls within the expected range and each value is equally likely, not that the output is fixed.
To find what RANDOM(a, b) can produce, list the integers from a up to b. The count of possible values is b - a + 1, and each one gets probability 1 divided by that count. So RANDOM(2, 6) can return 2, 3, 4, 5, or 6, five values total, each with probability 1/5. Run RANDOM(1, 6) a thousand times and graph the results as a bar chart: you won't get exactly 1000/6 for each bar, but with that many trials the bars end up roughly even in height, since equal likelihood is a statement about probability, not a guarantee of a perfectly even split in any particular batch of runs.
This idea connects directly to simulations, the topic that follows it. Simulations use repeated random choices to model real situations, like a weather model that picks rain or no rain each day, or a game that rolls dice for damage. None of that works unless RANDOM is trustworthy: unbiased, independent from call to call, and uniform across its range. Everything you know about equal likelihood here is what makes those larger simulations valid.
Key terms
- RANDOM(a, b)
- A command that returns an integer from a to b, inclusive, where every value in that range is equally likely.
- Equal likelihood
- Every possible outcome has exactly the same probability of being chosen.
- Uniform distribution
- A probability distribution where all outcomes in a range occur with the same chance.
- Simulation
- A program that models a real process, often using repeated random choices to represent uncertain events.
Watch it explained
- How it worksHow does RANDOM produce every integer in its range with equal likelihood?
- Worked exampleFind every value RANDOM(2, 6) can return and the chance attached to each one.
- Worked exampleShow me the spread of 1000 calls to RANDOM(1, 6) drawn as a bar chart.
- Common mistakeWhy doesn't a run of five sixes in a row mean the random generator is broken?
Check yourself
End of topic.