Run the experiment ten thousand times, and say how sure you are
The problem
Questions no table can answer
How many pastries should a bakery make each morning, when the number of customers changes from day to day?
Is one person at a service desk enough, when people arrive in bursts?
A survey of 2,000 customers gives an average. How far might that be from the average of all customers?
Build a small model of the situation, let the computer live through it thousands of times, and count what happens.
New difficulty
Run the program again and the answer changes. A simulated number is an estimate, not a fact.
So, two requirements
The randomness must be controlled, and every result must say how far it can be trusted.
Concept 1
Simulate to answer
importrandomsevens =0for roll inrange(10_000):
if random.randint(1, 6) + random.randint(1, 6) ==7:
sevens +=1print(sevens /10_000) # close to 0.1667, and different on the next run
The exact answer: 6 of 36 pairs, 0.1667.
The share of successes estimates the probability. The estimate is not the answer.
Try the method first on a problem whose answer is known, before trusting it where you cannot check.
Concept 2
Pseudorandom numbers and seeds
A computer cannot produce chance. Its numbers come from a recipe, started from a seed.
The same seed gives the same sequence, every time, on every machine.
With no seed, one is taken from the clock.
That is a feature: a result that cannot be repeated cannot be checked or debugged.
importnumpyasnprng = np.random.default_rng(8410)
rng.integers(1, 7, size=10) # ten dicerng.random() # 0 to 1rng.poisson(40) # arrivalsrng.exponential(4) # a waiting timerng.choice(items, size=5) # with repeatsrng.choice(items, size=5, replace=False)
rng.permutation(items) # a random order
rng.integers(1, 7) leaves out the upper end, like range. random.randint(1, 6) includes it. Mix them up and your dice never show a six.
Concept 3
One trial, many trials
deftrial(rng):
"""Run the experiment once; return its outcome."""return rng.integers(1, 7, size=2).sum() ==7defrun_trials(trial, trials, rng):
"""Run it many times; keep every outcome.""" outcomes = np.empty(trials)
for number inrange(trials):
outcomes[number] = trial(rng)
return outcomes
rng = np.random.default_rng(1)
run_trials(trial, 10_000, rng).mean() # True counts as 1: the share
run_trials knows nothing about dice. It runs any trial. Put the randomness in one small function and the arithmetic in another, which can then be checked by hand.
Concept 3, the classic bug
One generator, made once, at the top
Every trial is the same trial
for number inrange(trials):
rng = np.random.default_rng(1)
outcomes[number] = trial(rng)
# runs, prints a number,# and the number is 0 or 1
The generator is passed along
rng = np.random.default_rng(1)
for number inrange(trials):
outcomes[number] = trial(rng)
The trial takes the generator as an argument. It does not make its own.
Never create a generator inside the loop: it restarts the sequence on every pass.
No global generators (np.random.seed, random.random()): any other code that draws changes your result.
Concept 4
An estimate is uncertain
mean = outcomes.mean()
se = outcomes.std(ddof=1) / np.sqrt(len(outcomes)) # the standard errorlow, high = mean -1.96* se, mean +1.96* se
0.167, interval 0.160 to 0.175, from 10,000 trials
Twenty seeds give twenty answers, scattered around the truth. The standard error says how scattered, from a single run.
The claim is about the method: about 95 of 100 such intervals contain the true value. About one in twenty will not.
Concept 5
More trials, slowly better
To make the error
you need
half as large
4 times the trials
a tenth as large
100 times the trials
The error shrinks with the square root of the trials.
Enough trials: the interval is narrower than the difference you care about.
Print as many digits as the standard error supports.
Hundreds of times faster than the loop. It draws in a different order, so it gives different digits from the same seed, both correct.
Simulations are compared by whether they agree within their standard errors, never digit for digit.
Concept 6
Comparing options fairly
demand = rng.poisson(40, size=10_000) # drawn onceprofit_a = profit(42, demand) # both plans, the same daysprofit_b = profit(43, demand)
difference = profit_b - profit_a # one difference per day
Test one plan on Monday's customers and another on Saturday's, and you cannot tell the plan from the day.
Give every option exactly the same random numbers. The luck is in both results and cancels out.
Interval of the difference excludes zero: the data tell them apart. Contains zero: they do not, and saying so is a result.
Concept 7
Resampling real data: the bootstrap
means = [rng.choice(sample, size=len(sample), replace=True).mean()
for number inrange(5_000)]
low, high = np.quantile(means, [0.025, 0.975])
You cannot sample the world again. The sample is your best picture of it, so draw from it, with replacement.
No formula needed: works for a median, a quantile, or a correlation as well.
Its limit is the sample: a small sample knows little about rare, extreme values.
Worked example — notebook 2
One person at the help desk, or two?
A visitor every four minutes on average; a visit takes three and a half. On paper one person keeps up.
The model
randomness in one function
→
Check
on known answers
→
Many days
with intervals
→
1 vs 2
on the same days
→
What if
it gets busier?
One person
Average wait about a quarter of an hour. One day in four is worse than twenty minutes.
Two people
On the same simulated days, the wait is under a minute.
Waiting does not grow in step with traffic: near full use, a small rise in arrivals adds a large amount of waiting.
Reporting
What goes with a simulated number
A simulated number without its seed and its number of trials cannot be checked, and without its interval cannot be judged.
the estimate and its interval;
the number of trials and the seed;
the model: what was assumed.
The simulation answers the model, not the world.
To take away
Key points
A simulation answers a question by running an experiment many times and counting.
The numbers follow from a seed. Fix it, and hold the generator in a variable.
One generator, made once, passed to every function that draws.
An estimate changes from run to run. Report its interval.
A hundred times the trials for one more decimal place.
Compare options on the same random draws.
Report the seed, the number of trials, the interval and the assumptions.