Algorithm Search⌘K

Problemcore

Sample size determination

Also called power analysis, sample size calculation.

Find the smallest sample size for which a level-alpha test reaches a target power at a stated effect, or an interval reaches a target width. Closed form for z; numerical for t.

Sample size determination is the problem of choosing the number of observations before the data are collected. In its testing form, it asks for the smallest nn at which a level-α\alpha statistical hypothesis test has power at least 1−β1 - \beta against a stated alternative, usually given as an effect size. In its estimation form, it asks for the smallest nn at which a confidence interval is at most a given width. For the z-test the answer is the closed form n=⌈((z1−α/2+z1−β)σ/δ)2⌉n = \lceil((z_{1-\alpha/2} + z_{1-\beta})\sigma/\delta)^2\rceil, up to one observation; for the t-test it needs the noncentral t distribution and a numerical method.

In plain words

Before an experiment, you must decide how many subjects to measure. Too few, and a real effect of the size you care about will often be missed. Too many, and you waste money, time or patients. So you state four things: the smallest effect worth finding, how much single measurements scatter, how often you accept a false alarm, and how often you want to catch the effect when it is there. Then you find the smallest number of measurements that meets all four. For the simplest tests a short formula gives the answer. For the usual t-test, which estimates the scatter from the data, the answer is a little larger and needs a computer. The answer is only as good as the guessed effect and scatter.

Definition

Let {ϕn}\{\phi_n\} be a family of level-α\alpha tests, one for each sample size nn, of H0:θ∈Θ0H_0: \theta \in \Theta_0, and let πn(θ)=Pθ(ϕn rejects)\pi_n(\theta) = P_\theta(\phi_n \text{ rejects}) be the power function. Given a level α\alpha, an alternative θ1∉Θ0\theta_1 \notin \Theta_0 and a target power 1−β1 - \beta with α<1−β<1\alpha < 1 - \beta < 1, find

n∗=min⁡{n:πn(θ1)≥1−β}.n^* = \min\{n : \pi_n(\theta_1) \ge 1 - \beta\} .

For the tests of a normal mean, θ1\theta_1 enters only through the standardized effect d=δ/σd = \delta/\sigma, where δ\delta is the true difference μ−μ0\mu - \mu_0 (one sample, or paired differences) or μ1−μ2\mu_1 - \mu_2 (two groups of nn each). With the noncentrality λ=∣d∣n/g\lambda = |d|\sqrt{n/g}, where g=1g = 1 for one sample and g=2g = 2 for two groups:

  • the two-sided z-test with known σ\sigma has πn=Φ(λ−z1−α/2)+Φ(−λ−z1−α/2)\pi_n = \Phi(\lambda - z_{1-\alpha/2}) + \Phi(-\lambda - z_{1-\alpha/2});
  • the two-sided t-test has πn=P(∣Tν,λ′∣≥t(ν,1−α/2))\pi_n = P(|T'_{\nu,\lambda}| \ge t_{(\nu, 1-\alpha/2)}), where Tν,λ′=(Z+λ)/V/νT'_{\nu,\lambda} = (Z + \lambda)/\sqrt{V/\nu} with Z∼N(0,1)Z \sim N(0, 1) and V∼χν2V \sim \chi^2_\nu independent is the noncentral t variable and ν=g(n−1)\nu = g(n - 1).

The one-sided versions keep only the near tail, with z1−αz_{1-\alpha} and t(ν,1−α)t_{(\nu, 1-\alpha)}. The estimation form: find the smallest nn with half-width q σ/n≤hq\,\sigma/\sqrt n \le h (fixed width when σ\sigma is known), or, when σ\sigma is estimated, with a bound on the expected half-width or on the probability that the half-width exceeds hh.

Variants

  • Sides and level. One-sided tests replace z1−α/2z_{1-\alpha/2} by z1−αz_{1-\alpha} and need fewer observations.
  • Unequal allocation. With n1n_1 and n2=kn1n_2 = kn_1 and a common σ\sigma, Var⁡(Xˉ1−Xˉ2)=σ2(1+1/k)/n1\operatorname{Var}(\bar X_1 - \bar X_2) = \sigma^2(1 + 1/k)/n_1, so n1=(1+1/k)((z1−α/2+z1−β)σ/δ)2n_1 = (1 + 1/k)\big((z_{1-\alpha/2} + z_{1-\beta})\sigma/\delta\big)^2 for the z-test. For a fixed total n1+n2n_1 + n_2 the variance σ12/n1+σ22/n2\sigma_1^2/n_1 + \sigma_2^2/n_2 is smallest at n1/n2=σ1/σ2n_1/n_2 = \sigma_1/\sigma_2 (Cauchy-Schwarz), which is k=1k = 1 when the variances are equal.
  • Unequal variances. The two-sample size uses σ12+σ22\sigma_1^2 + \sigma_2^2 in place of 2σ22\sigma^2, and the test is then the Welch t-test.
  • Proportions. For binomial data the z-test variance is p(1−p)p(1 - p) under the null and the alternative, and an exact binomial test has a power that is not monotone in nn (Examples).
  • Precision instead of power. Choose nn so that a confidence interval has a given half-width. For the z interval this is n=⌈(z1−α/2σ/h)2⌉n = \lceil(z_{1-\alpha/2}\sigma/h)^2\rceil; for the t interval the half-width is random and the target is its expectation or a high quantile.
  • Clustered and sequential designs. Cluster sampling multiplies the variance by a design effect, and group sequential designs fix a maximum nn with interim looks; both reduce to the fixed-nn problem with an adjusted variance or level.

Examples

All values are at α=0.05\alpha = 0.05 with σ=1\sigma = 1, computed by the code of this page: the z sizes from the closed form followed by an exact power search, the t sizes by an upward search over nn with the t power computed by numerical integration (see Known algorithms). nn is the size per group.

design dd target power sides closed form, unrounded z-test nn t-test nn t power at nn and n−1n - 1
two groups 0.5 0.8 2 62.791 63 64 0.80146, 0.79517
two groups 0.2 0.8 2 392.444 393 394 0.80059, 0.79959
two groups 0.8 0.8 2 24.528 25 26 0.80749, 0.79145
two groups 0.5 0.9 2 84.059 85 86 0.90323, 0.89989
two groups 0.5 0.8 1 49.460 50 51 0.80590, 0.79894
one sample 0.5 0.8 2 31.396 32 34 0.80778, 0.79537
one sample 1.0 0.8 2 7.849 8 10 0.80310, 0.74802
one sample 0.5 0.8 1 24.730 25 27 0.81183, 0.79805

The first row is the familiar 64 per group for a "medium" effect in Cohen's terms. For it, z0.975=1.959964z_{0.975} = 1.959964, z0.8=0.841621z_{0.8} = 0.841621, and 2(2.801585/0.5)2=62.7912(2.801585/0.5)^2 = 62.791. The t-test needs 1 more per group with two groups and 2 more with one sample, because the estimated σ\sigma costs power, most at small nn: with 10 observations at d=0.5d = 0.5 the t power is 0.293 against 0.353 for the z-test, and at d=1d = 1 it is 0.803 against 0.885.

The power curve at a fixed design. With 64 per group, two-sided t-test, the power is 0.2023 at d=0.2d = 0.2, 0.3915 at d=0.3d = 0.3, 0.6124 at d=0.4d = 0.4, 0.8015 at d=0.5d = 0.5, 0.9205 at d=0.6d = 0.6 and 0.9943 at d=0.8d = 0.8. The design has 80% power only against effects of at least about 0.5σ0.5\sigma.

The far tail. The closed form ignores the probability of rejecting in the wrong direction. At d=0.05d = 0.05 with target power 0.3, the formula gives ⌈824.337⌉=825\lceil 824.337\rceil = 825, but the exact two-sided z power is 0.30024 at n=824n = 824 and 0.29994 at n=823n = 823, so n∗=824n^* = 824.

Precision. For a 95% z interval of half-width 0.5 with σ=2\sigma = 2: (1.959964×2/0.5)2=61.46(1.959964 \times 2/0.5)^2 = 61.46, so n=62n = 62.

A power that is not monotone in nn. The exact one-sided binomial test of H0:p=0.5H_0: p = 0.5 at level 0.05, rejecting for X≥kX \ge k with the smallest kk whose null tail is at most 0.05, has power at p=0.7p = 0.7 (exact sums): 0.8071 at n=37n = 37, 0.7745 at n=38n = 38, 0.7397 at n=39n = 39 and 0.8074 at n=40n = 40. The smallest nn with power at least 0.8 is 37, but n=38n = 38 and n=39n = 39 have less, because the attained size, 0.0494 at n=37n = 37 and 0.0266 at n=39n = 39, jumps with the integer critical value. For discrete tests the answer must say which of the two questions it answers.

Known algorithms

  • Closed form for the z-test. The near tail alone gives πn≥Φ(λ−z1−α/2)\pi_n \ge \Phi(\lambda - z_{1-\alpha/2}), which is at least 1−β1 - \beta once λ≥z1−α/2+z1−β\lambda \ge z_{1-\alpha/2} + z_{1-\beta}, that is n≥g((z1−α/2+z1−β)/d)2n \ge g\big((z_{1-\alpha/2} + z_{1-\beta})/d\big)^2. The ceiling of this value always reaches the target, and the far tail Φ(−λ−z1−α/2)≤α/2\Phi(-\lambda - z_{1-\alpha/2}) \le \alpha/2 can make one fewer enough. The code steps down from the formula while the exact power at n−1n - 1 still reaches the target; the exact z power increases with nn because ddλπ=φ(λ−c)−φ(λ+c)>0\frac{d}{d\lambda}\pi = \varphi(\lambda - c) - \varphi(\lambda + c) > 0 for λ,c>0\lambda, c > 0. For one-sided tests the formula is exact up to the ceiling.

  • t power by numerical integration. Conditioning on VV, with s=Vs = \sqrt V having the chi density with ν\nu degrees of freedom,

    πn=∫0∞[Φ(λ−csν)+Φ(−λ−csν)]fχν(s) ds,c=t(ν,1−α/2).\pi_n = \int_0^\infty \Big[\Phi\Big(\lambda - c\frac{s}{\sqrt\nu}\Big) + \Phi\Big(-\lambda - c\frac{s}{\sqrt\nu}\Big)\Big] f_{\chi_\nu}(s)\,ds, \qquad c = t_{(\nu, 1-\alpha/2)} .

    This is exact: given VV, the rejection event is a normal tail. The code integrates over [max⁡(0,m−12),m+12][\max(0, m - 12), m + 12] with m=max⁡(ν−1,0)m = \sqrt{\max(\nu - 1, 0)}, the mode of the chi density, whose standard deviation is below 0.8, and splits the range where the bracket falls from 1 to 0 (near s=λν/cs = \lambda\sqrt\nu/c and s=0s = 0). Each piece uses the composite Simpson rule with 800 intervals. The method's accuracy is checked, not proved: at λ=0\lambda = 0 the integral returns α\alpha within 10−810^{-8} for the tested ν\nu, and the power agrees with Monte Carlo simulation of the t-test within four standard errors (r=6000r = 6000, seeds 1 to 3, at (n,d,g)=(10,1,1),(6,1.2,2),(3,2,1)(n, d, g) = (10, 1, 1), (6, 1.2, 2), (3, 2, 1)).

  • Search for n∗n^* for the t-test. Start at the z-test answer nzn_z and step up until πn≥1−β\pi_n \ge 1 - \beta. This returns n∗n^* without assuming that the t power is monotone in nn, because every n<nzn < n_z has t power at most its z power, which is below the target (Bounds). Each step costs one integral, and the examples need at most 2 steps.

  • Simulation. For designs without a power formula (mixed models, non-normal data, complex stopping rules), estimate πn\pi_n by Monte Carlo simulation at a grid of nn and search. The error of each estimate is π(1−π)/r\sqrt{\pi(1 - \pi)/r}, so near π=0.8\pi = 0.8 with r=10000r = 10000 it is 0.004, enough to move n∗n^* by a few units when the power curve is flat.

  • Root finding. When πn\pi_n is monotone in a continuous nn, bisection on nn followed by a check of the two neighbouring integers is an alternative to the linear scan.

Bounds

  • The t-test needs at least the z-test sample size. For one-sided alternatives the z-test with known σ\sigma is uniformly most powerful among level-α\alpha tests of μ≤μ0\mu \le \mu_0, and for two-sided alternatives it is uniformly most powerful among unbiased level-α\alpha tests (Lehmann and Romano, Chapters 3 and 4, applied with σ\sigma fixed). For each fixed σ\sigma the t-test is a level-α\alpha test, and unbiased, in the model with that σ\sigma known. So its power at every nn is at most the z power, and nt∗≥nz∗n^*_t \ge n^*_z. The examples show differences of 1 to 2.
  • The closed form overshoots by at most a little. For two-sided z-tests nz∗≤⌈nf⌉n^*_z \le \lceil n_f\rceil with nf=g((z1−α/2+z1−β)/d)2n_f = g((z_{1-\alpha/2} + z_{1-\beta})/d)^2, and nz∗n^*_z is at least the size that the near tail would need with target 1−β−α/21 - \beta - \alpha/2, because the far tail adds at most α/2\alpha/2.
  • Scaling. n∗n^* grows like 1/d21/d^2: halving the effect quadruples the sample size, as the rows with d=0.2,0.5,0.8d = 0.2, 0.5, 0.8 show (393, 63, 25). Raising the power from 0.8 to 0.9 multiplies nn by (z0.975+z0.9)2/(z0.975+z0.8)2=10.507/7.849=1.34(z_{0.975} + z_{0.9})^2/(z_{0.975} + z_{0.8})^2 = 10.507/7.849 = 1.34.
  • Cost. The closed form is O(1)O(1). The t search costs O(n∗−nz∗+1)O(n^* - n^*_z + 1) integrals, each with a fixed number of normal CDF evaluations, independent of nn.

Reductions

  • Paired designs reduce to the one-sample problem on the differences, with σD\sigma_D in place of σ\sigma; a positive correlation ρ\rho within pairs gives σD2=2σ2(1−ρ)\sigma_D^2 = 2\sigma^2(1 - \rho) and a smaller nn.
  • Power of the t-test reduces to the CDF of the noncentral t distribution, which reduces to a one-dimensional integral over the chi distribution, as above.
  • Sample size for an interval reduces to inverting the half-width qσ/nq\sigma/\sqrt n, a monotone function of nn, and through test-interval duality a precision target is a power-like target for the dual test.
  • Sample size for a proportion reduces to the z-test case with σ2=p(1−p)\sigma^2 = p(1 - p) for large nn, by the central limit theorem for the binomial distribution; for small nn it needs the exact binomial test power and a scan over nn.

Applications

  • Clinical trials. Protocols state α\alpha, the power (often 0.8 or 0.9), the clinically relevant difference and the assumed variance, and justify the number of patients from them; too small a trial exposes patients without a reliable answer.
  • Online experiments. A/B tests choose the number of users per arm from the smallest lift worth detecting and the variance of the metric.
  • Surveys. The precision form sets the number of respondents for a margin of error, often with p=1/2p = 1/2 as the worst case of p(1−p)p(1 - p).
  • Replication studies. A replication is sized for the effect that matters, not for the effect observed in the original study, which tends to be inflated.

The answer depends on guesses of δ\delta and σ\sigma. Computing the power from the observed effect after a study ("observed power") adds nothing: it is a function of the p-value.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

sample_size_determination.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sample-size-determination/. The authors are listed in prov/43QS5G.jsonl.
"""Sample size for the z-test and the t-test of a mean or of two means.

The z-test sizes use the closed form and an exact power search. The t-test
power needs the noncentral t distribution, which the helper does not have, so
t_power computes it as a one-dimensional integral over the chi distribution
of the scaled standard deviation, by the composite Simpson rule.

Conventions: delta is the true difference mu - mu_0 (one sample) or
mu_1 - mu_2 (two samples), sigma the common standard deviation, alpha the
level, power the target power 1 - beta, sides 1 or 2, groups 1 (one-sample or
paired test, n observations) or 2 (two independent samples, n in each group).
For sides = 1 the test rejects in the direction of delta.
"""

import math

from stdist import norm_cdf, norm_ppf, t_ppf

_SIMPSON_INTERVALS = 800  # per piece, even; the error at lambda = 0 is below 1e-8 for nu >= 1


def _check(delta: float, sigma: float, alpha: float, sides: int, groups: int) -> None:
    if sigma <= 0.0 or delta == 0.0:
        raise ValueError("need sigma > 0 and delta != 0")
    if not 0.0 < alpha < 1.0 or sides not in (1, 2) or groups not in (1, 2):
        raise ValueError("need 0 < alpha < 1, sides in (1, 2) and groups in (1, 2)")


def _noncentrality(n: int, delta: float, sigma: float, groups: int) -> float:
    """lambda = |delta| / sigma divided by the standard error factor of the mean (difference)."""
    return abs(delta) / sigma * math.sqrt(n / groups)


def z_sample_size_formula(delta: float, sigma: float, alpha: float = 0.05,
                          power: float = 0.8, sides: int = 2, groups: int = 1) -> int:
    """ceil(groups * ((z_(1 - alpha/sides) + z_power) sigma / delta)^2).

    For sides = 2 this ignores the far rejection tail, so it can be 1 too
    large when the exact power at n - 1 already reaches the target.
    """
    _check(delta, sigma, alpha, sides, groups)
    if not 0.0 < power < 1.0:
        raise ValueError("need 0 < power < 1")
    z = norm_ppf(1.0 - alpha / sides) + norm_ppf(power)
    return max(1, math.ceil(groups * (z * sigma / delta) ** 2))


def z_power(n: int, delta: float, sigma: float, alpha: float = 0.05,
            sides: int = 2, groups: int = 1) -> float:
    """Exact power of the z-test with known sigma, both tails counted."""
    _check(delta, sigma, alpha, sides, groups)
    lam = _noncentrality(n, delta, sigma, groups)
    c = norm_ppf(1.0 - alpha / sides)
    if sides == 1:
        return norm_cdf(lam - c)
    return norm_cdf(lam - c) + norm_cdf(-lam - c)


def z_sample_size(delta: float, sigma: float, alpha: float = 0.05, power: float = 0.8,
                  sides: int = 2, groups: int = 1) -> int:
    """The smallest n with z_power(n) >= power (n per group when groups = 2).

    z_power increases with n, and the closed form n already reaches the
    target with the near tail alone, so the search steps down from it.
    """
    n = z_sample_size_formula(delta, sigma, alpha, power, sides, groups)
    while n > 1 and z_power(n - 1, delta, sigma, alpha, sides, groups) >= power:
        n -= 1
    return n


def _log_chi_density(s: float, nu: int) -> float:
    """log of the density of S = sqrt(V) for V chi-square with nu degrees of freedom."""
    return ((nu - 1) * math.log(s) - 0.5 * s * s
            - (0.5 * nu - 1.0) * math.log(2.0) - math.lgamma(0.5 * nu))


def t_power(n: int, delta: float, sigma: float, alpha: float = 0.05,
            sides: int = 2, groups: int = 1) -> float:
    """Power of the t-test at the true difference delta, by numerical integration.

    T = (Z + lambda) / (S / sqrt(nu)) with Z standard normal and S a chi
    variable with nu degrees of freedom, independent. Given S = s, the test
    rejects with probability Phi(lambda - c s / sqrt(nu)) (plus the far tail
    Phi(-lambda - c s / sqrt(nu)) for sides = 2), where c is the t critical
    value. The function integrates this against the chi density by Simpson.
    """
    _check(delta, sigma, alpha, sides, groups)
    nu = groups * (n - 1)
    if nu < 1:
        raise ValueError("need at least 1 degree of freedom")
    lam = _noncentrality(n, delta, sigma, groups)
    c = t_ppf(1.0 - alpha / sides, nu)
    root = math.sqrt(nu)

    def integrand(s: float) -> float:
        g = norm_cdf(lam - c * s / root)
        if sides == 2:
            g += norm_cdf(-lam - c * s / root)
        if s <= 0.0:
            # The chi density at 0 is sqrt(2/pi) for nu = 1 and 0 for nu >= 2.
            return g * math.sqrt(2.0 / math.pi) if nu == 1 else 0.0
        return g * math.exp(_log_chi_density(s, nu))

    mode = math.sqrt(max(nu - 1.0, 0.0))
    lo, hi = max(0.0, mode - 12.0), mode + 12.0  # the chi sd is below 0.8
    # The rejection probability falls from 1 to 0 within about 10 root / c of
    # lambda root / c (near tail) and of 0 (far tail); split the range there.
    w = 10.0 * root / c
    centre = lam * root / c
    cuts = sorted({lo, hi, *(min(max(v, lo), hi) for v in (centre - w, centre + w, w))})
    m = _SIMPSON_INTERVALS
    total = 0.0
    for a, b in zip(cuts, cuts[1:]):
        h = (b - a) / m
        part = integrand(a) + integrand(b)
        for i in range(1, m):
            part += (4.0 if i % 2 else 2.0) * integrand(a + i * h)
        total += part * h / 3.0
    return total


def t_sample_size(delta: float, sigma: float, alpha: float = 0.05, power: float = 0.8,
                  sides: int = 2, groups: int = 1) -> int:
    """The smallest n with t_power(n) >= power (n per group when groups = 2).

    At every n the t-test has at most the power of the z-test (the z-test is
    most powerful, or most powerful unbiased, when sigma is known), so no n
    below z_sample_size can work, and the search starts there.
    """
    n = max(z_sample_size(delta, sigma, alpha, power, sides, groups), 2)
    while t_power(n, delta, sigma, alpha, sides, groups) < power:
        n += 1
    return n


def z_width_sample_size(half_width: float, sigma: float, alpha: float = 0.05) -> int:
    """The smallest n for which the z interval X-bar +- z_(1 - alpha/2) sigma / sqrt(n) has half-width <= half_width."""
    if half_width <= 0.0 or sigma <= 0.0 or not 0.0 < alpha < 1.0:
        raise ValueError("need half_width > 0, sigma > 0 and 0 < alpha < 1")
    z = norm_ppf(1.0 - alpha / 2.0)
    n = max(1, math.ceil((z * sigma / half_width) ** 2))
    while n > 1 and z * sigma / math.sqrt(n - 1) <= half_width:
        n -= 1  # guard against rounding in the square
    return n
stdist.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.

The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""

import math
from statistics import NormalDist

_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000


def norm_cdf(x: float) -> float:
    """P(Z <= x) for a standard normal Z."""
    return 0.5 * math.erfc(-x / math.sqrt(2.0))


def norm_sf(x: float) -> float:
    """P(Z > x), computed with erfc, so it is accurate for large x."""
    return 0.5 * math.erfc(x / math.sqrt(2.0))


def norm_ppf(p: float) -> float:
    """The lower p-quantile z_p of the standard normal, 0 < p < 1."""
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    return _STD.inv_cdf(p)


def _gamma_tails(a: float, x: float) -> tuple[float, float]:
    """(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
    if a <= 0.0 or x < 0.0:
        raise ValueError("need a > 0 and x >= 0")
    if x == 0.0:
        return 0.0, 1.0
    if math.isinf(x):
        return 1.0, 0.0
    front = math.exp(-x + a * math.log(x) - math.lgamma(a))
    if x < a + 1.0:
        # Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
        ap, term = a, 1.0 / a
        total = term
        for _ in range(_MAXIT):
            ap += 1.0
            term *= x / ap
            total += term
            if abs(term) < abs(total) * _EPS:
                break
        p = front * total
        return p, 1.0 - p
    # Continued fraction for Q, modified Lentz.
    b = x + 1.0 - a
    c = 1.0 / _TINY
    d = 1.0 / b
    h = d
    for i in range(1, _MAXIT):
        an = -i * (i - a)
        b += 2.0
        d = an * d + b
        if abs(d) < _TINY:
            d = _TINY
        c = b + an / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    q = front * h
    return 1.0 - q, q


def gamma_p(a: float, x: float) -> float:
    """Regularized lower incomplete gamma P(a, x)."""
    return _gamma_tails(a, x)[0]


def gamma_q(a: float, x: float) -> float:
    """Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
    return _gamma_tails(a, x)[1]


def _beta_cf(a: float, b: float, x: float) -> float:
    """The continued fraction of I_x(a, b), modified Lentz."""
    qab, qap, qam = a + b, a + 1.0, a - 1.0
    c = 1.0
    d = 1.0 - qab * x / qap
    if abs(d) < _TINY:
        d = _TINY
    d = 1.0 / d
    h = d
    for m in range(1, _MAXIT):
        m2 = 2 * m
        aa = m * (b - m) * x / ((qam + m2) * (a + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        h *= d * c
        aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    return h


def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
    """(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.

    y is 1 - x; pass it when it is known more accurately than 1 - x.
    """
    if a <= 0.0 or b <= 0.0:
        raise ValueError("need a > 0 and b > 0")
    if y is None:
        y = 1.0 - x
    if x <= 0.0:
        return 0.0, 1.0
    if y <= 0.0:
        return 1.0, 0.0
    front = math.exp(
        math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
        + a * math.log(x) + b * math.log(y)
    )
    if x < (a + 1.0) / (a + b + 2.0):
        low = front * _beta_cf(a, b, x) / a
        return low, 1.0 - low
    # Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
    up = front * _beta_cf(b, a, y) / b
    return 1.0 - up, up


def beta_inc(a: float, b: float, x: float) -> float:
    """Regularized incomplete beta function I_x(a, b)."""
    return _beta_tails(a, b, x)[0]


def chi2_cdf(x: float, k: float) -> float:
    """P(X <= x) for X chi-square with k > 0 degrees of freedom."""
    return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)


def chi2_sf(x: float, k: float) -> float:
    """P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
    return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)


def t_sf(x: float, k: float) -> float:
    """P(T > x) for T Student t with k > 0 degrees of freedom."""
    if math.isfinite(x):
        s = k + x * x
        half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0]  # P(|T| > |x|) / 2
    else:
        half = 0.0
    return half if x >= 0.0 else 1.0 - half


def t_cdf(x: float, k: float) -> float:
    """P(T <= x) for T Student t with k degrees of freedom."""
    return t_sf(-x, k)


def f_cdf(x: float, k1: float, k2: float) -> float:
    """P(F <= x) for F with (k1, k2) degrees of freedom."""
    if x <= 0.0:
        return 0.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]


def f_sf(x: float, k1: float, k2: float) -> float:
    """P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
    if x <= 0.0:
        return 1.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]


def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
    """The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).

    lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
    """
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    if p <= 0.5:
        g = lambda x: cdf(x) - p  # increasing in x
    else:
        q = 1.0 - p
        g = lambda x: q - sf(x)  # increasing in x, and no cancellation in sf
    while g(hi) < 0.0:
        lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
    for _ in range(400):
        mid = 0.5 * (lo + hi)
        if mid <= lo or mid >= hi:
            break
        if g(mid) < 0.0:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def chi2_ppf(p: float, k: float) -> float:
    """The lower p-quantile chi^2_(k, p)."""
    return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))


def t_ppf(p: float, k: float) -> float:
    """The lower p-quantile t_(k, p)."""
    if p == 0.5:
        return 0.0
    if p < 0.5:
        return -t_ppf(1.0 - p, k)
    return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)


def f_ppf(p: float, k1: float, k2: float) -> float:
    """The lower p-quantile F_(k1, k2, p)."""
    return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
test_sample_size_determination.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sample-size-determination/. The authors are listed in prov/43QS5G.jsonl.

import math
import random

import pytest

from sample_size_determination import (
    t_power, t_sample_size, z_power, z_sample_size, z_sample_size_formula, z_width_sample_size,
)
from stdist import norm_ppf, t_ppf


def test_known_values() -> None:
    # Two samples, d = 0.5, alpha = 0.05 two-sided, power 0.8: 63 by z, 64 by t.
    assert z_sample_size_formula(0.5, 1.0, groups=2) == 63
    assert z_sample_size(0.5, 1.0, groups=2) == 63
    assert t_sample_size(0.5, 1.0, groups=2) == 64
    # One sample, d = 0.5: 32 by z, 34 by t.
    assert z_sample_size(0.5, 1.0) == 32
    assert t_sample_size(0.5, 1.0) == 34
    # Only delta / sigma matters.
    assert t_sample_size(5.0, 10.0, groups=2) == 64


def test_formula_matches_closed_form() -> None:
    z = norm_ppf(0.975) + norm_ppf(0.8)
    for d in [0.1, 0.25, 0.5, 1.0, 2.0]:
        assert z_sample_size_formula(d, 1.0) == math.ceil((z / d) ** 2)
        assert z_sample_size_formula(d, 1.0, groups=2) == math.ceil(2 * (z / d) ** 2)


def brute_smallest(power_fn, target: float, start: int) -> int:
    n = start
    while power_fn(n) < target:
        n += 1
    return n


@pytest.mark.parametrize("sides", [1, 2])
@pytest.mark.parametrize("groups", [1, 2])
def test_z_search_against_upward_scan(sides: int, groups: int) -> None:
    for d in [0.3, 0.45, 0.8, 1.3]:
        for target in [0.3, 0.5, 0.8, 0.95]:
            got = z_sample_size(d, 1.0, 0.05, target, sides, groups)
            want = brute_smallest(lambda n: z_power(n, d, 1.0, 0.05, sides, groups), target, 1)
            assert got == want


def test_far_tail_can_save_one_observation() -> None:
    # alpha = 0.05, power 0.3, d = 0.05: the closed form says 825, the exact power gives 824.
    assert z_sample_size_formula(0.05, 1.0, 0.05, 0.3) == 825
    assert z_sample_size(0.05, 1.0, 0.05, 0.3) == 824


