Sample Size for A/B Tests and Bayesian Inference
Statistics & ExperimentsModel answerLast updated
Calculate per-group sample size for a two-sample z-test given power requirements, and compute a Bayesian posterior probability.
You need to build two statistical functions for an experimentation platform.
Part A: Sample Size Calculation
Given historical data for a metric, determine how many observations are needed per variant in an A/B experiment.
Inputs:
observations: array of historical metric values (independent, identically distributed)alpha: significance threshold (probability of false positive)power: target probability of detecting a real effecteffect_size: minimum meaningful difference between variants (absolute value, same units as the metric)
Requirements:
- Calculate the per-variant sample size for a two-sample z-test (two-tailed)
- Assume equal allocation between control and treatment
- Assume both variants have equal variance
- Estimate population variance from the historical data
- Return the smallest integer sample size that meets the power requirement
Part B: Posterior Probability
Given prior and conditional probabilities, calculate the posterior probability of an event.
Inputs:
prior: P(A)likelihood: P(B|A)likelihood_complement: P(B|¬A)
Return: P(A|B)
All probabilities are valid values in (0, 1).
Write clean, production-ready code with appropriate error handling.
Hints
Hint 1
For the sample size problem, start from the standard error of the difference between two means and work through what rejection threshold is needed
Hint 2
Remember that a two-tailed test splits the significance level between both tails
Hint 3
For Bayes' rule, you'll need to expand P(B) using the law of total probability
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Sample Size for A/B Tests and Bayesian Inference
This problem tests whether you understand the mechanics behind statistical formulas rather than just memorizing them, and whether you handle numerical edge cases correctly.
Part A: Sample Size for Two-Sample Z-Test
Core Logic
When comparing two groups with n observations each, the difference between sample means has variance:
$$\text{Var}(\bar{X}_1 - \bar{X}_2) = \frac{\sigma^2}{n} + \frac{\sigma^2}{n} = \frac{2\sigma^2}{n}$$
So the standard error is:
$$SE = \sigma\sqrt{\frac{2}{n}}$$
Under the null hypothesis (no true difference), we reject if the test statistic exceeds the critical value for our significance level. For a two-tailed test at level α, this critical value is the (1 - α/2) quantile of the standard normal: z₁₋α/₂.
Under the alternative hypothesis (true difference equals Δ), the test statistic has a different center. For the test to achieve power (1 - β), we need the true signal to be strong enough that the rejection region captures the alternative distribution with probability (1 - β). This translates to:
$$\frac{\Delta}{SE} = z_{1-\alpha/2} + z_{1-\beta}$$
Substituting the expression for SE and solving for n:
$$n = \frac{2\sigma^2(z_{1-\alpha/2} + z_{1-\beta})^2}{\Delta^2}$$
We estimate σ using the sample standard deviation from historical data, using the unbiased estimator (dividing by n-1), then round up to get an integer.
Critical Implementation Details
-
Two-tailed critical value: Use z₁₋α/₂, not z₁₋α. For α = 0.05, this is approximately 1.96, not 1.645.
-
Power quantile: The input
powerrepresents (1 - β), so we directly compute the inverse CDF at that value. For power = 0.8, this gives approximately 0.842. -
Factor of 2: This comes from adding the variances of two independent groups. Omitting it gives you the one-sample formula.
-
Unbiased variance: Use division by (n - 1), not n.
-
Rounding: Always round up, since rounding down would give power below the target. Account for floating-point precision by subtracting a small epsilon before ceiling.
-
Approximation note: The full power formula accounts for rejection in both tails, but the upper tail (far from the alternative) contributes negligibly and is typically ignored. Mentioning this shows depth.
Worked Example
Historical data: standard deviation s = 1
Minimum detectable effect: Δ = 0.5
Significance level: α = 0.05
Target power: 0.8
Calculations:
- z₀.₉₇₅ ≈ 1.96
- z₀.₈ ≈ 0.842
- Sum: 1.96 + 0.842 = 2.802
- Squared: 7.851
- Formula: 2 × 1² × 7.851 / 0.5² = 62.81
Result: n = 63 per group (126 total)
Edge Cases
- Insufficient data (len < 2): Cannot estimate variance; raise error
- Zero effect size: Infinite sample size required; raise error
- Zero variance: Metric is constant; return 1 (or 2 if you want to estimate variance in the experiment)
- Invalid probability parameters: Validate α and power are in (0, 1)
- Floating-point precision: Guard against ceil(63.0000001) returning 64
Complexity
Time: O(n) for computing variance from historical data
Space: O(1) beyond input
Part B: Bayesian Posterior
Core Logic
Bayes' theorem with expansion of the marginal probability:
$$P(A|B) = \frac{P(B|A) \cdot P(A)}{P(B)}$$
The denominator P(B) is computed using the law of total probability over the partition {A, ¬A}:
$$P(B) = P(B|A) \cdot P(A) + P(B|\neg A) \cdot P(\neg A)$$
Therefore:
$$P(A|B) = \frac{P(B|A) \cdot P(A)}{P(B|A) \cdot P(A) + P(B|\neg A) \cdot (1 - P(A))}$$
Intuition: The Base Rate Trap
Consider a medical test: 1% disease prevalence, 90% sensitivity, 5% false positive rate.
Many people incorrectly answer "90%" when asked for the probability of having the disease given a positive test. The correct calculation:
- Numerator: 0.90 × 0.01 = 0.009
- Denominator: 0.009 + 0.05 × 0.99 = 0.009 + 0.0495 = 0.0585
- Result: 0.009 / 0.0585 ≈ 15.4%
The low base rate (prior) dominates, even with a fairly accurate test. This illustrates why P(A|B) ≠ P(B|A).
Edge Cases
- P(B) = 0: Both conditional probabilities are zero; posterior is undefined; raise error
- Invalid probabilities: Validate all inputs are in [0, 1]
- Numerical stability: The result automatically lies in [0, 1] since the numerator is a component of the denominator
Complexity
Time: O(1)
Space: O(1)
Implementation
import math
from statistics import NormalDist
from typing import Sequence
def calculate_sample_size(
observations: Sequence[float],
alpha: float,
power: float,
effect_size: float
) -> int:
"""Calculate per-group sample size for two-sample z-test."""
if len(observations) < 2:
raise ValueError("Need at least 2 observations to estimate variance")
if not (0 < alpha < 1) or not (0 < power < 1):
raise ValueError("alpha and power must be in (0, 1)")
delta = abs(effect_size)
if delta == 0:
raise ValueError("effect_size cannot be zero")
# Compute sample variance (unbiased estimator)
n = len(observations)
mean = sum(observations) / n
variance = sum((x - mean) ** 2 for x in observations) / (n - 1)
if variance == 0:
return 1 # Constant metric: any effect is immediately detectable
# Normal distribution quantiles
dist = NormalDist()
z_alpha_half = dist.inv_cdf(1 - alpha / 2) # Two-tailed critical value
z_power = dist.inv_cdf(power) # Power quantile
# Sample size formula
numerator = 2 * variance * (z_alpha_half + z_power) ** 2
denominator = delta ** 2
n_required = numerator / denominator
# Round up, with floating-point guard
return max(1, math.ceil(n_required - 1e-9))
def compute_posterior(
prior: float,
likelihood: float,
likelihood_complement: float
) -> float:
"""Compute P(A|B) using Bayes' rule."""
if not all(0 <= p <= 1 for p in [prior, likelihood, likelihood_complement]):
raise ValueError("All probabilities must be in [0, 1]")
numerator = likelihood * prior
marginal = numerator + likelihood_complement * (1 - prior)
if marginal == 0:
raise ValueError("P(B) = 0; posterior is undefined")
return numerator / marginal
What Strong Candidates Demonstrate
- Derivation over memorization: Explaining where the factor of 2 comes from and why we add the two quantiles
- Correct quantile selection: Using 1 - α/2 for two-tailed tests
- Variance estimation: Using the unbiased estimator with n - 1
- Proper rounding: Ceiling with floating-point guards
- For Bayes: Correctly expanding P(B) and recognizing the base rate phenomenon
Common pitfalls:
- Using z₁₋α instead of z₁₋α/₂
- Computing the inverse CDF at (1 - power) instead of power
- Omitting the factor of 2
- Confusing P(A|B) with P(B|A)
- Returning total sample size instead of per-group size