Sample Size for Statistical Power
Background
Every A/B test starts with one question: how big does each arm need to be? Underpowered experiments routinely come back with "+0.3% lift, not significant" and get shipped on vibes; rigorous teams compute the required sample size up front. The standard formula closes the loop between three knobs: the noise in the metric (), the minimum detectable effect (), and the significance / power trade-off (, ).
Problem statement
Implement sample_size_per_arm(sigma, mde, z_alpha2=1.96, z_beta=0.8416) returning the per-arm sample size needed to detect a difference in means with the given parameters:
Defaults correspond to two-sided () and i.e. 80% power (). Round up to the next integer (you cannot run fractional users).
Input
sigma-float > 0, standard deviation of the primary metric per user.mde-float > 0, the minimum detectable effect (absolute difference in means you want to be able to call).z_alpha2-float, critical value for the two-sided significance level. Default1.96(alpha = 0.05).z_beta-float, critical value for the power. Default0.8416(power = 0.80).
Output
int >= 1- the required per-arm sample size, rounded up.
Examples
Example 1 - the canonical "watch time" calculation
Input: sigma = 30.0, mde = 0.3 (a 1% lift on 30 min mean)
Output: 156980
Explanation: . , ceil to .
Example 2 - tightening the MDE quadruples n
Input: sigma = 30.0, mde = 0.15
Output: 627918 # ~ 4 * 156980
Explanation: ; halving MDE multiplies by .
Example 3 - higher power (90%) needs more samples
Input: sigma = 30.0, mde = 0.3, z_alpha2 = 1.96, z_beta = 1.2816
Output: 210160
Explanation: , so .
Constraints
- Raise
ValueErrorifsigma <= 0ormde <= 0(the formula is undefined). - Use
math.ceilto round up; return a Pythonint. - The formula is for a difference-in-means test; for a difference-in-proportions test, see the variant note.
Notes
- Rule of thumb. for the default , giving the famous . The exact value is what the formula uses; the rule-of-thumb is for whiteboard arithmetic.
- Bound MDE before you optimise sample size. The smallest worthwhile MDE is bounded by what the product cares about, not by what the experiment can detect. Computing for an MDE smaller than the product cares about wastes capacity.
- CUPED. Pre-experiment variance reduction shrinks by , where is the correlation between the pre-experiment baseline and the experiment metric. With , CUPED roughly halves the required .
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Reference example: canonical watch-time n
- •Sample: tightening the MDE quadruples n
- •Example: 90% power needs more than 80%