Power and sample size
Before collecting data: how likely is the test to detect an effect of a given size, and how many observations does it need? For the z test and the one-proportion test the textbook answers are formulas in normal quantiles. Here the quantiles are certified, so the power is an interval certain to contain it, and a sample size is the smallest whole number proven to meet the target.
Power of the z test
Test with known and observations. Under the alternative the statistic is normal with mean and variance 1, so for
and for a two-sided test , both tails counted. power returns that number as an enclosure.
import { power, sampleSize, show } from "@ratmath/stats";
const p = power({ mu0: 100, mu: 106, sigma: 15, n: 25, alternative: "greater" });
show(p.power); // "0.638760": reject when x̄ > 104.935, and P(Z > −0.355) ≈ 0.6388
power({ test: "proportion", p0: "0.5", p: "0.6", n: 100, alternative: "greater" }).power; // ≈ 0.6415
The one-proportion version uses the normal approximation, as textbooks do: the cut-offs come from the standard error under , the spread of from the one under . For other tests, where no closed form is standard, powerCurve estimates power by simulation.
Sample size for a margin of error
A 95% interval for a proportion has half-width , so a margin of at most needs , with when nothing is known (the largest ). For a mean with known , . The bound is enclosed and rounded up only once its enclosure lies within one whole step, so the answer is never off by one.
sampleSize({ margin: "0.03" }).n; // 1068: (1.96/0.03)²·¼ = 1067.1
sampleSize({ margin: 2, sigma: 10 }).n; // 97: (1.96·10/2)² = 96.04
n is a JavaScript number while it is exact as one; above it is returned as a bigint, because a number would round it (for and margin the smallest is 3841458820694125959, which as a number would read 121 higher).
Sample size for a target power
With power given, sampleSize finds the smallest whose power is proven to reach it: the power grows with , so it doubles until the target is met and then bisects. For a one-sided z test this agrees with the formula ; for a two-sided test it also counts the far tail, which the formula ignores. With no effect () the power is for every , so a target up to is met by and a larger one is refused.
sampleSize({ power: "0.8", mu0: 100, mu: 106, sigma: 15, alternative: "greater" }).n; // 39
sampleSize({ power: "0.9", mu0: 0, mu: "0.5", sigma: 1 }).n; // 43
@ratmath/stats and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.