Lab 5 Solutions: Simulating Distributions with NumPy¶
These are the worked solutions, with outputs. Try the lab yourself first.
In the reading, Olaya’s manager planned her mornings with three probability models. Now you do the same for two other branches, then judge a trial with a confidence interval.
The question. The regional manager asks you for a morning plan for the University branch (baristas and breakfast boxes) and the Corniche branch (croissants), and one decision: should Corniche open at 6:30 for good?
How this lab works
Run the cells from top to bottom with Shift + Enter. Replace every
...with your code, then run the check cell under it.Extended track: after Part D, try the ★ challenges.
Submit before the next lab session: File → Download → Download .ipynb.
You may use an AI assistant for code. If you do, add a short note at the end: what you asked, what you kept and what you changed.
# Run this cell once: it defines a small helper that checks your answers.
def check(label, condition):
print(("✅ " if condition else "❌ ") + label)import numpy as np
import pandas as pd
from scipy import stats
BASE = "https://chebil.github.io/BusinessDecision/data/"
def load(name):
"""Read a course dataset from the website, or from a local copy of the repository."""
try:
return pd.read_csv(BASE + name)
except Exception: # offline, or working from a copy of the course repository
return pd.read_csv("../data/" + name)
arrivals = load("qahwa_arrivals_2025.csv")
normal_days = arrivals[(arrivals["day_type"] == "workday") & (arrivals["ramadan"] == 0)]
arrivals.head()| Column | Meaning |
|---|---|
date, weekday | the day |
day_type | workday (Sunday to Thursday) or weekend (Friday and Saturday) |
ramadan | 1 during Ramadan (1 to 29 March 2025), when mornings are much quieter |
branch, city | where |
peak_customers | customers who arrived between 8:00 and 9:00 |
croissant_demand | croissants customers asked for: sales, plus requests logged after a sell-out |
box_preorders, box_pickups | breakfast boxes pre-ordered in the app for that morning (paid at pickup), and boxes collected |
early_customers | customers between 6:30 and 7:00, counted only during the early-opening trial (Olaya and Corniche, 5 October to 9 November); empty otherwise |
normal_days keeps the workdays outside Ramadan, when mornings are alike.
Part A: Croissants at Corniche (normal distribution)¶
A1. The distribution¶
Select the Corniche rows of normal_days into corn. Store the mean and the standard deviation of its croissant_demand in mu and sigma.
corn = normal_days[normal_days["branch"] == "Corniche"]
mu = corn["croissant_demand"].mean()
sigma = corn["croissant_demand"].std()
print(f"mean {mu:.1f}, standard deviation {sigma:.1f}")mean 97.2, standard deviation 16.4
check("A1 241 normal workdays at Corniche", len(corn) == 241)
check("A1 mean and standard deviation", abs(mu - 97.2) < 0.1 and abs(sigma - 16.4) < 0.1)✅ A1 241 normal workdays at Corniche
✅ A1 mean and standard deviation
A2. Baking the mean¶
If Corniche bakes round(mu) croissants every day, on what share of the 241 days would it have sold out (demand above the quantity baked)? Store the share in soldout.
soldout = (corn["croissant_demand"] > round(mu)).mean()
print(f"sold out on {soldout:.0%} of days")sold out on 49% of days
check("A2 baking the mean sells out on about half the days", 0.4 < soldout < 0.6)✅ A2 baking the mean sells out on about half the days
A3. A service level¶
Use stats.norm.ppf to find how many croissants to bake to sell out on at most 10% of days (bake90), and at most 5% (bake95). Round up with int(np.ceil(...)).
bake90 = int(np.ceil(stats.norm.ppf(0.90, mu, sigma)))
bake95 = int(np.ceil(stats.norm.ppf(0.95, mu, sigma)))
print(bake90, bake95)119 125
check("A3 90% service level", bake90 == 119)
check("A3 95% service level", bake95 == 125)✅ A3 90% service level
✅ A3 95% service level
Part B: Baristas at University (Poisson distribution)¶
B1. Is the Poisson model plausible?¶
Select the University rows of normal_days into uni. Store the mean of peak_customers in lam and the ratio of its variance to its mean in ratio.
uni = normal_days[normal_days["branch"] == "University"]
lam = uni["peak_customers"].mean()
ratio = uni["peak_customers"].var() / lam
print(f"mean {lam:.2f}, variance / mean = {ratio:.2f}")mean 55.57, variance / mean = 0.88
check("B1 the University peak mean", abs(lam - 55.57) < 0.01)
check("B1 variance close to the mean (ratio between 0.7 and 1.3)", 0.7 < ratio < 1.3)✅ B1 the University peak mean
✅ B1 variance close to the mean (ratio between 0.7 and 1.3)
B2. How many baristas?¶
One barista serves 25 orders an hour. For 1, 2 and 3 baristas, compute the probability that more customers arrive than they can serve, with stats.poisson.sf(capacity, lam). Store the three probabilities in a list overload, in that order.
overload = [stats.poisson.sf(25 * k, lam) for k in [1, 2, 3]]
for k, prob in zip([1, 2, 3], overload):
print(f"{k} barista(s): overloaded with probability {prob:.4f}")1 barista(s): overloaded with probability 1.0000
2 barista(s): overloaded with probability 0.7479
3 barista(s): overloaded with probability 0.0053
check("B2 three probabilities, falling", len(overload) == 3 and overload[0] > overload[1] > overload[2])
check("B2 two baristas are overloaded on most workdays", overload[1] > 0.5)
check("B2 three baristas almost never", overload[2] < 0.01)✅ B2 three probabilities, falling
✅ B2 two baristas are overloaded on most workdays
✅ B2 three baristas almost never
B3. Weekends¶
Students are away at weekends. Compute lam_weekend, the mean peak_customers at University on weekend days outside Ramadan, and risk_one, the probability that one barista is overloaded.
weekend = arrivals[(arrivals["branch"] == "University") & (arrivals["day_type"] == "weekend") & (arrivals["ramadan"] == 0)]
lam_weekend = weekend["peak_customers"].mean()
risk_one = stats.poisson.sf(25, lam_weekend)
print(f"weekend mean {lam_weekend:.1f}; one barista overloaded with probability {risk_one:.4f}")weekend mean 13.9; one barista overloaded with probability 0.0024
check("B3 a quiet weekend", 10 < lam_weekend < 18)
check("B3 one barista is enough", risk_one < 0.01)✅ B3 a quiet weekend
✅ B3 one barista is enough
Part C: Breakfast boxes at University (binomial distribution)¶
C1. The pickup rate¶
Over all University rows of arrivals, what share of pre-ordered boxes were collected? Store it in p_uni.
u_all = arrivals[arrivals["branch"] == "University"]
p_uni = u_all["box_pickups"].sum() / u_all["box_preorders"].sum()
print(f"{p_uni:.3f}")0.755
check("C1 the pickup rate", abs(p_uni - 0.755) < 0.001)✅ C1 the pickup rate
C2. How many boxes for 30 pre-orders?¶
Tomorrow University has 30 pre-orders. For every number of boxes b from 20 to 30, compute the probability that more than b customers come to collect one (stats.binom.sf(b, 30, p_uni)). Store the smallest b with a probability of at most 10% in boxes.
risk = {b: stats.binom.sf(b, 30, p_uni) for b in range(20, 31)}
boxes = min(b for b, r in risk.items() if r <= 0.10)
print(boxes, round(risk[boxes], 3))26 0.042
check("C2 the smallest safe number of boxes", boxes == 26)✅ C2 the smallest safe number of boxes
C3. Preparing all 30 boxes wastes 30 × (1 − 0.755) ≈ 7.4 boxes on an average morning. In one sentence: is preparing fewer boxes than pre-orders a fair deal for the customers who pre-ordered? What could the branch do for the customer who finds no box ready?
With 26 boxes, a customer has to wait for a box made on the spot on about 4% of mornings (25 boxes would just miss the 10% limit, at 10.9%), while the waste falls from about 7 boxes to about 3.4. Since boxes are paid at pickup, nobody loses money; the branch can keep the wait short by preparing the missing box first, or offer a free coffee when it happens.
Part D: Simulation and a trial¶
D1. Simulate the University peak¶
Use a NumPy generator with seed 42 to simulate 100,000 workday peaks at University (rng.poisson). Store the simulated share of mornings with more than 75 customers in sim_share, and compare it with overload[2].
rng = np.random.default_rng(42)
sim = rng.poisson(lam, 100_000)
sim_share = (sim > 75).mean()
print(f"simulated {sim_share:.4f} formula {overload[2]:.4f}")simulated 0.0051 formula 0.0053
check("D1 100,000 simulated mornings", len(sim) == 100_000)
check("D1 the simulation agrees with the formula", abs(sim_share - overload[2]) < 0.002)✅ D1 100,000 simulated mornings
✅ D1 the simulation agrees with the formula
D2. Should Corniche open at 6:30?¶
Corniche ran the same 36-day early-opening trial as Olaya. Its break-even is also 17 customers per morning. Compute the mean of its early_customers (mean_early) and a 95% confidence interval for the long-run mean (lo, hi), with stats.t.ppf(0.975, n - 1).
early = arrivals.loc[arrivals["branch"] == "Corniche", "early_customers"].dropna()
n = len(early)
mean_early = early.mean()
se = early.std() / np.sqrt(n)
t = stats.t.ppf(0.975, n - 1)
lo, hi = mean_early - t * se, mean_early + t * se
print(f"n = {n}, mean {mean_early:.2f}, 95% CI [{lo:.2f}, {hi:.2f}]")n = 36, mean 22.36, 95% CI [19.90, 24.82]
check("D2 36 trial days", n == 36)
check("D2 the interval", abs(lo - 19.90) < 0.01 and abs(hi - 24.82) < 0.01)✅ D2 36 trial days
✅ D2 the interval
D3. Your recommendation¶
Write three sentences for the regional manager: how many baristas University needs on workdays and at weekends, and how many breakfast boxes to prepare for 30 pre-orders; how many croissants Corniche should bake, with the service level you chose; and whether Corniche should open at 6:30, explaining why your answer differs from Olaya’s (Olaya: mean 18.3, 95% CI [16.05, 20.56]).
University needs 3 baristas on workday mornings (with 2 the peak overloads them on about 75% of days, with 3 on 0.5%) but only 1 at weekends, and should prepare 26 boxes for 30 pre-orders (a wait on about 4% of mornings, about 3 boxes wasted instead of 7). Corniche should bake 119 croissants on workdays, which sells out on about 1 day in 10; baking the mean (97) sells out on about half the days. Corniche should open at 6:30: its 95% interval for early customers, [19.9, 24.8], lies entirely above the break-even of 17, whereas Olaya’s interval still includes 17, so Olaya needs a longer trial before deciding.
★ Extended challenges¶
E1. One distribution for the whole year? Compute the mean and the variance of peak_customers at University over all 365 days. Is a single Poisson model plausible? Explain the result in two sentences.
E2. Do 95% intervals catch the truth 95% of the time? Treat Corniche’s 241 workday croissant demands as the population. Draw 1,000 samples of 36 days (without replacement), build a 95% interval from each, and report the share that contains the population mean.
E3. How long a trial at Olaya? If Olaya’s early-morning mean (18.31) and standard deviation (6.66) stayed the same, how many trial days would make the lower end of the 95% interval reach 17? Use 1.96 for .
# E1: all 365 days at University
u_peak = arrivals.loc[arrivals["branch"] == "University", "peak_customers"]
print(f"mean {u_peak.mean():.1f}, variance {u_peak.var():.1f}, ratio {u_peak.var() / u_peak.mean():.1f}")mean 41.4, variance 431.5, ratio 10.4
The variance is about ten times the mean, so a single Poisson model does not fit: the year mixes busy workdays (about 56 customers), quiet weekends (about 14) and Ramadan mornings. Each kind of day has its own rate, and a mixture of rates is far more variable than any one of them, so the branch should plan each kind of day separately.
# E2: coverage of 95% intervals
population = corn["croissant_demand"].to_numpy()
true_mean = population.mean()
rng = np.random.default_rng(1)
hits = 0
for _ in range(1000):
s = rng.choice(population, 36, replace=False)
half = stats.t.ppf(0.975, 35) * s.std(ddof=1) / 6
hits += abs(s.mean() - true_mean) <= half
print(f"{hits / 1000:.1%} of the intervals contain the population mean {true_mean:.1f}")95.5% of the intervals contain the population mean 97.2
Close to 95%, as the method promises (a little higher, because sampling without replacement from only 241 days varies less than sampling from an endless population).
# E3: trial length for Olaya
n_needed = int(np.ceil((1.96 * 6.66 / (18.31 - 17)) ** 2))
print(f"about {n_needed} days")about 100 days
About 100 days, nearly three times the original trial, and only if the mean really stays at 18.3. If the true mean is closer to 17, no realistic trial will settle it; the decision then rests on whether a small possible loss is acceptable.