@pytest.mark.parametrize("sides", [1, 2])
@pytest.mark.parametrize("groups", [1, 2])
def test_t_power_at_the_null_is_alpha(sides: int, groups: int) -> None:
    for n in [2, 3, 5, 12, 40, 200]:
        for alpha in [0.001, 0.01, 0.05, 0.2]:
            assert abs(t_power(n, 1e-12, 1.0, alpha, sides, groups) - alpha) < 1e-8


def test_t_power_is_below_z_power() -> None:
    for n in [2, 5, 10, 30]:
        for d in [0.2, 0.5, 1.0]:
            for sides in (1, 2):
                assert t_power(n, d, 1.0, 0.05, sides) <= z_power(n, d, 1.0, 0.05, sides) + 1e-9


def simulated_t_power(n: int, delta: float, groups: int, r: int, rng: random.Random) -> float:
    """Monte Carlo power of the two-sided t-test at level 0.05, sigma = 1."""
    nu = groups * (n - 1)
    c = t_ppf(0.975, nu)
    hits = 0
    for _ in range(r):
        x = [rng.gauss(delta, 1.0) for _ in range(n)]
        mx = math.fsum(x) / n
        ss = math.fsum((v - mx) ** 2 for v in x)
        if groups == 1:
            se = math.sqrt(ss / (n - 1) / n)
            diff = mx
        else:
            y = [rng.gauss(0.0, 1.0) for _ in range(n)]
            my = math.fsum(y) / n
            ss += math.fsum((v - my) ** 2 for v in y)
            se = math.sqrt(ss / nu * 2.0 / n)
            diff = mx - my
        hits += abs(diff / se) > c
    return hits / r


