Data analysis · Intermediate · 25 min
Understand probability distributions by simulating them
By Padding · Updated 18 Nov 2026
Python 3.15 · NumPy 2.5.5 · SciPy 1.18.1 · matplotlib 3.11.2 (checked on python:3.15-slim)
You will simulate coin flips, help-line calls, waiting times, heights and incomes with NumPy, check each against its SciPy distribution, watch averages of skewed data turn bell-shaped, and save one chart that compares every simulation with its theory.
On this page
Statistics courses usually start with formulas: the binomial coefficient, e to the minus lambda, the bell curve's square root of two pi. The formulas are correct, but they hide the one thing that makes a distribution useful: the process that produces it. If you know the process, you know which distribution to reach for and when it will mislead you.
This tutorial goes the other way. You write a few lines of NumPy that act out a random process, run it 100,000 times, and only then ask SciPy what the theory predicts. Five processes cover most of what an analyst meets:
- flipping a coin 10 times and counting heads (binomial)
- counting calls to a help line in an hour (Poisson)
- timing the gap between those calls (exponential)
- building an adult's height from many small influences (normal)
- growing an income by a random percentage every year (log-normal)
Then you take the most lopsided of them, the waiting times, and watch averages of it turn into a bell curve as the sample grows. That is the central limit theorem, and it is the reason confidence intervals and A/B tests work at all.
Every script uses a seeded random generator, so your numbers match the ones printed here as long as you use the same NumPy version.
Step 1 · Create the project and install NumPy, SciPy and matplotlib
Make a throwaway folder and a virtual environment, then install the three libraries pinned to the versions this tutorial was written against:
mkdir -p ~/distributions-demo
cd ~/distributions-demo
python3 -m venv .venv
. .venv/bin/activate
pip install "numpy==2.5.5" "scipy==1.18.1" "matplotlib==3.11.2"
python -c "import numpy, scipy, matplotlib; print(numpy.__version__, scipy.__version__, matplotlib.__version__)"The pin matters more here than in most projects. NumPy promises that a seeded generator gives the same numbers on every machine for a given NumPy version, but a later version may change how some distributions are drawn. With a different version your tables will be close to the ones below, not identical.
SciPy is the largest of the three downloads, and all three together come to several tens of megabytes. On prepaid mobile data, install once on Wi-Fi: pip keeps a cache, so installing the same versions in another project later downloads nothing.
Check it worked
The last command prints 2.5.5 1.18.1 3.11.2 and your prompt starts with (.venv). If you open a new terminal later, run cd ~/distributions-demo and . .venv/bin/activate again.
Step 2 · Write the five simulations
Put every random process in one module, simulate.py. Each function takes a NumPy Generator (the object np.random.default_rng(seed) returns) instead of creating its own, so each script decides the seed and two scripts never quietly share random numbers.
Read each function as a story, not as maths. None of them calls a binomial-shaped, Poisson-shaped or normal-shaped generator for the thing it models; the shapes come out of the process.
cd ~/distributions-demo
cat > simulate.py <<'PY'
"""Simulations of everyday random processes. Each function takes a NumPy Generator."""
import numpy as np
def coin_flips(rng, people=100_000, flips=10):
"""Number of heads when each of 100,000 people flips a fair coin 10 times."""
return rng.integers(0, 2, size=(people, flips)).sum(axis=1)
def calls_per_hour(rng, hours=100_000, calls_per_hour=4):
"""Calls in each hour when every one of 3,600 seconds has a tiny chance of a call."""
seconds = 3_600
return rng.binomial(seconds, calls_per_hour / seconds, size=hours)
def waiting_minutes(rng, hours=10_000, calls_per_hour=4):
"""Minutes between calls that land at random moments over 10,000 hours."""
times = np.sort(rng.uniform(0, hours * 60, size=hours * calls_per_hour))
return np.diff(times)
def heights_cm(rng, people=100_000, nudges=50):
"""Adult height as 165 cm plus 50 small, independent nudges up or down."""
return 165 + rng.uniform(-1.7, 1.7, size=(people, nudges)).sum(axis=1)
def monthly_incomes(rng, people=100_000, years=30, start=1_000):
"""Monthly income after 30 years of random yearly changes between -10% and +20%."""
changes = rng.uniform(-0.10, 0.20, size=(people, years))
return start * np.prod(1 + changes, axis=1)
PY
. .venv/bin/activate
python -c "import numpy as np, simulate; print(simulate.coin_flips(np.random.default_rng(1), people=5))"What each process assumes:
- Coin flips.
rng.integers(0, 2, ...)draws 0 or 1 with equal chance. A 100,000 by 10 grid is 100,000 people flipping 10 times; summing each row counts their heads. - Calls per hour. An hour has 3,600 seconds. If the line gets 4 calls an hour on average and callers act independently, each second has a 4 in 3,600 chance of a call. Counting those rare successes is the Poisson process in its plainest form.
- Waiting times. Scatter 40,000 calls at random moments over 10,000 hours, sort them, and take the gaps between neighbours.
- Heights. Start at 165 cm and add 50 small, independent nudges of up to 1.7 cm either way, standing in for genes, diet and childhood health.
- Incomes. Start at 1,000 a month in any currency and, for 30 years, change it by a random percentage between -10% and +20%. Changes multiply; they do not add.
Check it worked
The last command prints five head counts between 0 and 10, [5 4 6 3 4]. No error means all five functions import cleanly.
Step 3 · Flip coins and meet the binomial
The binomial distribution answers: in n independent tries with the same chance p of success, how often do you get exactly k successes? It fits any yes/no outcome repeated a fixed number of times: replies to a survey, deliveries that arrive late, loan repayments made on time.
Simulate 100,000 people flipping a coin 10 times, then compare the share who got each number of heads with SciPy's binom.pmf (probability mass function: the chance of exactly k):
cd ~/distributions-demo
. .venv/bin/activate
cat > coins.py <<'PY'
import numpy as np
from scipy import stats
import simulate
rng = np.random.default_rng(2026)
heads = simulate.coin_flips(rng)
print("heads simulated binomial")
for k in range(11):
print(f"{k:>5} {(heads == k).mean():>9.4f} {stats.binom.pmf(k, 10, 0.5):>8.4f}")
print(f"mean heads: {heads.mean():.3f}")
print(f"8 or more heads: simulated {(heads >= 8).mean():.4f}, binomial {stats.binom.sf(7, 10, 0.5):.4f}")
PY
python coins.pybinom.sf(7, ...) is the survival function: the chance of more than 7, which is the same as 8 or more. SciPy gives every distribution the same methods (pmf or pdf, cdf, sf, mean, rvs), so once you know one you know them all.
Check it worked
You see an 11-row table where the two columns agree to about two decimal places, peaking at 5 heads (0.2483 simulated against 0.2461), then:
mean heads: 4.993
8 or more heads: simulated 0.0539, binomial 0.0547About 1 person in 20 gets 8 or more heads from a fair coin. Keep that in mind the next time a small sample looks "obviously" lopsided.
Step 4 · Count help-line calls and meet the Poisson
The Poisson distribution counts events in a fixed window of time or space when they happen independently at a steady average rate: calls per hour, card payments per minute, potholes per kilometre. It has one parameter, the average rate, and a property you can test on real data: its variance equals its mean.
cd ~/distributions-demo
. .venv/bin/activate
cat > calls.py <<'PY'
import numpy as np
from scipy import stats
import simulate
rng = np.random.default_rng(2026)
calls = simulate.calls_per_hour(rng)
print("calls simulated poisson")
for k in range(13):
print(f"{k:>5} {(calls == k).mean():>9.4f} {stats.poisson.pmf(k, 4):>7.4f}")
print(f"mean {calls.mean():.3f}, variance {calls.var():.3f}")
print(f"more than 8 calls: simulated {(calls > 8).mean():.4f}, poisson {stats.poisson.sf(8, 4):.4f}")
PY
python calls.pyThe simulation never mentioned Poisson. Many seconds, each with a small independent chance, is enough to produce it. That is also how you spot when it will fail: if calls arrive in bursts (a network outage makes everyone ring at once), the variance climbs well above the mean and the Poisson understates the busy hours.
Check it worked
The table peaks at 3 and 4 calls (both about 0.195), and the last two lines read:
mean 3.989, variance 4.002
more than 8 calls: simulated 0.0212, poisson 0.0214So if one agent can handle 8 calls an hour, about 2 hours in 100 will overflow. That is a staffing answer you can take to a manager, and you got it without a formula.
Step 5 · Time the gaps and meet the exponential
The calls in the last step arrive at random moments. The time between one call and the next follows the exponential distribution, with mean equal to 1 divided by the rate: 4 calls an hour means a 15-minute average gap. In SciPy you pass that mean as scale.
cd ~/distributions-demo
. .venv/bin/activate
cat > waits.py <<'PY'
import numpy as np
from scipy import stats
import simulate
rng = np.random.default_rng(2026)
waits = simulate.waiting_minutes(rng)
wait_dist = stats.expon(scale=15) # mean wait 60 / 4 = 15 minutes
print(f"gaps: {waits.size:,}")
print(f"mean {waits.mean():.2f} min, median {np.median(waits):.2f} min (exponential: 15.00, {wait_dist.median():.2f})")
print(f"wait over 30 min: simulated {(waits > 30).mean():.4f}, exponential {wait_dist.sf(30):.4f}")
long_waits = waits[waits > 10]
print(f"already waited 10, wait 10 more: {(long_waits > 20).mean():.4f}")
print(f"fresh start, wait over 10: {(waits > 10).mean():.4f}")
PY
python waits.pyTwo things to notice:
- The median is well below the mean. Most gaps are short and a few are very long, which pulls the mean up. Report "half of all gaps are under 10 minutes" rather than "the average gap is 15 minutes" if you want people to picture a typical wait.
- It has no memory. Among gaps that already lasted 10 minutes, the share lasting 10 more is the same as the share of all gaps longer than 10 minutes. Having waited does not make the next call any closer. That is true of independent random arrivals; it is not true of buses on a timetable or machines that wear out.
Check it worked
The script prints:
gaps: 39,999
mean 15.00 min, median 10.35 min (exponential: 15.00, 10.40)
wait over 30 min: simulated 0.1365, exponential 0.1353
already waited 10, wait 10 more: 0.5127
fresh start, wait over 10: 0.5120The last two numbers match to two decimal places.
Step 6 · Build heights and meet the normal
Adding up many small, independent influences produces the normal distribution, whatever shape each influence has on its own, as long as no single influence dominates. In heights_cm each nudge is flat (any value between -1.7 and 1.7 cm is equally likely), yet 50 of them added together give the familiar bell. That is why the normal turns up for heights, measurement errors and exam marks made of many questions, and why it fails for things that do not add up this way.
cd ~/distributions-demo
. .venv/bin/activate
cat > heights.py <<'PY'
import numpy as np
from scipy import stats
import simulate
rng = np.random.default_rng(2026)
heights = simulate.heights_cm(rng)
mean, sd = heights.mean(), heights.std()
height_dist = stats.norm(loc=mean, scale=sd)
print(f"mean {mean:.1f} cm, standard deviation {sd:.2f} cm")
for k in (1, 2, 3):
inside = (np.abs(heights - mean) < k * sd).mean()
print(f"within {k} sd: simulated {inside:.4f}, normal {stats.norm.cdf(k) - stats.norm.cdf(-k):.4f}")
print(f"taller than 180 cm: simulated {(heights > 180).mean():.4f}, normal {height_dist.sf(180):.4f}")
PY
python heights.pyThe "within k sd" lines are the 68-95-99.7 rule, checked rather than memorised. Only use it once you have reason to think the data is roughly normal; the next step shows what happens when it is not.
Check it worked
The script prints:
mean 165.0 cm, standard deviation 6.93 cm
within 1 sd: simulated 0.6823, normal 0.6827
within 2 sd: simulated 0.9542, normal 0.9545
within 3 sd: simulated 0.9974, normal 0.9973
taller than 180 cm: simulated 0.0151, normal 0.0151Step 7 · Grow incomes and meet the log-normal
Incomes do not grow by adding a fixed amount each year. They grow by percentages, and percentages multiply. Multiplying many small independent changes produces the log-normal: a distribution whose logarithm is normal. It fits incomes, house prices, company sizes and file sizes, all of which have a long right tail.
cd ~/distributions-demo
. .venv/bin/activate
cat > incomes.py <<'PY'
import numpy as np
from scipy import stats
import simulate
rng = np.random.default_rng(2026)
incomes = simulate.monthly_incomes(rng)
logs = np.log(incomes)
print(f"mean {incomes.mean():,.0f}, median {np.median(incomes):,.0f}")
print(f"people earning less than the mean: {(incomes < incomes.mean()).mean():.1%}")
print(f"skew of incomes {stats.skew(incomes):.2f}, skew of log incomes {stats.skew(logs):.2f}")
shape, loc, scale = stats.lognorm.fit(incomes, floc=0)
income_dist = stats.lognorm(shape, loc=0, scale=scale)
print(f"log-normal fit: sigma {shape:.3f}, median {scale:,.0f}")
threshold = 3 * np.median(incomes)
print(f"over 3x the median: simulated {(incomes > threshold).mean():.4f}, log-normal {income_dist.sf(threshold):.4f}")
PY
python incomes.pystats.skew measures lopsidedness: 0 is symmetric, positive means a long right tail. The incomes are clearly skewed; their logs are not, which is the test for log-normal data. floc=0 fixes the distribution's lower edge at zero, so the fit only estimates the shape (sigma of the logs) and the scale (the median).
This is the step with the most practical weight. Most people earn less than the mean, so a headline "average income" describes almost nobody. In economies with a large informal sector and a few very high earners, as in many African countries, the gap between mean and median is often wider than in this simulation. Report the median, and analyse skewed money values on a log scale.
Check it worked
The script prints:
mean 4,317, median 3,899
people earning less than the mean: 58.9%
skew of incomes 1.47, skew of log incomes -0.02
log-normal fit: sigma 0.453, median 3,896
over 3x the median: simulated 0.0072, log-normal 0.0077The skew drops from 1.47 to almost 0 once you take logs, and the fitted median is within a few units of the simulated one.
Step 8 · Watch averages become normal
The waiting times are the most lopsided data you have: skew 2. The central limit theorem says that the average of n independent values gets closer to normal as n grows, whatever the shape of the values themselves. For the exponential, the theory even says how fast: the skew of an average of n waits is 2 divided by the square root of n.
Draw 20,000 samples of each size from the simulated waits, average each sample, and measure how skewed the averages are:
cd ~/distributions-demo
. .venv/bin/activate
cat > clt.py <<'PY'
import numpy as np
from scipy import stats
import simulate
rng = np.random.default_rng(2026)
waits = simulate.waiting_minutes(rng)
sd = waits.std()
print(" n skew theory within 1.96 SE")
for n in (1, 2, 5, 30, 100):
means = rng.choice(waits, size=(20_000, n)).mean(axis=1)
se = sd / np.sqrt(n)
inside = (np.abs(means - waits.mean()) < 1.96 * se).mean()
print(f"{n:>5} {stats.skew(means):>4.2f} {2 / np.sqrt(n):>6.2f} {inside:>14.4f}")
PY
python clt.pyThe last column checks the rule behind every 95% confidence interval: the sample average lands within 1.96 standard errors of the true mean about 95% of the time. For n of 30 and more it does, from both sides. For n of 1 the 0.9486 is a coincidence: a single wait can never be far below the mean, so every miss is on the high side. The rule needs averages, not single values.
Check it worked
You see:
n skew theory within 1.96 SE
1 2.02 2.00 0.9486
2 1.35 1.41 0.9538
5 0.88 0.89 0.9558
30 0.34 0.37 0.9508
100 0.25 0.20 0.9487The skew falls as n grows and tracks the theory column. The small mismatch at 100 is sampling noise: skew estimated from 20,000 averages wobbles by a few hundredths.
Step 9 · Chart every simulation against its theory
Numbers convinced you; a chart convinces other people. chart.py reruns each simulation with the same seed and draws six panels: bars for the simulation, dots or a line for the theory, and the averages from the last step as outlines. The weights passed to hist put the bars on the same scale as the curve even when the long income tail is cut off at 12,000.
cd ~/distributions-demo
. .venv/bin/activate
cat > chart.py <<'PY'
import matplotlib
matplotlib.use("Agg") # draw to files only; no window
import matplotlib.pyplot as plt # noqa: E402
from matplotlib.ticker import MaxNLocator # noqa: E402
import numpy as np # noqa: E402
from scipy import stats # noqa: E402
import simulate # noqa: E402
plt.rcParams.update({"svg.fonttype": "none", "font.size": 9,
"axes.spines.top": False, "axes.spines.right": False})
BAR, LINE = "#9ba1ac", "#0b0c0e"
def counts_panel(ax, sample, pmf, title, xlabel):
ks = np.arange(sample.max() + 1)
ax.bar(ks, np.bincount(sample) / sample.size, color=BAR, label="simulated")
ax.plot(ks, pmf(ks), "o", color=LINE, markersize=4, label="theory")
ax.set(title=title, xlabel=xlabel, ylabel="share")
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.legend(frameon=False)
def density_panel(ax, sample, pdf, title, xlabel, low, high):
edges = np.linspace(low, high, 61)
# weights keep the bars on the same scale as the curve, even when the
# long tail beyond `high` is left off the chart
weights = np.full(sample.size, 1 / (sample.size * (edges[1] - edges[0])))
ax.hist(sample, bins=edges, weights=weights, color=BAR)
xs = np.linspace(low, high, 300)
ax.plot(xs, pdf(xs), color=LINE, linewidth=1.5)
ax.set(title=title, xlabel=xlabel, ylabel="density")
fig, axs = plt.subplots(2, 3, figsize=(12, 7), layout="constrained")
rng = np.random.default_rng(2026)
counts_panel(axs[0, 0], simulate.coin_flips(rng), lambda k: stats.binom.pmf(k, 10, 0.5),
"Coin flips: binomial", "heads in 10 flips")
rng = np.random.default_rng(2026)
counts_panel(axs[0, 1], simulate.calls_per_hour(rng), lambda k: stats.poisson.pmf(k, 4),
"Calls per hour: Poisson", "calls in one hour")
rng = np.random.default_rng(2026)
waits = simulate.waiting_minutes(rng)
density_panel(axs[0, 2], waits, stats.expon(scale=15).pdf,
"Waiting times: exponential", "minutes between calls", 0, 90)
rng = np.random.default_rng(2026)
heights = simulate.heights_cm(rng)
density_panel(axs[1, 0], heights, stats.norm(heights.mean(), heights.std()).pdf,
"Heights: normal", "height (cm)", 135, 195)
rng = np.random.default_rng(2026)
incomes = simulate.monthly_incomes(rng)
shape, _, scale = stats.lognorm.fit(incomes, floc=0)
density_panel(axs[1, 1], incomes, stats.lognorm(shape, scale=scale).pdf,
"Incomes: log-normal", "monthly income", 0, 12_000)
ax = axs[1, 2]
rng = np.random.default_rng(2026)
for n, shade in ((1, "#9ba1ac"), (5, "#6a707b"), (30, "#0b0c0e")):
means = rng.choice(waits, size=(20_000, n)).mean(axis=1)
ax.hist(means, bins=80, range=(0, 60), density=True, histtype="step",
color=shade, linewidth=1.5, label=f"average of {n}")
ax.set(title="Averages of waiting times", xlabel="average wait (minutes)", ylabel="density")
ax.legend(frameon=False)
fig.suptitle("Simulated (bars) against theory (dots and lines)", x=0.01, ha="left",
fontsize=12, fontweight="bold")
fig.savefig("distributions.svg")
fig.savefig("distributions.png", dpi=150)
print("panels:", len(fig.axes))
print("titles:", " | ".join(a.get_title() for a in fig.axes))
PY
python chart.pymatplotlib.use("Agg") draws to files only, so the script works on a server with no screen. The SVG keeps its text as text; the PNG is 12 by 7 inches at 150 dpi, 1800 by 1050 pixels.
Check it worked
The script prints panels: 6 and the six titles. Open distributions.svg in a browser. In each of the first five panels the dots or line sit on top of the bars. In the last panel the outline for single waits starts at its highest point and trails off to the right, the average of 5 is a lopsided hump, and the average of 30 is a narrow, nearly symmetric bell centred on 15 minutes.
When you are done, delete the project with rm -rf ~/distributions-demo.
Next steps
- Describe data with summary statistics applies mean, median, spread and skew to a real dataset, and helps you pick which to report.
- Calculate and explain confidence intervals the right way builds on the central limit theorem from the last two steps.
- Find and handle outliers in data shows why a long right tail, like the incomes here, is not the same as bad data.
- Plot data with matplotlib explains the Figure and Axes objects behind the final chart.
Related tutorials
- Describe data with summary statistics that tell the truthYou will summarise 1,200 generated household incomes with the mean, median, mode, standard deviation, IQR and percentiles, see why the mean misleads on skewed data, compare two districts and write up a figure that carries its spread and count.
- Calculate and explain confidence intervals the right wayYou will compute a t interval for a mean, a Wilson interval for a proportion and a bootstrap interval for a median in Python, prove by simulation that about 95 in 100 intervals catch the true value, and write the results up in sentences that say what a confidence interval does and does not mean.
- Plot data with matplotlib's figure and axes interfaceYou will draw line, bar, scatter and histogram charts with matplotlib's figure and axes interface, format their ticks as thousands, percentages and dates, annotate the busiest day, combine all four in one grid and save it as SVG and as a sharp 2x PNG.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials