Two-Sample Z-Test: Compute Minimum Experiment Size
Statistics & ExperimentsModel answerLast updated
Given historical metric data and test parameters, derive the smallest total sample size that meets a specified significance level and statistical power.
Setting the Scene
You are building an experimentation toolkit. One core utility calculates how many users an A/B test needs before it starts, so the team commits to a sample size up front rather than peeking and stopping early.
What You Receive
| Parameter | Type | Description |
|---|---|---|
observed | 1-D array of floats | Historical measurements of the metric you plan to test. Used to estimate outcome variability. |
alpha | float | Two-sided significance level (e.g., 0.05). |
power | float | Desired probability of detecting a real effect (e.g., 0.8). |
delta | float | Smallest absolute mean difference worth detecting (treatment minus control). |
What You Must Return
A single integer: the minimum total number of participants across both groups combined.
Assumptions
- The test is two-sided and uses the z-distribution (normal approximation).
- Treatment and control groups are equal in size.
- Both groups share the same outcome variance, estimated from
observed. - Estimate the standard deviation using the sample formula (unbiased,
ddof=1).
Requirements
- Estimate σ from
observed. - Apply the standard per-group sample size formula for a two-sample z-test.
- Round the per-group size up to the nearest whole number, then double it. Ceiling-per-group, not ceiling-of-total.
- State the formula you use.
- Describe how you handle edge cases:
delta ≤ 0,sigma == 0, invalid ranges foralphaorpower, and insufficient data.
Example
observed = [10, 12, 9, 11, 10.5, 13, 8.5]
alpha = 0.05
power = 0.80
delta = 1.0
What is the minimum total sample size?
Hints
Hint 1
The standard error of the difference between two independent means of equal-sized groups is σ√(2/n). Rearranging for n gives the core formula — make sure the factor of 2 in the numerator is there, or you're solving a one-sample problem.
Hint 2
Two z-quantiles appear in the formula: one for the significance level and one for the power. The power quantile is z_{1−β}, not z_{β}. Using z_{0.2} instead of z_{0.8} gives a negative number and collapses the required sample size.
Hint 3
Ceiling and rounding are not the same. Always apply math.ceil to the per-group n before doubling. If you ceil the total instead you can end up with an odd number that cannot be split into two equal groups that each individually meet the requirement.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Core Formula
For a two-sided, two-sample z-test with equal group sizes, the difference in sample means has standard error:
$$SE = \sigma\sqrt{\frac{2}{n}}$$
Two conditions must hold simultaneously:
- Type I control: reject H₀ when the standardized difference exceeds z_{1−α/2}.
- Power: when the true difference equals δ, the probability of exceeding that threshold must be at least 1−β.
Combining both constraints and solving for n:
$$n = \frac{2,\sigma^2,(z_{1-\alpha/2} + z_{1-\beta})^2}{\delta^2}$$
Total participants: N = 2⌈n⌉. The ceiling is applied per group, not to the total, because each group independently needs at least n whole users.
σ is estimated with the sample standard deviation of observed (dividing by m−1, not m), which gives an unbiased variance estimate.
Worked Example
For the inputs above, NumPy gives a sample SD of roughly 1.479.
- z_{0.975} = 1.960, z_{0.80} = 0.842, sum = 2.802, squared ≈ 7.851
- n = 2 × 1.479² × 7.851 / 1.0² ≈ 34.35
- ⌈34.35⌉ = 35 per group → N = 70
Edge Cases
| Situation | Response | Rationale |
|---|---|---|
len(observed) < 2 | ValueError | Sample SD with ddof=1 requires at least two points. |
NaN or infinite values in observed | ValueError | These silently propagate to a NaN sample size. |
delta ≤ 0 | ValueError | Detecting a zero or negative effect size is meaningless; δ = 0 requires infinite samples. |
alpha or power outside (0, 1) | ValueError | The z-quantiles are undefined or infinite at the boundaries. |
sigma == 0 | return 2 | Zero variance means any nonzero δ is trivially detectable. The formula yields 0, but an experiment needs at least one unit per group. Raising an error is equally defensible if you state why. |
In an interview, it matters more that you acknowledge the sigma == 0 case explicitly and justify your convention than which convention you pick.
Python Solution
import math
from statistics import NormalDist
import numpy as np
def min_total_sample_size(
observed, alpha: float, power: float, delta: float
) -> int:
"""
Minimum total sample size for a two-sided, two-sample z-test
with equal group sizes and variance estimated from `observed`.
Formula (per group):
n = 2 * sigma^2 * (z_{1-alpha/2} + z_{1-beta})^2 / delta^2
Total:
N = 2 * ceil(n)
"""
x = np.asarray(observed, dtype=float).ravel()
# --- input validation ---
if x.size < 2:
raise ValueError("At least 2 observations are required to estimate SD.")
if not np.all(np.isfinite(x)):
raise ValueError("`observed` must contain only finite values.")
if not (0.0 < alpha < 1.0):
raise ValueError("`alpha` must be strictly between 0 and 1.")
if not (0.0 < power < 1.0):
raise ValueError("`power` must be strictly between 0 and 1.")
if not math.isfinite(delta) or delta <= 0.0:
raise ValueError("`delta` must be a positive, finite number.")
# --- estimate standard deviation (unbiased, ddof=1) ---
sigma = float(np.std(x, ddof=1))
if sigma == 0.0:
# No variability: trivially detectable. Minimum viable experiment.
return 2
# --- z critical values ---
nd = NormalDist()
z_alpha = nd.inv_cdf(1.0 - alpha / 2.0) # two-sided threshold
z_beta = nd.inv_cdf(power) # z_{1-beta}
# --- per-group size, ceiling with float-noise tolerance ---
n_exact = 2.0 * sigma**2 * (z_alpha + z_beta)**2 / delta**2
n_per_group = max(1, math.ceil(n_exact - 1e-9))
return 2 * n_per_group
The 1e-9 subtraction before ceil guards against floating-point noise turning an exact integer like 63.0 into 63.0000000001, which would incorrectly round up to 64.
Complexity
- Time: O(m) where m =
len(observed), dominated by the standard deviation calculation. The quantile lookups and arithmetic are O(1). - Space: O(m) if
observedis a plain Python list (array conversion), O(1) extra otherwise.
Common Mistakes
- One-sided quantile for a two-sided test. Using z_{1−α} instead of z_{1−α/2} undersizes the experiment by roughly 20% at α = 0.05.
- Missing the factor of 2 in the numerator. Writing σ²(z_α + z_β)²/δ² treats the problem as a one-sample test and halves the true requirement.
- Confusing per-group n with total N. The formula gives per-group size; the question asks for the total.
- Using z_β instead of z_{1−β}. z_{0.2} is negative, which dramatically shrinks n in a meaningless way.
- Using
ddof=0. NumPy's default is the population SD, which underestimates σ on small baselines. roundinstead ofceil. Rounding down leaves the experiment underpowered.
Follow-Up Topics Worth Mentioning
- t-test vs. z-test for small n. For small baselines the t critical value is larger, so the true required n is higher than the normal approximation suggests.
- Unequal allocation. If the allocation ratio is k = n_T/n_C, the 2 in the formula becomes 1 + 1/k, allowing you to over-sample the cheaper group.
- Variance reduction (CUPED). Pre-experiment covariate adjustment can lower the effective σ substantially, reducing N without changing α or power.
- Multiple metrics / FWER. Running several tests simultaneously requires an α correction (Bonferroni or similar), which lowers each test's α and increases N.