Probability for Decisions¶
Every morning the manager of the Olaya branch makes four small decisions before the first customer arrives: how many croissants to bake, how many baristas to put on the 8 o’clock peak, how many pre-ordered breakfast boxes to prepare, and (this autumn) whether opening half an hour earlier pays. None of the numbers she needs is known in advance. Tomorrow’s demand is not a number; it is a distribution.
This reading shows how to describe that uncertainty with three probability models (the normal, the Poisson and the binomial), how to simulate them with NumPy, and how to tell how much a small sample can be trusted with a confidence interval.
After this reading you can:
explain what a random variable and its distribution are, and why a decision needs more than the mean;
use the normal distribution to set a service level (how much to stock);
use the Poisson distribution for arrivals and the binomial for yes/no outcomes;
simulate a distribution with NumPy and check it against the formula;
explain sampling variability, the standard error and a 95% confidence interval, and use one to decide.
Textbook: Albright & Winston, Chapters 4–5 (probability and distributions) and 7–8 (sampling and confidence intervals), selected sections.
The data¶
One row per branch and day of 2025 (1,460 rows), with the counts behind the four decisions.
| 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 |
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")
arrivals.head()Mornings differ by type of day: weekends and Ramadan are much quieter. A distribution only makes sense for days that are alike, so we keep workdays outside Ramadan and focus on the Olaya branch.
normal_days = arrivals[(arrivals["day_type"] == "workday") & (arrivals["ramadan"] == 0)]
olaya = normal_days[normal_days["branch"] == "Olaya"]
print(len(olaya), "normal workdays at Olaya")241 normal workdays at Olaya
1. From a number to a distribution¶
A random variable is a quantity whose value we will only know later: tomorrow’s croissant demand, the customers arriving between 8 and 9, the boxes collected. Its distribution lists the values it can take and how likely each one is.
A discrete random variable takes countable values (0, 1, 2 customers…); its distribution gives a probability to each value.
A continuous one can take any value in a range (a waiting time, a weight); its distribution is a density curve, and probabilities are areas under it.
Two numbers summarise a distribution: the mean (or expected value), the long-run average, and the standard deviation, the typical distance from it. Here is the croissant demand on 241 workdays at Olaya:
import matplotlib.pyplot as plt
demand = olaya["croissant_demand"]
print(f"mean {demand.mean():.1f}, standard deviation {demand.std():.1f}, "
f"from {demand.min()} to {demand.max()}")
fig, ax = plt.subplots(figsize=(7, 3.4))
ax.hist(demand, bins=range(60, 190, 8), color="#4C9BC9", edgecolor="white")
ax.set_xlabel("croissants asked for in a day")
ax.set_ylabel("number of days")
ax.set_title("Olaya, workdays outside Ramadan")
plt.show()mean 121.8, standard deviation 19.1, from 61 to 176

The mean, about 122 croissants, is the single best guess for tomorrow. But demand was below 100 on some days and above 160 on others. A decision taken on the mean alone ignores that spread, and the spread is what costs money: unsold croissants on quiet days, disappointed customers on busy ones.
2. The normal distribution: how many croissants to bake?¶
The histogram is roughly bell-shaped and symmetric. The normal distribution with the same mean and standard deviation is a good model for it. Its main properties:
about 68% of values fall within , about 95% within , and nearly all within ;
any normal value can be turned into a z-score, , the number of standard deviations from the mean;
scipy.stats.normgives probabilities:norm.cdf(x, mu, sigma)is ,norm.sf(x, mu, sigma)is , andnorm.ppf(q, mu, sigma)returns the value with a share below it.
mu, sigma = demand.mean(), demand.std()
within_1 = ((demand - mu).abs() <= sigma).mean()
within_2 = ((demand - mu).abs() <= 2 * sigma).mean()
print(f"within 1 sd: {within_1:.1%} within 2 sd: {within_2:.1%}")
x = np.linspace(60, 190, 300)
fig, ax = plt.subplots(figsize=(7, 3.4))
ax.hist(demand, bins=range(60, 190, 8), density=True, color="#4C9BC9", edgecolor="white", label="data")
ax.plot(x, stats.norm.pdf(x, mu, sigma), color="#D2691E", lw=2.5, label=f"normal({mu:.0f}, {sigma:.0f})")
ax.set_xlabel("croissants asked for in a day")
ax.set_yticks([])
ax.legend()
plt.show()within 1 sd: 69.3% within 2 sd: 94.2%

The data follow the rule closely (about 68% and 95%), and the curve fits the histogram. Now the decision. If the branch bakes exactly the mean, 122 croissants, it sells out whenever demand is above 122:
bake = round(mu)
print(f"bake {bake}: model P(sell out) = {stats.norm.sf(bake, mu, sigma):.0%}, "
f"in the data: {(demand > bake).mean():.0%} of days")bake 122: model P(sell out) = 50%, in the data: 46% of days
Baking the mean means selling out on about half of all days (46% in the data, 50% in the model). The mean is a forecast, not a plan.
A better question is: on what share of days are we willing to sell out? That share defines a service level. To sell out on at most 10% of days, bake the 90th percentile of demand:
levels = [0.50, 0.80, 0.90, 0.95, 0.99]
plan = pd.DataFrame({
"service level": [f"{q:.0%}" for q in levels],
"bake": [int(np.ceil(stats.norm.ppf(q, mu, sigma))) for q in levels],
})
plan["extra over the mean"] = plan["bake"] - bake
plan["sold out (data)"] = [f"{(demand > b).mean():.1%}" for b in plan["bake"]]
planGoing from 50% to 90% service costs 25 extra croissants a day, and the data agree: with 147 croissants the branch sold out on 7.1% of days. Each further step costs more: 99% needs 167, 45 more than the mean. Which level is right depends on what a sell-out costs compared with a wasted croissant; Week 14 (the newsvendor model) answers that exactly. Today’s point: set the quantity from the distribution, not from the mean.
3. The Poisson distribution: staffing the 8 o’clock peak¶
Customers who walk in between 8:00 and 9:00 are counts of independent arrivals over a fixed period. When arrivals are independent and happen at a steady average rate , the count follows a Poisson distribution:
A Poisson variable has a special signature: its variance equals its mean. That gives a quick check on data:
peak = olaya["peak_customers"]
lam = peak.mean()
print(f"mean {lam:.2f}, variance {peak.var():.2f}")mean 47.97, variance 46.72
The mean (48.0) and the variance (46.7) are close, so the Poisson model is plausible. The bars below show the data; the line shows the Poisson probabilities for :
k = np.arange(25, 75)
counts = peak.value_counts().reindex(k, fill_value=0) / len(peak)
fig, ax = plt.subplots(figsize=(7, 3.4))
ax.bar(k, counts, color="#4C9BC9", label="data")
ax.plot(k, stats.poisson.pmf(k, lam), color="#D2691E", lw=2.5, marker="o", ms=3, label=f"Poisson({lam:.0f})")
ax.axvline(50.5, color="black", ls="--", lw=1)
ax.annotate("2 baristas serve\n50 an hour", xy=(50.5, 0.045), xytext=(60, 0.05), fontsize=9,
arrowprops=dict(arrowstyle="->"))
ax.set_xlabel("customers between 8:00 and 9:00")
ax.set_ylabel("share of days")
ax.legend(loc="upper left")
plt.show()
One barista serves about 25 orders an hour at the peak. With 48 customers on average, two baristas (50 an hour) look sufficient. The distribution says otherwise:
CAPACITY = 25 # orders one barista serves in the peak hour
staff = pd.DataFrame({"baristas": [1, 2, 3]})
staff["capacity"] = staff["baristas"] * CAPACITY
staff["P(overloaded), Poisson"] = [round(stats.poisson.sf(c, lam), 4) for c in staff["capacity"]]
staff["overloaded days (data)"] = [round((peak > c).mean(), 4) for c in staff["capacity"]]
staffWith two baristas, more than 50 customers arrive on 35% of workday mornings (the model and the data agree), so the queue builds about one morning in three. A third barista removes the problem almost entirely. A cheaper middle path, such as a helper who works only from 8:00 to 9:00, can now be compared on the same basis.
A trap: mixing different days. The Poisson model assumes a steady rate. Over all 365 days at Olaya, weekends and Ramadan included, the counts are a mix of several rates:
all_days = arrivals.loc[arrivals["branch"] == "Olaya", "peak_customers"]
print(f"all days: mean {all_days.mean():.1f}, variance {all_days.var():.1f}")all days: mean 40.5, variance 166.1
The variance (166) is four times the mean (40.5). That is the sign of a mixture: fit one distribution per type of day, never one for the whole year.
4. The binomial distribution: how many breakfast boxes to prepare?¶
Customers can pre-order a breakfast box in the app and pay when they collect it. Each pre-order is a yes/no outcome: collected or not. When there are independent trials, each a success with the same probability , the number of successes follows a binomial distribution:
First, estimate from the year’s pre-orders at Olaya:
p = olaya["box_pickups"].sum() / olaya["box_preorders"].sum()
print(f"share of pre-ordered boxes collected: {p:.3f}")share of pre-ordered boxes collected: 0.880
Tomorrow there are 50 pre-orders. If the kitchen prepares all 50, on average 6 boxes are never collected and thrown away. If it prepares fewer, a customer may arrive to find no box ready (it is then made on the spot, with a wait). The binomial distribution with and puts numbers on both sides:
n_pre, p = 50, 0.88
print(f"collected boxes: mean {n_pre * p:.1f}, standard deviation {np.sqrt(n_pre * p * (1 - p)):.2f}")
boxes = pd.DataFrame({"prepare": range(44, 51)})
boxes["P(a customer waits)"] = [round(stats.binom.sf(b, n_pre, p), 3) for b in boxes["prepare"]]
x = np.arange(n_pre + 1)
boxes["boxes wasted (average)"] = [round((np.maximum(b - x, 0) * stats.binom.pmf(x, n_pre, p)).sum(), 2)
for b in boxes["prepare"]]
boxescollected boxes: mean 44.0, standard deviation 2.30
If the manager accepts a wait on at most one morning in ten, she prepares 47 boxes: a customer waits on 5.1% of mornings, and on average 3.1 boxes are wasted instead of 6. The decision trades one risk against another, and the binomial distribution puts a number on each.
5. Simulating distributions with NumPy¶
Formulas exist for these three distributions, but most real problems combine several uncertain quantities, and then the easiest route is to simulate: draw many random values from each distribution and count what happens. NumPy’s random generator does this in one line per distribution. Fixing the seed makes the results reproducible.
rng = np.random.default_rng(5)
N = 100_000 # simulated mornings
sim_demand = rng.normal(mu, sigma, N) # croissants asked for
sim_peak = rng.poisson(lam, N) # customers from 8 to 9
sim_boxes = rng.binomial(50, 0.88, N) # boxes collected out of 50
print(f"sell out with 147 croissants: simulated {(sim_demand > 147).mean():.3f} formula {stats.norm.sf(147, mu, sigma):.3f}")
print(f"overloaded with 2 baristas: simulated {(sim_peak > 50).mean():.3f} formula {stats.poisson.sf(50, lam):.3f}")
print(f"a wait with 47 boxes: simulated {(sim_boxes > 47).mean():.3f} formula {stats.binom.sf(47, 50, 0.88):.3f}")sell out with 147 croissants: simulated 0.094 formula 0.093
overloaded with 2 baristas: simulated 0.350 formula 0.350
a wait with 47 boxes: simulated 0.051 formula 0.051
With 100,000 simulated mornings the shares match the formulas to two decimals. Simulation also answers questions the formulas cannot answer directly. With the plan 3 baristas, 147 croissants, 47 boxes, how often does something go wrong in a morning?
problem = (sim_demand > 147) | (sim_peak > 75) | (sim_boxes > 47)
print(f"mornings with at least one problem: {problem.mean():.1%}")mornings with at least one problem: 14.0%
Each risk looks small on its own (9%, almost 0% and 5%), but together roughly one morning in seven has a problem. Week 14 builds whole decision models this way (Monte Carlo simulation).
6. Samples vary: the early-opening trial¶
From 5 October to 9 November (36 days), Olaya opened at 6:30 instead of 7:00 and counted the customers in that extra half hour. Opening early costs about 170 SAR a day (staff and utilities), and an early customer brings about 10 SAR of margin, so the branch needs 17 customers per morning to break even.
early = arrivals.loc[arrivals["branch"] == "Olaya", "early_customers"].dropna()
print(f"{len(early)} trial days, mean {early.mean():.2f} customers, standard deviation {early.std():.2f}")36 trial days, mean 18.31 customers, standard deviation 6.66
The trial averaged 18.3 customers, above 17. Should Olaya open early for good? The 36 days are only a sample of the mornings to come. Another 36 days would have given another mean. How much can a sample mean move?
We can see it with data we know completely. Treat the 241 croissant days of section 1 as the whole population, draw many samples of 36 days, and look at their means:
population = demand.to_numpy()
rng = np.random.default_rng(7)
means = np.array([rng.choice(population, 36, replace=False).mean() for _ in range(2000)])
print(f"population mean {population.mean():.1f}")
print(f"sample means: from {means.min():.1f} to {means.max():.1f}, standard deviation {means.std():.2f}")
print(f"sigma / sqrt(36) = {population.std() / 6:.2f}")
fig, ax = plt.subplots(figsize=(7, 3.2))
ax.hist(means, bins=30, color="#4C9BC9", edgecolor="white")
ax.axvline(population.mean(), color="#D2691E", lw=2.5)
ax.set_xlabel("mean of a sample of 36 days")
ax.set_ylabel("number of samples")
plt.show()population mean 121.8
sample means: from 110.1 to 130.0, standard deviation 2.96
sigma / sqrt(36) = 3.17

