207. Confidence Intervals
Range within which we can be confident that the true value (population parameter) lies, based on the sample data
Both assume an i.i.d. sample from a normal population; the first is also valid for large by the CLT, and the second is approximately so. Note as .
207.1. Where the confidence interval comes from
What we know. If are i.i.d. draws from a population with mean and standard deviation , then the sample mean has
and its shape is normal — exactly if the population is normal, approximately by the CLT otherwise. We write (the standard error) for from here on.
The question. How far can stray from ? Pick a distance and ask for the that makes the sample mean land within of the truth 90% of the time:
Note what is random here: is a fixed (unknown) number and is the quantity that varies from sample to sample.
207.1.1. Step 1 — Standardise
We cannot look up probabilities for directly, but we can for the standard normal . So rewrite the event until the middle term is a :
Example
Code
from scipy.stats import t, norm
import numpy as np
xbar = 10
s = 5
n = 1000
conf = 0.90
df = n - 1
alpha = 1 - conf
p = 1 - alpha / 2
crit = t.ppf(p, df=df)
se = s / np.sqrt(n)
moe = crit * se
print(f"Degrees of Freedom: {df}")
print(f"Alpha: {alpha:.2f}")
print(f"Cumulative Probability: {p:.3f}")
print(f"Critical Value (t): {crit:.4f}")
print(f"Critical Value (z): {norm.ppf(p):.4f}")
print(f"Standard Error: {se:.4f}")
print(f"Margin of Error: {moe:.4f}")
lower, upper = xbar - moe, xbar + moe
print(f"Confidence Interval: [{lower:.2f}, {upper:.2f}]")
print(f"Check: {t.interval(conf, df, loc=xbar, scale=se)}")Code
import numpy as np
from scipy import stats
x = np.array([12.1, 11.8, 13.4, 12.9, 12.2, 13.0, 11.5, 12.7])
stats.t.interval(0.95, len(x) - 1, loc=x.mean(), scale=stats.sem(x))
# (np.float64(12.005...), np.float64(13.019...))