Sub topic 6
Generating random numbers
This chapter assumes you can write Python functions, use loops and list comprehensions, and run a script. You also need to know how to import a module. The chapter covers the basic number generators in the random module and the errors people most often make with them.
What the random module produces
The random module generates pseudo-random numbers. A pseudo-random number comes from a deterministic algorithm (Python uses the Mersenne Twister) that starts from an internal state. The numbers look unpredictable, but the same state always produces the same sequence. The next chapters use that property for reproducible results.
The module-level functions such as random.random() all share one hidden generator that Python seeds from the operating system when it starts.
The four basic functions
| Function | Returns | Range |
|---|---|---|
| `random.random()` | float | 0.0 up to, but not including, 1.0 |
| `random.uniform(a, b)` | float | between `a` and `b` |
| `random.randint(a, b)` | int | `a` to `b`, both included |
| `random.randrange(start, stop, step)` | int | `start` up to, but not including, `stop` |
import random
print(random.random()) # for example 0.8444218515250481
print(random.uniform(1.5, 4)) # for example 2.7319
print(random.randint(1, 6)) # a die roll: 1, 2, 3, 4, 5 or 6
print(random.randrange(10)) # 0 to 9
print(random.randrange(0, 100, 5)) # 0, 5, 10, ... 95The output differs on every run. The comments show only examples.
randint and randrange handle endpoints differently
randint(1, 6) includes 6. randrange(1, 6) stops at 5, like range. This difference causes many off-by-one errors. randint(a, b) is just randrange(a, b + 1).
import random
counts = {value: 0 for value in range(1, 7)}
for _ in range(6000):
counts[random.randint(1, 6)] += 1
print(counts) # each face appears roughly 1000 timesEach face appears about 1000 times. The counts are rarely exactly equal, because random sequences have no obligation to balance out.
Scaling a float
random.random() is the building block for other ranges. To get a float in [low, high), scale and shift it:
import random
low, high = 10, 20
value = low + (high - low) * random.random()
print(low <= value < high) # Truerandom.uniform(low, high) does this for you, but there is a small difference. Because of floating-point rounding, uniform may return high itself. Use the formula above if you need the upper bound excluded.
Other distributions
random.uniform gives every value in the range equal likelihood. Real data often looks different, and the module has other generators for it.
import random
print(random.gauss(100, 15)) # normal distribution: mean 100, std dev 15
print(random.triangular(0, 10, 2)) # low, high, modeFor gauss, the first argument is the mean and the second is the standard deviation. Most results fall within about two standard deviations of the mean.
Common errors
- Calling
random.randint(0, len(items))to pick an index. It can returnlen(items), which raisesIndexError. Userandrange(len(items))orrandom.choice(items). - Passing floats to
randintorrandrange. Both require integers. Useuniformfor floats. - Passing arguments in the wrong order, such as
randint(6, 1). This raisesValueErrorbecause the range is empty. - Naming your own file
random.py. Python then imports your file instead of the standard module, andrandom.randintfails with anAttributeError. - Expecting a short run to look evenly distributed. A streak of the same value does not mean the generator is broken.
Exercise
Write a function roll_dice(n) that rolls two six-sided dice n times and returns a list of the totals. Which function should you use for each die, and why is randrange(1, 6) wrong?
Show answer
Use randint(1, 6) for each die, because it includes both 1 and 6.
import random
def rolldice(n):
return [random.randint(1, 6) + random.randint(1, 6) for in range(n)]
print(roll_dice(5)) # for example [7, 4, 9, 11, 6]
randrange(1, 6) excludes the stop value, so it only returns 1 to 5. A die built with it could never show a 6.
Exercise
You need a random float that is at least 5.0 and strictly less than 8.0. Which expression is guaranteed to meet that, and why might random.uniform(5.0, 8.0) not be?
Show answer
Use 5.0 + 3.0 * random.random(). random.random() is always below 1.0, so the result stays below 8.0. The documentation for uniform says the end point may be included because of floating-point rounding.