Chapter 70 · Solutions
CI for a Mean — Worked Solutions ✅
Five challenges, each verified in code.
⚙️ Setup¶
In [1]:
import numpy as np, pandas as pd
from scipy import stats
rng = np.random.default_rng(700)
BASE="https://raw.githubusercontent.com/johnfisher-ai/Statistics-Data-Science-AI-Visual-Book/main/data/"
CHALLENGE 1
z-interval (sigma known)
Sigma is known to be 8. From a sample of 40 from Normal(50, 8), build a 95% z-interval for the mean.
In [2]:
s = rng.normal(50, 8, 40); xb=s.mean(); se=8/np.sqrt(40); z=stats.norm.ppf(0.975)
print(f"95% z-interval: [{xb-z*se:.2f}, {xb+z*se:.2f}]")
95% z-interval: [46.91, 51.87]
CHALLENGE 2
t-interval (sigma unknown)
Now pretend sigma is unknown: use the sample sd and the t-distribution for the same sample.
In [3]:
sd = s.std(ddof=1); se=sd/np.sqrt(40)
lo,hi = stats.t.interval(0.95, df=39, loc=s.mean(), scale=se)
print(f"95% t-interval: [{lo:.2f}, {hi:.2f}] (t* = {stats.t.ppf(0.975,39):.3f} vs z* {stats.norm.ppf(0.975):.3f})")
95% t-interval: [47.12, 51.65] (t* = 2.023 vs z* 1.960)
CHALLENGE 3
t* shrinks toward z*
Tabulate the 95% t critical value for df = 4, 9, 29, 99 and compare to z* = 1.96.
In [4]:
for d in [4,9,29,99]: print(f"df={d:>3}: t* = {stats.t.ppf(0.975,d):.3f}")
print(f"z* = {stats.norm.ppf(0.975):.3f} (t* -> z* as df grows)")
df= 4: t* = 2.776 df= 9: t* = 2.262 df= 29: t* = 2.045 df= 99: t* = 1.984 z* = 1.960 (t* -> z* as df grows)
CHALLENGE 4
Coverage check
From a skewed Gamma(3,5) population, confirm the t-interval coverage is near 95% at n=40.
In [5]:
pop=rng.gamma(3,5,800_000); MU=pop.mean()
def cov(n=40):
x=rng.choice(pop,n,replace=False); se=x.std(ddof=1)/np.sqrt(n)
lo,hi=stats.t.interval(0.95,n-1,x.mean(),se); return lo<=MU<=hi
print(f"coverage at n=40: {np.mean([cov() for _ in range(4000)])*100:.1f}%")
coverage at n=40: 94.4%
CHALLENGE 5
Real data: mean delivery time
Load confidence-intervals-for-a-mean--delivery_times.xlsx and report the 95% t-interval for the mean delivery time.
In [6]:
try: ship = pd.read_excel("../../data/confidence-intervals-for-a-mean--delivery_times.xlsx", sheet_name="Shipments")
except FileNotFoundError: ship = pd.read_excel(BASE+"confidence-intervals-for-a-mean--delivery_times.xlsx", sheet_name="Shipments")
h=ship.delivery_hours; n=len(h); se=h.std(ddof=1)/np.sqrt(n)
lo,hi=stats.t.interval(0.95,n-1,h.mean(),se)
print(f"n={n}: mean {h.mean():.2f} h, 95% t-interval [{lo:.2f}, {hi:.2f}] h")
n=180: mean 35.85 h, 95% t-interval [34.37, 37.34] h
Statistics, Data Science and AI: A Visual Handbook · © 2026 John Fisher