How to Calculate Minimum Sample Size for a T-Test in Python
Compute the minimum sample size per group for a two-sample t-test using effect size, significance level, and statistical power.
pip install scipy
Python code
28 linesimport math
from scipy.stats import norm
def min_sample_size(effect_size, alpha=0.05, power=0.8):
"""
Calculate minimum sample size for a two-sample t-test (equal groups).
Args:
effect_size: Cohen's d (standardized mean difference)
alpha: significance level (Type I error)
power: desired statistical power (1 - Type II error)
Returns:
Minimum sample size per group (rounded up)
"""
z_alpha = norm.ppf(1 - alpha / 2)
z_beta = norm.ppf(power)
n = (2 * (z_alpha + z_beta) ** 2) / (effect_size ** 2)
return math.ceil(n)
if __name__ == "__main__":
# Example: effect size 0.5, 95% confidence, 80% power
n_per_group = min_sample_size(effect_size=0.5)
print(f"Minimum sample size per group: {n_per_group}")
print(f"Total sample size (two groups): {n_per_group * 2}")
Output
Minimum sample size per group: 64
Total sample size (two groups): 128
How it works
The function uses the normal approximation to estimate the required sample size per group for a two-sample t-test. It computes z-scores for the chosen alpha and power using scipy.stats.norm.ppf. The formula n = 2 * (z_alpha + z_beta)^2 / effect_size^2 balances Type I and Type II error rates. math.ceil rounds up to ensure you meet the minimum statistical requirement. This approach is standard for balanced A/B tests before data collection begins.
Common mistakes
- Using `math.floor` instead of `math.ceil`, underestimating needed participants
- Forgetting to account for unequal group sizes in real experiments
- Using one-tailed z-values when a two-tailed test is required
Variations
- Use `statsmodels` `NormalIndPower` for more complex designs
- Add a correction factor for finite populations
Real-world use cases
- Determining participant counts for an A/B test on a marketing landing page.
- Sizing a clinical trial cohort before recruiting patients for a drug study.
- Estimating required sample sizes for user research experiments in product analytics.
Sponsored
More from A/B testing & experimentation
Keep learning
Related tutorials and quizzes for this topic.