@pytest.mark.parametrize("n,delta,groups,seed", [(10, 1.0, 1, 1), (6, 1.2, 2, 2), (3, 2.0, 1, 3)])
def test_t_power_against_monte_carlo(n: int, delta: float, groups: int, seed: int) -> None:
    r = 6000
    exact = t_power(n, delta, 1.0, 0.05, 2, groups)
    sim = simulated_t_power(n, delta, groups, r, random.Random(seed))
    assert abs(sim - exact) < 4.0 * math.sqrt(exact * (1.0 - exact) / r)


def test_t_sample_size_is_the_smallest() -> None:
    for d, groups in [(0.8, 1), (1.0, 2), (1.5, 1)]:
        n = t_sample_size(d, 1.0, groups=groups)
        assert n == brute_smallest(lambda m: t_power(m, d, 1.0, 0.05, 2, groups), 0.8, 2)
        assert t_power(n, d, 1.0, 0.05, 2, groups) >= 0.8 > t_power(n - 1, d, 1.0, 0.05, 2, groups)


def test_width() -> None:
    # Half-width 0.5 with sigma = 2: (1.96 * 2 / 0.5)^2 = 61.46, so 62.
    assert z_width_sample_size(0.5, 2.0) == 62
    n = z_width_sample_size(0.1, 1.0, 0.01)
    z = norm_ppf(0.995)
    assert z / math.sqrt(n) <= 0.1 < z / math.sqrt(n - 1)


def test_bad_input() -> None:
    with pytest.raises(ValueError):
        z_sample_size(0.0, 1.0)
    with pytest.raises(ValueError):
        t_power(10, 0.5, -1.0)
    with pytest.raises(ValueError):
        z_sample_size(0.5, 1.0, sides=3)

References

  1. Jacob Cohen, Statistical Power Analysis for the Behavioral Sciences, second edition, Lawrence Erlbaum, 1988, Chapter 2 (the t-test for means, the effect size d, and the power and sample size tables)
  2. George Casella and Roger L. Berger, Statistical Inference, second edition, Duxbury, 2002, Section 8.3.1 (error probabilities and the power function, with the sample size choice for a normal mean)
  3. E. L. Lehmann and Joseph P. Romano, Testing Statistical Hypotheses, third edition, Springer, 2005, Chapter 3 (uniformly most powerful tests) and Chapter 4 (unbiasedness), used for the bound that the t-test needs at least the z-test sample size

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a known algorithm
  • a contract.yaml