Three facts appear, and they hold for almost any population:
Sample means scatter around the population mean: here from 110 to 130 croissants, around a true mean of 121.8.
Their spread, the standard error, is : 3.2 here (3.0 in the simulation, a bit less because each sample takes 36 of only 241 days). Four times as many days would halve it.
Their histogram is bell-shaped. This is the central limit theorem: the mean of a large enough sample is approximately normal, whatever the shape of the data.
7. Confidence intervals: decide with the interval, not the point¶
A 95% confidence interval for a population mean, from a sample of values with mean and standard deviation , is
where comes from the distribution with degrees of freedom (about 2.03 for ; it approaches 1.96 as grows). The method is built so that 95% of the intervals it produces contain the true mean. Check that with the croissant population: build an interval from each of 2,000 samples and count how many contain 121.8.
def ci95(sample):
n = len(sample)
m, se = np.mean(sample), np.std(sample, ddof=1) / np.sqrt(n)
t = stats.t.ppf(0.975, n - 1)
return m - t * se, m + t * se
rng = np.random.default_rng(8)
hits = 0
for _ in range(2000):
lo, hi = ci95(rng.choice(population, 36, replace=False))
hits += lo <= population.mean() <= hi
print(f"intervals that contain the true mean: {hits / 2000:.1%}")intervals that contain the true mean: 96.2%
About 95%, as promised (slightly more, again because the samples are drawn without replacement from a small population). Now the trial:
lo, hi = ci95(early)
print(f"Olaya early customers: mean {early.mean():.2f}, 95% confidence interval [{lo:.2f}, {hi:.2f}]")
print("break-even: 17 customers")Olaya early customers: mean 18.31, 95% confidence interval [16.05, 20.56]
break-even: 17 customers
The point estimate (18.3) is above break-even, but the interval, 16.05 to 20.56, contains 17. The trial is consistent with an early hour that loses a little money as well as with one that earns a good margin. Its honest conclusion is not yet proven, not profitable.
The manager has three reasonable options: extend the trial, accept the risk because the downside is small (at worst about 1 customer a day below break-even), or try a cheaper set-up that lowers the break-even. What she should not do is report 18.3 as if it were certain.
How much longer? If the mean and standard deviation stayed at the trial’s values, the interval’s lower end would reach 17 when :
s, gap = early.std(), early.mean() - 17
n_needed = int(np.ceil((1.96 * s / gap) ** 2))
print(f"about {n_needed} trial days")about 100 trial days
About 100 days in all, almost three times the trial. Precision is expensive: halving the standard error takes four times as much data.
What a confidence interval does not say. It is not the range of daily counts (single trial mornings ranged from 5 to 38 customers); it is a range for the long-run average. And “95%” describes the method, not this particular interval: either it contains the true mean or it does not.
Summary¶
| Model | Use it for | Qahwa House decision | Key result |
|---|---|---|---|
| Normal | a continuous quantity, roughly symmetric | croissants to bake | the mean (122) sells out on half the days; 147 for 90% service |
| Poisson | counts of independent arrivals at a steady rate | baristas at the peak | 2 baristas overloaded on 35% of mornings; 3 almost never |
| Binomial | yes/no outcomes of independent trials | boxes to prepare | 47 boxes for 50 pre-orders: 5% risk of a wait, half the waste |
| Sampling, CI | how far a sample mean can be from the truth | open early? | mean 18.3, but the 95% CI [16.05, 20.56] contains break-even (17) |
In every case, the decision came from the spread of the distribution, not from its mean alone.
Next week: regression, a model that explains and predicts one variable from others.