3.3. Random Number Generation#
Many business questions involve chance: how many orders arrive tomorrow, which customers respond to a campaign, whether a shipment is late. NumPy’s np.random module produces pseudorandom numbers, values that look random but come from a formula, so you can model that chance in code. This section covers the functions you will use in later chapters, how to make random results repeatable, and a first small simulation.
The functions below belong to NumPy’s original np.random interface, whose short calls are common in older code and tutorials. NumPy now recommends a newer generator interface, np.random.default_rng(), which most later chapters and this chapter’s lab and homework use. The generator is introduced at the end of this section; its drawing functions take the same arguments.
3.3.1. Drawing Random Numbers#
The most common functions, and what each one draws:
Function |
Distribution |
Typical use |
Example |
|---|---|---|---|
|
Uniform [0, 1) |
Random decimals |
|
|
Uniform [0, 1) |
Same as |
|
|
Normal (0, 1) |
Standardized noise |
|
|
Normal (μ, σ) |
Measurements with a known mean and spread |
|
|
Integers |
Dice, counts, indexes |
|
rand and random draw the same numbers. The difference is how they take the shape: rand(2, 3) takes the dimensions as separate arguments, while random((2, 3)) takes one tuple, like most other NumPy functions.
3.3.1.1. rand() and random()#
Each call returns decimals between 0 (included) and 1 (excluded), all equally likely. With no argument you get one number; with a shape you get an array.
print(np.random.rand()) ### one number
print(np.random.rand(3)) ### 1D array of 3
print(np.random.rand(2, 3)) ### 2D array, 2 rows and 3 columns
0.5674907421743682
[0.16310752 0.62904976 0.394806 ]
[[3.49941712e-01 2.76490213e-01 8.17508073e-01]
[4.26399887e-01 1.57733811e-02 5.59737400e-04]]
print(np.random.random()) ### same as rand()
print(np.random.random(3))
print(np.random.random((2, 3))) ### the shape as one tuple
0.7715064868573643
[0.56674852 0.97231816 0.83674097]
[[0.30934726 0.27990868 0.50261859]
[0.31832068 0.63073329 0.0446786 ]]
3.3.1.2. randn() and normal()#
randn() draws from the standard normal distribution, a bell curve centered on 0 with standard deviation 1, so most values fall between -2 and 2. normal() lets you set the center and the spread:
np.random.normal(loc=0.0, scale=1.0, size=None)
loc is the mean and scale is the standard deviation. Descriptive Distributions explains the normal distribution itself; here you only need to draw from it.
print(np.random.randn()) ### one standard normal value
print(np.random.randn(2, 3)) ### 2D array of standard normal values
-0.663605101649643
[[ 1.57153689 -1.11629179 -2.57041664]
[-0.42001813 -0.22650883 -0.03727746]]
print(np.random.normal()) ### mean 0, SD 1: same as randn()
print(np.random.normal(loc=10, scale=2)) ### mean 10, SD 2
print(np.random.normal(10, 2, size=(2, 3))) ### a 2x3 array with mean 10, SD 2
-1.5314187116713192
8.932945190486388
[[ 8.67700285 11.01913213 11.84600974]
[10.60868971 10.60588179 8.84166157]]
3.3.1.3. randint()#
np.random.randint(low, high, size=None) draws whole numbers from low up to, but not including, high. With one argument, it draws from 0 up to that number.
print(np.random.randint(10)) ### 0 to 9
print(np.random.randint(5, 10)) ### 5 to 9
print(np.random.randint(1, 7, size=10)) ### ten rolls of a die
print(np.random.randint(5, 10, (3, 3))) ### a 3x3 array of integers 5 to 9
2
6
[5 4 2 3 3 5 6 1 6 5]
[[5 6 8]
[6 6 5]
[8 9 7]]
3.3.2. Sampling with choice()#
np.random.choice(a, size=None, replace=True, p=None) draws values from a list or array a instead of from a range:
size: how many values to draw, or the shape of an array of themreplace: whether a value can be drawn more than once (defaultTrue)p: the probability of each value; without it, every value is equally likely
With replace=False, each value appears at most once, which is how you pick a random subset, such as five customers to call. With p, you can make some outcomes more likely than others, such as deliveries that are late one time in ten.
regions = ['North', 'South', 'East', 'West']
print(np.random.choice(regions, size=6)) ### 6 draws, repeats allowed
print(np.random.choice(regions, size=3, replace=False)) ### 3 different regions
print(np.random.choice([3, 5, 7, 9], size=(3, 5))) ### size can be a shape
print(np.random.choice(['on time', 'late'], size=10, p=[0.9, 0.1])) ### 90% on time
['North' 'East' 'North' 'West' 'West' 'East']
['North' 'East' 'South']
[[5 9 3 9 7]
[3 9 5 7 9]
[3 9 5 3 5]]
['on time' 'late' 'late' 'on time' 'on time' 'late' 'on time' 'on time'
'on time' 'on time']
3.3.3. Reproducibility: Seeds#
Run any cell above twice and the numbers change. That is what random means, but it is a problem for teaching, debugging, and reporting: a colleague cannot check your work if your numbers differ from theirs. A seed fixes this. np.random.seed(42) sets the starting point of the pseudorandom sequence, so every call after it produces the same values each time the cell runs. The number itself does not matter; 42 is just a convention.
Below, the first two lines have no seed, so their numbers change every time you run the cell. The last two lines each start from seed 42, so they print the same five numbers, and the same ones on every run.
print(np.random.randint(1, 7, size=5)) ### no seed: different every run
print(np.random.randint(1, 7, size=5))
np.random.seed(42)
print(np.random.randint(1, 7, size=5)) ### seed 42: the same every run
np.random.seed(42)
print(np.random.randint(1, 7, size=5)) ### reset to seed 42: the same five again
[4 5 3 4 5]
[6 6 3 4 1]
[4 5 3 5 5]
[4 5 3 5 5]
A seed applies to the whole sequence that follows it, not just the next call. The second randint after a seed is also fixed, but it gives a different result from the first, because it continues the same sequence. Later chapters seed every random example, usually with a generator such as np.random.default_rng(42) (see below), so that the book’s output matches what you see when you run the cell.
3.3.4. A Small Simulation#
A simulation uses random draws to model something uncertain many times over, then summarizes the results. Suppose a store receives somewhere between 80 and 120 orders a day, each count equally likely, and about one delivery in ten is late. Rather than reasoning about a single day, the code simulates 1,000 days and looks at the pattern.
np.random.seed(42)
orders = np.random.randint(80, 121, size=1000) ### 1,000 days of 80 to 120 orders
print('Mean orders per day:', orders.mean())
print('Busiest day:', orders.max())
print('Days with more than 110 orders:', np.sum(orders > 110))
late = np.random.choice([0, 1], size=1000, p=[0.9, 0.1]) ### 1 = a late delivery, 10% of the time
print('Share of late deliveries:', late.mean())
Mean orders per day: 100.338
Busiest day: 120
Days with more than 110 orders: 264
Share of late deliveries: 0.101
The mean is close to 100, the middle of the range, and about a quarter of the days have more than 110 orders, since 10 of the 41 possible counts exceed 110. The share of late deliveries lands near the 0.1 built into the simulation. Simulation is how the probability and statistics chapters later test what a model predicts against what chance actually produces.
3.3.5. Legacy and Modern Random APIs#
Everything above uses NumPy’s original random functions, which share one global random state: np.random.seed() affects every later call anywhere in the program. NumPy now recommends a generator object instead. np.random.default_rng(42) creates a generator, usually named rng, with its own seed and its own state, and you call the drawing functions on it. The cell below draws the same kinds of values as the sections above, each with its legacy form in the comment. The modern integers() excludes high, like randint().
rng = np.random.default_rng(42) ### a generator with seed 42
print(rng.random(3)) ### like np.random.rand(3)
print(rng.random((2, 3))) ### like np.random.random((2, 3))
print(rng.standard_normal(3)) ### like np.random.randn(3)
print(rng.normal(10, 2, size=3)) ### like np.random.normal(10, 2, size=3)
print(rng.integers(1, 7, size=10)) ### like np.random.randint(1, 7, size=10)
[0.77395605 0.43887844 0.85859792]
[[0.69736803 0.09417735 0.97562235]
[0.7611397 0.78606431 0.12811363]]
[-0.85304393 0.87939797 0.77779194]
[10.1320614 12.25448241 10.93501868]
[3 2 1 4 6 1 6 5 2 4]
choice() keeps its arguments too: rng.choice(a, size=None, replace=True, p=None). Probability Models uses rng.choice() with p to simulate outcomes from a probability model.
rng = np.random.default_rng(42) ### a generator with seed 42
print(rng.choice([1, 2, 3, 4, 5], size=2)) ### same as np.random.choice
print(rng.choice(['on time', 'late'], size=10, p=[0.9, 0.1])) ### 90% on time, 10% late
print(rng.integers(1, 7, size=5)) ### modern randint: high is exclusive
[1 4]
['on time' 'on time' 'on time' 'on time' 'late' 'on time' 'on time'
'on time' 'on time' 'on time']
[2 6 5 4 3]
The modern names differ from the legacy ones in a few places. The table matches them up:
Legacy |
Modern |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Either form is fine in your own work. Use the generator form to match most of the book’s later examples and this chapter’s lab and homework. It is also the safer choice for code that others will run, because a generator’s seed cannot be disturbed by random calls elsewhere in the program.
3.3.6. Quick Reference: Random Numbers#
a = ['North', 'South', 'East', 'West'] # values to draw from
probs = [0.4, 0.3, 0.2, 0.1] # one probability per value
np.random.seed(42) # make the calls below repeatable
np.random.rand(5) # 5 decimals in [0, 1)
np.random.randint(1, 7, size=5) # 5 integers from 1 to 6
np.random.normal(10, 2, size=5) # 5 values, mean 10, SD 2
np.random.choice(a, size=3) # 3 draws from a
np.random.choice(a, size=3, replace=False) # 3 different values from a
np.random.choice(a, size=3, p=probs) # weighted draws
rng = np.random.default_rng(42) # the modern form
rng.random(5)
rng.integers(1, 7, size=5)
rng.normal(10, 2, size=5)
rng.choice(a, size=3)
3.3.7. Section Practice#
Use this short exercise to check the main workflow from this section.
### Exercise: Practice Random Number Generation
# A cafe sells between 150 and 250 coffees a day, each count equally likely,
# and 20% of customers pay with a loyalty card.
# 1. Seed NumPy with 42.
# 2. Simulate 500 days of coffee sales with np.random.randint.
# 3. Print the mean daily sales, rounded to 1 decimal, and the number of days
# with fewer than 170 sales.
# 4. Simulate 500 customers' payments with np.random.choice, drawing from
# ['cash', 'card'] with p=[0.8, 0.2], and print how many paid by card.
# Print exactly:
# Mean daily sales: 199.4
# Days under 170: 106
# Paid by card: 93
### Your code starts here
### Your code ends here
Mean daily sales: 199.4
Days under 170: 106
Paid by card: 93