Hypothesis Tests
One-Sample t Statistic
Compute the one-sample t statistic: t = (mean − mu0) / SE, where
SE = s/√n with s = sample std (ddof=1). Two loops: first accumulates the
mean, second accumulates the squared deviations for s. Library:
scipy.stats.ttest_1samp(sample, mu0) — snapshot shows both statistic and
pvalue; RESULT is the statistic only, matching .statistic.
By hand
With the library
scipy.stats.ttest_1samp(sample, mu0) returns a result object; .statistic
is the t value and .pvalue is the two-tailed p-value (snapshot only).
import math
sample = [4, 7, 2, 9, 5, 9]
mu0 = 4
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)
t = (mean - mu0) / se
print('RESULT:', round(t, 4))
import numpy as np
from scipy import stats
from dalib.display import set_display
set_display()
sample = [4, 7, 2, 9, 5, 9]
mu0 = 4
n = len(sample)
mean = float(np.mean(sample))
s = float(np.std(sample, ddof=1))
se = float(s / np.sqrt(n))
result = stats.ttest_1samp(sample, mu0)
print('mean:', round(mean, 4))
print('se:', round(se, 6))
print('t_stat:', round(float(result.statistic), 4))
print('pvalue:', round(float(result.pvalue), 4))
print('RESULT:', round(float(result.statistic), 4))
mean: 6.0
se: 1.154701
t_stat: 1.7321
pvalue: 0.1438
RESULT: 1.7321
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 approximate normality); the p-value / interval here should be read as "how the formula is computed," not as a conclusion about a population.
Implementation notes
- Design rule §7: RESULT = statistic only; p-value appears in the snapshot for context but is not the comparable between naive and library.
- df = n−1 = 5. Under H0: mu = mu0, t follows a t distribution with 5 df.
- Two-tailed p-value: probability of |T| ≥ |t| under H0. Here p≈0.1438, so no rejection at α=0.05.
- s uses ddof=1 (sample std); using ddof=0 would understate variability and inflate the statistic.
- Cross-reference:
standard-error(ch06) for the SE computation;z-scores(ch02) for the standardization idea the t statistic extends.