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.
- Evidence
- Code in 1 languages
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 at which a level- statistical hypothesis test has power at least against a stated alternative, usually given as an effect size. In its estimation form, it asks for the smallest at which a confidence interval is at most a given width. For the z-test the answer is the closed form , 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 be a family of level- tests, one for each sample size , of , and let be the power function. Given a level , an alternative and a target power with , find
For the tests of a normal mean, enters only through the standardized effect , where is the true difference (one sample, or paired differences) or (two groups of each). With the noncentrality , where for one sample and for two groups:
- the two-sided z-test with known has ;
- the two-sided t-test has , where with and independent is the noncentral t variable and .
The one-sided versions keep only the near tail, with and . The estimation form: find the smallest with half-width (fixed width when is known), or, when is estimated, with a bound on the expected half-width or on the probability that the half-width exceeds .
Variants
- Sides and level. One-sided tests replace by and need fewer observations.
- Unequal allocation. With and and a common , , so for the z-test. For a fixed total the variance is smallest at (Cauchy-Schwarz), which is when the variances are equal.
- Unequal variances. The two-sample size uses in place of , and the test is then the Welch t-test.
- Proportions. For binomial data the z-test variance is under the null and the alternative, and an exact binomial test has a power that is not monotone in (Examples).
- Precision instead of power. Choose so that a confidence interval has a given half-width. For the z interval this is ; 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 with interim looks; both reduce to the fixed- problem with an adjusted variance or level.
Examples
All values are at with , 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 with the t power computed by numerical integration (see Known algorithms). is the size per group.
| design | target power | sides | closed form, unrounded | z-test | t-test | t power at and | |
|---|---|---|---|---|---|---|---|
| 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, , , and . The t-test needs 1 more per group with two groups and 2 more with one sample, because the estimated costs power, most at small : with 10 observations at the t power is 0.293 against 0.353 for the z-test, and at 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 , 0.3915 at , 0.6124 at , 0.8015 at , 0.9205 at and 0.9943 at . The design has 80% power only against effects of at least about .
The far tail. The closed form ignores the probability of rejecting in the wrong direction. At with target power 0.3, the formula gives , but the exact two-sided z power is 0.30024 at and 0.29994 at , so .
Precision. For a 95% z interval of half-width 0.5 with : , so .
A power that is not monotone in . The exact one-sided binomial test of at level 0.05, rejecting for with the smallest whose null tail is at most 0.05, has power at (exact sums): 0.8071 at , 0.7745 at , 0.7397 at and 0.8074 at . The smallest with power at least 0.8 is 37, but and have less, because the attained size, 0.0494 at and 0.0266 at , 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 , which is at least once , that is . The ceiling of this value always reaches the target, and the far tail can make one fewer enough. The code steps down from the formula while the exact power at still reaches the target; the exact z power increases with because for . For one-sided tests the formula is exact up to the ceiling.
-
t power by numerical integration. Conditioning on , with having the chi density with degrees of freedom,
This is exact: given , the rejection event is a normal tail. The code integrates over with , 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 and ). Each piece uses the composite Simpson rule with 800 intervals. The method's accuracy is checked, not proved: at the integral returns within for the tested , and the power agrees with Monte Carlo simulation of the t-test within four standard errors (, seeds 1 to 3, at ).
-
Search for for the t-test. Start at the z-test answer and step up until . This returns without assuming that the t power is monotone in , because every 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 by Monte Carlo simulation at a grid of and search. The error of each estimate is , so near with it is 0.004, enough to move by a few units when the power curve is flat.
-
Root finding. When is monotone in a continuous , bisection on 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 is uniformly most powerful among level- tests of , and for two-sided alternatives it is uniformly most powerful among unbiased level- tests (Lehmann and Romano, Chapters 3 and 4, applied with fixed). For each fixed the t-test is a level- test, and unbiased, in the model with that known. So its power at every is at most the z power, and . The examples show differences of 1 to 2.
- The closed form overshoots by at most a little. For two-sided z-tests with , and is at least the size that the near tail would need with target , because the far tail adds at most .
- Scaling. grows like : halving the effect quadruples the sample size, as the rows with show (393, 63, 25). Raising the power from 0.8 to 0.9 multiplies by .
- Cost. The closed form is . The t search costs integrals, each with a fixed number of normal CDF evaluations, independent of .
Reductions
- Paired designs reduce to the one-sample problem on the differences, with in place of ; a positive correlation within pairs gives and a smaller .
- 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 , a monotone function of , 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 for large , by the central limit theorem for the binomial distribution; for small it needs the exact binomial test power and a scan over .
Applications
- Clinical trials. Protocols state , 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 as the worst case of .
- 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 and . 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.
# 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
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 43QS5G Edit this page History Report an error Markdown