Compute the sample size per group for a two-proportion A/B test

Why it matters Every product team running conversion experiments needs this number to know how long a test must run before results mean anything.

Before launching an A/B test you need to know how many users each arm needs to detect the lift you care about.

Write ab_sample_size(p1, p2, alpha=0.05, power=0.8). p1 is the baseline conversion rate and p2 the rate you want to detect. Use a two-sided test: z_a = Phi^-1(1 - alpha / 2), z_b = Phi^-1(power), with Phi^-1 from statistics.NormalDist().inv_cdf. With pbar = (p1 + p2) / 2, n = (z_a * sqrt(2 pbar (1 - pbar)) + z_b * sqrt(p1 (1 - p1) + p2 (1 - p2)))^2 / (p1 - p2)^2. Return ceil(n) as an int. Raise ValueError if p1 == p2.

Signaturedef ab_sample_size(p1, p2, alpha=0.05, power=0.8)

Example

p1 0.10, p2 0.12 gives 3841.

Understand the idea

Small lifts need many users. To detect conversion moving from 10% to 12%, random noise must be small compared with a 2 point gap, and noise only shrinks like 1 / sqrt(n).

Two settings control the answer. alpha is the false alarm rate (5% means you accept a 1 in 20 chance of calling a fake win). Power is the chance of catching a real lift of that size (80% is common). Each becomes a z-value: about 1.96 for a two-sided 5% alpha and about 0.84 for 80% power.

Worked example: p1 = 0.10, p2 = 0.12, pbar = 0.11. First term 1.96 * sqrt(2 * 0.11 * 0.89) = 1.96 * 0.4425 = 0.867. Second term 0.84 * sqrt(0.09 + 0.1056) = 0.84 * 0.4423 = 0.372. Sum 1.239, squared 1.536, divided by 0.0004 gives about 3,841 users per arm.

Rule: n = (z_a sqrt(2 pbar(1 - pbar)) + z_b sqrt(p1(1 - p1) + p2(1 - p2)))^2 / (p1 - p2)^2.

Halving the lift roughly quadruples the sample size.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampleab_sample_size(0.10, 0.12)
  • Sample 2: big liftab_sample_size(0.2, 0.3)
  • Test 3: high power strict alphaab_sample_size(0.05, 0.06, alpha=0.01, power=0.9)
  • Test 4: same rates_raises(lambda: ab_sample_size(0.1, 0.1))