Chapter 72 · Solutions
Margin of Error — Worked Solutions ✅
Five challenges, each verified in code.
⚙️ Setup¶
In [1]:
import numpy as np, pandas as pd
from scipy import stats
z = stats.norm.ppf(0.975)
BASE="https://raw.githubusercontent.com/johnfisher-ai/Statistics-Data-Science-AI-Visual-Book/main/data/"
CHALLENGE 1
Compute a margin of error
A poll of 1,200 finds 47% support. Compute the 95% margin of error.
In [2]:
p,n=0.47,1200; moe=z*np.sqrt(p*(1-p)/n)
print(f"MoE = +/- {moe*100:.2f} pts -> {p*100:.0f}% +/- {moe*100:.1f}%")
MoE = +/- 2.82 pts -> 47% +/- 2.8%
CHALLENGE 2
Worst-case margin
Not knowing p, compute the WORST-CASE 95% margin for n=1,200 (use p=0.5).
In [3]:
print(f"worst case p=0.5: MoE = +/- {z*np.sqrt(0.25/1200)*100:.2f} pts")
worst case p=0.5: MoE = +/- 2.83 pts
CHALLENGE 3
Confidence widens the margin
For n=1,000 and p=0.5, tabulate the margin at 90%, 95%, 99% confidence.
In [4]:
for c in [0.90,0.95,0.99]:
zz=stats.norm.ppf(0.5+c/2); print(f"{c:.0%}: +/- {zz*np.sqrt(0.25/1000)*100:.2f} pts")
90%: +/- 2.60 pts 95%: +/- 3.10 pts 99%: +/- 4.07 pts
CHALLENGE 4
Quadruple for half
Confirm that going from n=1,000 to n=4,000 halves the margin of error.
In [5]:
m1=z*np.sqrt(0.25/1000); m4=z*np.sqrt(0.25/4000)
print(f"n=1000: +/-{m1*100:.2f} pts | n=4000: +/-{m4*100:.2f} pts | ratio {m4/m1:.2f}")
n=1000: +/-3.10 pts | n=4000: +/-1.55 pts | ratio 0.50
CHALLENGE 5
Real data: survey margin
Load margin-of-error--customer_survey.xlsx and report the recommend rate with its 95% margin of error.
In [6]:
try: s = pd.read_excel("../../data/margin-of-error--customer_survey.xlsx", sheet_name="Responses")
except FileNotFoundError: s = pd.read_excel(BASE+"margin-of-error--customer_survey.xlsx", sheet_name="Responses")
p=s.would_recommend.mean(); n=len(s); moe=z*np.sqrt(p*(1-p)/n)
print(f"n={n}: {p*100:.0f}% would recommend, +/- {moe*100:.1f} pts (95%)")
n=900: 64% would recommend, +/- 3.1 pts (95%)
Statistics, Data Science and AI: A Visual Handbook · © 2026 John Fisher