One-Sample T-Test
Hypothesis Testing
The Everyday Workhorse for Mean Comparisons
The one-sample t-test is the most commonly used hypothesis test, applicable whenever σ is unknown — which is nearly always in practice. It provides reliable inference even with small samples.
- Quality Assurance — Testing whether product dimensions meet specifications
- Education Research — Comparing class performance against national averages
- Healthcare — Evaluating whether patient measurements differ from healthy norms
When σ is unknown, the t-test is always the right choice.
What You'll Learn
- 1State the hypotheses of a one-sample t-test and identify when it applies
- 2Explain why the t-distribution, not the normal, is the correct reference distribution
- 3Hand-compute the statistic, degrees of freedom, p-value and confidence interval
- 4Report Cohen's d for a one-sample design and size the study that detects it
Whenever a measured quantity must be checked against a fixed reference — a specification, a historical baseline, a published norm, a contractual threshold — the question reduces to whether a sample mean is compatible with a stated population value. The population standard deviation is the missing ingredient, and estimating it from the data is what changes the reference distribution from normal to Student's t.
The t-distribution has heavier tails than the normal, accounting for uncertainty in estimating σ with s. Its shape is indexed by the degrees of freedom: with it is very dispersed for small samples and converges to the standard normal as the degrees of freedom grow, at which point the t-test and the z-test coincide.
Assumptions
The assumptions carry very different weight. Independence is the one that cannot be salvaged: measurements taken from the same batch, the same subject, or the same cluster share information, and treating them as separate observations shrinks the standard error artificially. Normality is the soft one — the t-test tolerates moderate skew once n reaches about 30, and tolerates strong symmetry even at n = 15 — and it is checked rather than assumed. The measurement level requirement simply means that a mean must be interpretable, which excludes ranked categories and heavily bounded scores.
A useful distinction is between sampling from a finite population without replacement, where the sample fraction matters, and sampling with replacement or from an effectively infinite process, where it does not. Production lines, user populations and simulated data all fall into the second category.
A Worked Example From Start to Finish
A factory claims its bolts have mean diameter 10.00 mm. A quality engineer samples 20 bolts and measures each one.
The data. The 20 measurements total 199.93 mm, giving mm. The sum of squared deviations from 10.00 is 0.0169, so the corrected sum of squares about the mean is .
Step 1 — the standard deviation.
Step 2 — the standard error and the statistic.
Step 3 — the decision. With , the two-sided p-value is 0.603, far above 0.05, so the null hypothesis of a 10.00 mm mean is not rejected.
Step 4 — the interval. With , the 95 percent confidence interval is , that is from 9.9826 to 10.0104 mm. The target sits comfortably inside it.
Step 5 — the effect size. , a negligible deviation of about a tenth of a standard deviation from target.
Step 6 — what the test does not say. Failing to reject does not prove the process is centred; with the interval spans 0.028 mm, so a mean as far as 0.017 mm off target would go undetected. If the specification tolerance is tighter than that, the sample is too small regardless of the p-value. Process capability indices, which compare the tolerance width against the observed spread, are the right companion analysis here.
Checking the Distribution First
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
sample = np.array([22.1, 23.5, 21.8, 24.2, 22.9, 23.1, 22.7, 24.0, 21.5, 23.8,
22.3, 23.6, 21.9, 24.1, 22.6, 23.3, 22.0, 24.3, 21.7, 23.9])
stat_sw, p_sw = stats.shapiro(sample)
print(f"Shapiro-Wilk: W = {stat_sw:.4f}, p = {p_sw:.4f}")
print("Normal assumption OK" if p_sw > 0.05 else "Normality violated")
ad = stats.anderson(sample, dist='norm')
print(f"Anderson-Darling A^2 = {ad.statistic:.4f}, "
f"5% critical = {ad.critical_values[2]:.4f}")
fig, axes = plt.subplots(1, 3, figsize=(14, 4))
axes[0].hist(sample, bins=8, edgecolor='black', color='steelblue', alpha=0.75)
axes[0].set_title('Histogram')
stats.probplot(sample, dist='norm', plot=axes[1])
axes[1].set_title('Q-Q plot: points on the line support normality')
axes[2].boxplot(sample)
axes[2].set_title('Boxplot: whisker outliers hint at skew')
plt.tight_layout(); plt.show()
# Skewness and its rough standard error for a normal sample
skew = stats.skew(sample, bias=False)
print(f"skewness = {skew:.3f}, approx SE = {np.sqrt(6/len(sample)):.3f}")
Three checks are worth running together, because each fails differently. The Shapiro-Wilk test is powerful against many alternatives but becomes oversensitive in large samples, where it rejects for deviations too small to matter. The Q-Q plot never reduces to a single number, so it shows how the distribution departs — heavy tails, skew, or a single outlier. Skewness with its standard error gives a scale-free check: a value within two standard errors of zero is consistent with symmetry.
Choosing the Right Procedure
| Situation | Procedure | Key difference |
|---|---|---|
| Mean versus a fixed value, σ unknown | One-sample t-test | Reference distribution is t with n minus 1 df |
| Mean versus a fixed value, σ known from history | One-sample z-test | Rare; σ is almost never truly known |
| Symmetric differences, ordinal or skewed data | Wilcoxon signed-rank | Tests the median under symmetry, not the mean |
| Direction only, arbitrary distribution | Sign test | Weakest assumptions, least power |
| Proportion versus a claimed rate | One-proportion z-test | Binary outcome, normal approximation to the binomial |
| Two independent means | Welch two-sample t-test | Compares groups rather than a benchmark |
| Two matched measurements | Paired t-test | Uses within-unit differences |
Selecting the Wilcoxon signed-rank test is not automatically safer: it answers a different question (whether the distribution of values is centred at ) and, under genuine normality, it needs about 5 percent more observations to reach the same power.
Effect Size and Power for One Sample
The one-sample standardised mean difference divides the deviation by the sample standard deviation:
In the bolt example , which is negligible against Cohen's anchors of 0.2, 0.5 and 0.8. Because d and the t-statistic are locked together through , the effect size is the same quantity in either direction: a d of 0.5 at gives .
Sample size follows from the detectable effect. The normal approximation
suggests 32 observations, and the exact t calculation, which must also estimate σ, raises that to 34. For a large effect of only about 15 observations are needed; for the requirement exceeds 190. This cubic-like growth in cost is the arithmetic behind the advice to define the smallest effect worth detecting before collecting data.
from statsmodels.stats.power import TTestPower
bolt_diameters = np.array([9.98, 10.02, 9.97, 10.05, 9.99,
10.01, 9.96, 10.03, 9.98, 10.00,
9.94, 10.04, 9.97, 10.02, 9.99,
10.01, 9.96, 10.03, 9.98, 10.00])
mu_0, alpha = 10.00, 0.05
n = len(bolt_diameters)
x_bar = bolt_diameters.mean()
s = bolt_diameters.std(ddof=1)
se = s / np.sqrt(n)
t_stat = (x_bar - mu_0) / se
df = n - 1
p_value = 2 * stats.t.sf(abs(t_stat), df=df)
t_crit = stats.t.ppf(1 - alpha/2, df=df)
ci = stats.t.interval(1 - alpha, df=df, loc=x_bar, scale=se)
d = (x_bar - mu_0) / s
print(f"n = {n}, mean = {x_bar:.4f}, s = {s:.5f}, SE = {se:.5f}")
print(f"t({df}) = {t_stat:.4f}, p = {p_value:.4f}, crit = +/-{t_crit:.4f}")
print(f"95% CI = ({ci[0]:.4f}, {ci[1]:.4f}), Cohen's d = {d:.4f}")
print("Decision:", "reject H0" if p_value < alpha else "fail to reject H0")
t2, p2 = stats.ttest_1samp(bolt_diameters, popmean=mu_0)
print(f"scipy check: t = {t2:.4f}, p = {p2:.4f}")
# Power: what the study could detect, and what a target d would require
power = TTestPower()
achieved = power.solve_power(effect_size=abs(d), nobs=n,
alpha=alpha, alternative='two-sided')
needed = power.solve_power(effect_size=0.5, alpha=alpha, power=0.80)
print(f"achieved power at d = {abs(d):.3f}: {achieved:.3f}")
print(f"n for d = 0.5 at 80% power: {int(np.ceil(needed))}")
⚠️Post-hoc power is just a function of the p-value
Reading the Output Correctly
Four numbers complete a report: the statistic with its degrees of freedom, the p-value, the confidence interval for , and the effect size. A sentence such as "bolts did not differ from the 10.00 mm specification, t(19) = -0.53, p = .603, 95% CI [9.983, 10.010], d = -0.12" lets a reader reconstruct the design, judge the precision, and compare with other studies.
Two interpretive traps deserve their own warning. First, a non-significant result is not evidence of equivalence; if you need to demonstrate that the mean is within tolerance, run an equivalence test with pre-specified bounds and check that the whole confidence interval falls inside them. Second, a significant result at large n may still be operationally irrelevant, which is exactly what the effect size reveals.
Common Mistakes
Running a z-test because the sample standard deviation looks stable
Fix: Unless sigma comes from genuine prior knowledge rather than the same data, use the t-test; the difference vanishes only as n grows large.
Claiming the null is true because p is large
Fix: Report the confidence interval and, when equivalence is the claim, run a TOST procedure with pre-declared bounds.
Computing post-hoc power from the observed effect
Fix: It restates the p-value. Use the confidence interval width to describe precision instead.
Ignoring independence because the distribution looks normal
Fix: Normality of the marginal distribution says nothing about dependence between observations; cluster or sample design errors must be addressed structurally.
Best Practices
- Plot the data before testing; a dot plot with the reference line and interval communicates more than a p-value
- Pre-specify one- or two-sided and the alpha level before looking at the sample
- Report t with degrees of freedom, p, the confidence interval and Cohen's d together
- Size the study from the smallest effect of interest, not from a convenience sample
Key Takeaways
- The t-statistic is the standardised distance from the sample mean to the claimed value, measured in standard errors
- Degrees of freedom equal n minus 1 because estimating the mean from the data costs one piece of information
- The 95 percent confidence interval uses t with n minus 1 degrees of freedom, not the normal critical value
- Cohen's d for one sample is the mean deviation divided by the sample standard deviation
- Detecting d = 0.5 at 80 percent power needs about 34 observations, while d = 0.2 needs more than 190
Interview Questions
Q1: Why is the t-distribution used instead of the normal?
Because the population standard deviation is unknown and is replaced by the sample standard deviation s. That substitution adds uncertainty, and Gosset showed the resulting ratio follows a heavier-tailed distribution indexed by n minus 1 degrees of freedom.
Q2: What happens to the test as n grows?
The t-distribution converges to the standard normal, the critical value approaches 1.96, and the t-test becomes numerically identical to the z-test. The degrees of freedom also make the standard error smaller, so power rises with n for a fixed effect.
Q3: How do you distinguish a non-significant result from evidence of no effect?
By the confidence interval. A wide interval containing both zero and meaningful values means the study was inconclusive. To claim practical equivalence you must run an equivalence test, such as TOST, with bounds fixed in advance and show the interval lies inside them.
Q4: Report a one-sample t-test result correctly.
Give the statistic with degrees of freedom, the p-value, the confidence interval for the mean, and Cohen's d — for example t(19) = -0.53, p = .603, 95% CI [9.983, 10.010], d = -0.12 — plus a sentence stating what mu_0 represented.
Frequently Asked Questions
When is a one-sample t-test genuinely the right design?
When a fixed external benchmark exists and the observations are independent — testing a production mean against a specification, a class average against a national norm, or a lab replicate series against a certified reference value. If the benchmark was itself estimated from data, its uncertainty must enter the analysis, and a two-sample or regression framework is needed instead.
How many observations are enough?
There is no universal threshold. The classic n of 30 comes from the central limit theorem applying to moderate skew; for heavy-tailed data you may need more, and for symmetric data fewer. What actually matters is the effect size you must detect: power tables show the required n scaling with the inverse square of d.
Can the test handle outliers?
It is far more resistant than the z-test but not robust. A single extreme value shifts and inflates s simultaneously, which pushes the statistic toward zero in both directions. Inspect the data, and if outliers are genuine rather than errors, consider the Wilcoxon signed-rank test or a trimmed-mean procedure as a sensitivity analysis.
What if the reference value is itself uncertain?
Then the reference is an estimate, not a constant, and the correct analysis compares two estimates of uncertain precision. Treating an estimated benchmark as fixed understates the standard error and inflates the Type I error rate. Use a two-sample framework, or propagate the benchmark's uncertainty through a simulation-based interval.