Sample Size Calculator for Two-Proportion Z-Test
Arrays & HashingAuto-graded · 13 test casesLast updated
Tests ability to implement statistical power calculations for comparing two binary outcome rates in experimental design.
Sample Size Calculator for Two-Proportion Z-Test
You are designing an experiment comparing two groups where each observation has a binary outcome (success or failure). Your task is to determine how many participants are needed in each group to reliably detect a specific difference in success rates.
Write a function that calculates the minimum sample size per group required to detect a given lift with specified statistical power and significance level.
Inputs
Your function receives four parameters:
p_control: The baseline success probability in the control group (a float strictly between 0 and 1)lift: The absolute increase in success probability you want to detect (a positive float)power: The desired statistical power, i.e., probability of detecting the effect if it exists (a float strictly between 0 and 1)alpha: The significance level for a two-sided test (a float strictly between 0 and 1)
Task
Calculate the minimum number of observations needed per group using the two-proportion z-test formula with pooled variance under the null hypothesis:
n = [z_{1-α/2} × √(2 × p̄ × (1 - p̄)) + z_{1-β} × √(p₁ × (1 - p₁) + p₂ × (1 - p₂))]² / δ²
Where:
- p₁ =
p_control(control group rate) - p₂ =
p_control+lift(treatment group rate) - δ =
lift(absolute difference) - p̄ = (p₁ + p₂) / 2 (pooled rate under null hypothesis)
- z_{1-α/2} is the two-sided critical value from the standard normal distribution at significance level α
- z_{1-β} is the quantile of the standard normal distribution at probability equal to
power
Output
Return a single integer: the sample size per group, rounded up to the nearest whole number.
Validation Rules
If the input parameters are invalid, raise a ValueError with the exact message:
- If either p₁ or p₂ is not strictly between 0 and 1: raise
ValueError('Both event rates must be strictly between 0 and 1') - If either
poweroralphais not strictly between 0 and 1: raiseValueError('power and alpha must be between 0 and 1')
Implementation Notes
You must implement the standard normal distribution's quantile function (inverse CDF) yourself. Do not use external libraries like scipy or numpy. You may use only:
- The
mathmodule'serf,sqrt, andceilfunctions - The standard normal CDF formula: Φ(x) = 0.5 × (1 + erf(x / √2))
- Binary search to compute the inverse CDF (quantile function)
Constraints
- 0 <
p_control< 1 - 0 <
p_control+lift< 1 - 0 <
power< 1 - 0 <
alpha< 1 - All inputs are floats
- You may only import from the
mathmodule
Examples
Example 1
Input: sample_size_per_group(0.2, 0.03, 0.9, 0.05)
Output: 3939
Hints
Hint 1
Calculate the treatment success rate by adding the lift to the control rate, then find the pooled rate by averaging them.
Hint 2
Implement the standard normal quantile function using binary search over the range [-10, 10] with the forward CDF computed via the error function.
Hint 3
The forward CDF of the standard normal is: Φ(x) = 0.5 × (1 + erf(x / √2)) where erf is the error function from the math module.
Hint 4
Compute z_{1-α/2} by finding the quantile at (1 - alpha/2) and z_{1-β} by finding the quantile at power, then plug both into the formula and round up.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Sample Size Calculator for Two-Proportion Z-Test
Approach
This problem requires computing the per-group sample size needed to detect a specified difference between two proportions with given statistical power and significance level. The solution implements the classical power analysis formula for a two-proportion z-test.
The algorithm proceeds as follows:
-
Validate all inputs: Check that the control rate and the resulting treatment rate (control + lift) both lie strictly between 0 and 1. Also verify that power and alpha are valid probabilities.
-
Compute the treatment success rate: This is simply the control rate plus the lift.
-
Calculate the pooled rate: Under the null hypothesis of no difference, we assume both groups have the same rate. This pooled rate is the average of the control and treatment rates: p̄ = (p₁ + p₂) / 2.
-
Obtain critical values from the standard normal distribution:
- For a two-sided test with significance level α, we need the quantile at 1 - α/2
- For the desired power (1 - β), we need the quantile at the power level itself
- Since scipy and numpy are not allowed, we implement the quantile function using binary search on the CDF
-
Apply the power formula: The numerator combines two variance components:
- Under H₀: 2 × p̄ × (1 - p̄) represents the pooled variance
- Under H₁: p₁(1-p₁) + p₂(1-p₂) represents the actual variance when the effect exists
- Each variance term is weighted by its corresponding z-score, summed, and then squared
-
Normalize by effect size: Divide the numerator by δ² (lift squared) to get the required sample size.
-
Round up: Since we need an integer number of observations and must guarantee the desired power, we always round up.
Why This Works
The formula derives from the requirement that under the alternative hypothesis (when the true difference equals the lift), the test statistic must exceed the critical threshold with probability equal to the desired power. The pooled variance term reflects variability under the null, while the separate variance term reflects variability under the alternative. The formula balances Type I error (controlled by α) and Type II error (controlled by power) to determine the necessary sample size.
Complexity
- Time: O(1) — The computation involves a constant number of arithmetic operations. The quantile function uses binary search with exactly 100 iterations, making it effectively constant time.
- Space: O(1) — Only a fixed number of scalar variables are stored.
Implementation
from math import ceil, erf, sqrt
def _normal_cdf(x):
return 0.5 * (1.0 + erf(x / sqrt(2.0)))
def _normal_ppf(p):
lo, hi = -10.0, 10.0
for _ in range(100):
mid = (lo + hi) / 2.0
if _normal_cdf(mid) < p:
lo = mid
else:
hi = mid
return (lo + hi) / 2.0
def sample_size_per_group(p_control, lift, power, alpha):
p_treatment = p_control + lift
if not (0 < p_control < 1 and 0 < p_treatment < 1):
raise ValueError('Both event rates must be strictly between 0 and 1')
if not (0 < power < 1 and 0 < alpha < 1):
raise ValueError('power and alpha must be between 0 and 1')
p_bar = (p_control + p_treatment) / 2.0
z_alpha = _normal_ppf(1.0 - alpha / 2.0)
z_power = _normal_ppf(power)
numerator = (z_alpha * sqrt(2.0 * p_bar * (1.0 - p_bar)) + z_power * sqrt(p_control * (1.0 - p_control) + p_treatment * (1.0 - p_treatment))) ** 2
return ceil(numerator / (lift * lift))