Sampling and Estimation
Confidence Interval for the Mean
Compute a 95% CI as mean ± t_crit × SE, where SE = s/√n (ddof=1) and
t_crit = scipy.stats.t.ppf(0.975, df=n−1) is hardcoded as a literal so
both halves use the identical critical value. Two loops for mean and sample
std; then CI = mean ± t_crit × SE. Library: scipy.stats.t.interval(0.95, df, loc=mean, scale=SE).
By hand
With the library
scipy.stats.t.interval(0.95, df, loc=mean, scale=SE) computes the same
interval using the same t critical value internally. The snapshot shows
t_crit explicitly so the match is verifiable.
import math
sample = [4, 7, 2, 9, 5, 9]
n = len(sample)
total = 0.0
for v in sample:
total = total + v
mean = total / n
sq_diff = 0.0
for v in sample:
sq_diff = sq_diff + (v - mean) ** 2
s = math.sqrt(sq_diff / (n - 1))
se = s / math.sqrt(n)
df = n - 1
t_crit = 2.570581835636314 # scipy.stats.t.ppf(0.975, df=5)
margin = t_crit * se
lower = mean - margin
upper = mean + margin
print('RESULT:', (round(lower, 4), round(upper, 4)))
import math
import numpy as np
from scipy.stats import t
from dalib.display import set_display
set_display()
sample = [4, 7, 2, 9, 5, 9]
n = len(sample)
mean = float(np.mean(sample))
s = float(np.std(sample, ddof=1))
se = s / math.sqrt(n)
df = n - 1
t_crit = float(t.ppf(0.975, df))
lo, hi = t.interval(0.95, df, loc=mean, scale=se)
print('mean:', mean, ' SE:', round(se, 6))
print('t_crit (df=5):', round(t_crit, 10))
print('RESULT:', (round(float(lo), 4), round(float(hi), 4)))
mean: 6.0 SE: 1.154701
t_crit (df=5): 2.5705818356
RESULT: (3.0317, 8.9683)
Honesty
This lesson shows the computation exactly, on a tiny pinned sample. The arithmetic is correct and reproducible, but with a sample this small the result is not a valid statistical finding — it demonstrates the mechanism, not evidence. Real inference needs an adequate sample size and assumption checks (e.g. independence and normality or large n for the CLT); the p-value / interval here should be read as "how the formula is computed," not as a conclusion about a population.
Implementation notes
- The t_crit literal
2.570581835636314equalsscipy.stats.t.ppf(0.975, 5)to full float64 precision — this is why parity holds. - Interpretation: "95% of intervals constructed this way will contain the true population mean." NOT "95% probability the true mean is in this specific interval."
- Width scales with 1/√n (via SE) and with df (wider for small samples due to higher t_crit). At large n, t_crit approaches the normal z=1.96.
- Cross-reference:
standard-error(this chapter) for the SE computation;z-scores(ch02) for the standardization concept underlying the t statistic.