Module contents
Lesson 12 of 27Core 90 min

Power, effect size and sample size

Calculate power and sample size, compare effect-size scales, simulate power for complex designs, and understand selection exaggeration and post hoc power.

After this lesson you can

  • Calculate and interpret power as a function of effect and standard error.
  • Plan sample size and minimum detectable effect using normal and noncentral-t methods.
  • Estimate power by simulation for a specified design and analysis.
  • Quantify type S and M errors and explain why observed post hoc power adds no information.

Before you start

Motivation: an experiment that could not go well

A team tests an intervention with two groups of 40 people. It suspects a modest true effect, one quarter of a standard deviation (d=0.25d = 0.25), and analyzes it using the usual tt test. Before collecting any data we can predict the outcome: the study will detect the effect one time in five. When it does, the estimate will be inflated. The next cell repeats the experiment twenty thousand times to check.

[ ]Twenty thousand replicates of a study with 20 % powerBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(12)
n, d, R = 40, 0.25, 20000               # por grupo; efecto real 0.25 sigma; réplicas
x = rng.normal(0, 1, (R, n))
y = rng.normal(d, 1, (R, n))
dif = y.mean(1) - x.mean(1)
sp = np.sqrt((x.var(1, ddof=1) + y.var(1, ddof=1)) / 2)
t = dif / (sp * np.sqrt(2 / n))
p = 2 * stats.t.sf(np.abs(t), 2 * n - 2)
sig = p < 0.05

print(f"efecto real                              : {d:.3f}")
print(f"media de TODAS las estimaciones          : {dif.mean():.3f}   (insesgada)")
print(f"fracción significativa (potencia)        : {sig.mean():.3f}")
print(f"media de las estimaciones significativas : {dif[sig].mean():.3f}   (x{dif[sig].mean() / d:.2f} el efecto real)")
print(f"significativas con el signo equivocado   : {(dif[sig] < 0).mean():.3%}")

The estimate is unbiased, yet the mean among studies that “work” is more than twice the true effect. There is no calculation error: the significance filter selects samples in which noise pushed upward. This lesson studies that phenomenon and the tool that prevents it: planning. It answers five questions every experimenter (and reader of experiments) needs to handle:

  1. What is the chance of detecting a given effect size? The power function.
  2. What units measure “how much” effect? Absolute and standardized effect sizes, and why standardization can mislead.
  3. How much data do I need? Closed-form formulas for zz, tt and proportion tests, minimum detectable effect, and the noncentral tt for exact calculation.
  4. What if the test or design has no formula? Simulation-based power, applicable to any procedure.
  5. What happens without planning? Type S and M errors, the winner’s curse, and the fallacy of calculating power after an experiment.

We use the vocabulary of hypothesis tests, type I and II errors and p-values from the prior lesson, as well as standard errors and confidence intervals.

The power function

Design a test by fixing false-positive probability, level α\alpha. Then we ask it to detect effects when they exist. This property depends on how much effect there is, so it is a function rather than a single number.

A frequent mistake is to discuss “a study’s power” as a single number. It is always power against a specific effect: one study has 5 % power against zero effect (level α\alpha) and 99 % against a huge one.

The normal case in full

Start with the simplest model, containing the whole structure. The effect estimator is D^∼N(δ,SE2)\hat D \sim \Normal(\delta, \mathrm{SE}^2) with known SE\mathrm{SE} (difference of means with known σ\sigma, or one mean), and H0:δ=0H_0: \delta = 0 is tested using ∣D^/SE∣>z1−α/2\abs{\hat D/\mathrm{SE}} > z_{1-\alpha/2}, where zpz_{p} is the pp quantile of the standard normal and Φ\Phi its distribution function.

Z=D^SE∼N(λ,1),λ=δSEZ = \frac{\hat D}{\mathrm{SE}} \sim \Normal(\lambda, 1), \qquad \lambda = \frac{\delta}{\mathrm{SE}}
Standardize by standard error, not effect: under true effect δ\delta, the statistic is centered at λ\lambda, not 0.
1/5

The number λ=δ/SE\lambda = \delta/\mathrm{SE} is the noncentrality parameter: effect measured in standard errors. Everything about zz-test power passes through it.

Proof

Let φ=Φ′\varphi = \Phi' be the standard normal density. (1) is immediate: SE=σ/n\mathrm{SE} = \sigma/\sqrt n for a mean. For (2), evenness follows from the formula. For λ>0\lambda > 0,

 ⁣dπ ⁣dλ=φ(λ−z)−φ(λ+z)>0,\frac{\dd \pi}{\dd \lambda} = \varphi(\lambda - z) - \varphi(\lambda + z) > 0,

because φ\varphi decreases in ∣u∣\abs{u} and ∣λ−z∣<λ+z\abs{\lambda - z} < \lambda + z when λ,z>0\lambda, z > 0. (3) follows from (2): with δ≠0\delta \neq 0, ∣λ∣\abs\lambda increases in nn and decreases in σ\sigma; since ∂π/∂z=−φ(λ−z)−φ(λ+z)<0\partial \pi/\partial z = -\varphi(\lambda - z) - \varphi(\lambda + z) < 0 and zz decreases in α\alpha, π\pi increases in α\alpha. Limits follow from Φ(±∞)\Phi(\pm\infty). For (4), π=Φ(0)+Φ(−2z)\pi = \Phi(0) + \Phi(-2z), with Φ(−2z)≈4.4×10−5\Phi(-2z) \approx 4.4 \times 10^{-5} if α=0.05\alpha = 0.05.

∎

Property (4) is a golden rule: when the true effect equals 1.961.96 standard errors, the study has 50 % power. For 80 % it needs 2.802.80 standard errors, and for 90 %, 3.243.24. Remember this; it will recur.

InteractiveThe power curve
Observed difference D^\hat D under H0H_0 and H1H_1 (reject if ∣D^∣>8.90|\hat D| > 8.90)
0δ
  • H₀: no effect
  • H₁: effect δ
  • α: false positive
  • power 1 − β
  • β: false negative
Power function π(δ)\pi(\delta) of this test (click to choose δ\delta)
80 %α = 0.05
  • n per group
  • 4n per group
  • 80% target
  • selected δ
40
5.0
20
Level α\alpha
Power (exact t)19.7 %
Power (normal approximation)20.1 %
Standard error SE=σ2/n\mathrm{SE} = \sigma\sqrt{2/n}4.47
Noncentrality λ=δ/SE\lambda = \delta/\mathrm{SE}1.12
Cohen's d=δ/σd = \delta/\sigma0.25
MDE at 80% (this nn)12.69
MDE at 80% with 4n4n6.28
Power 20 %: the study misses the true effect 80 % of the time. To reach 80% at this δ\delta would require 253 per group.
A two-sample tt test with nn per group. Left: observed difference D^\hat D has a bell under H0H_0 (grey) and another under H1H_1 (blue); dashed lines are rejection thresholds. (For areas to give exact tt-test power, SE⋅T\mathrm{SE}\cdot T is plotted, the tt statistic in original units, i.e. D^\hat D with estimated σ\sigma.) Red is false positive, filled blue power, amber false negative. Right: the full power function. Increase nn from 5 to 2000: bells narrow and rejection region approaches 0. Keep δ\delta fixed and go from nn to 4n4n: minimum detectable effect halves. Halve σ\sigma at fixed nn: what happens to the curve? Try α=0.01\alpha = 0.01 and α=0.1\alpha = 0.1 to see gains and costs.

The figure has three levers, all acting through λ\lambda:

  • More data. SE∝1/n\mathrm{SE} \propto 1/\sqrt n. Halving standard error requires quadrupling nn. Each extra decimal of precision costs its square.
  • Less noise. Reducing σ\sigma (better measurement, covariate adjustment, paired or blocked designs covered in experimental design) does the same as increasing nn: halving σ\sigma equals quadrupling sample size, often more cheaply.
  • Higher level. Increasing α\alpha moves the threshold and gains power, at the cost of false positives. It is not free: it is the familiar balance between errors.

Effect sizes

Power depends on “how much effect”. This needs a scale, and choosing it is a scientific rather than statistical decision.

The most used is Cohen’s dd: mean difference in standard-deviation units. Its estimate replaces σ\sigma with pooled standard deviation, d^=(yˉ−xˉ)/sp\hat d = (\bar y - \bar x)/s_p. It is upward biased in small samples, corrected by Hedges’ gg, g=Jd^g = J\hat d with J≈1−3/(4ν−1)J \approx 1 - 3/(4\nu - 1) and ν=n1+n2−2\nu = n_1 + n_2 - 2 (for 20 per group, J=0.98J = 0.98: small but nonzero). Like every estimate, it needs uncertainty: for group sizes n1,n2n_1, n_2,

SE(d^)≈n1+n2n1n2+d^22(n1+n2).\mathrm{SE}(\hat d) \approx \sqrt{\frac{n_1 + n_2}{n_1 n_2} + \frac{\hat d^2}{2(n_1 + n_2)}}.

With 40 per group and d^=0.5\hat d = 0.5, standard error is 0.230.23 and the 95 % interval for dd ranges from about 0.060.06 to 0.940.94: a “medium” effect with an interval spanning trivial to large. An effect size without an interval is an estimate without its uncertainty.

For binary outcomes, with x1x_1 events among n1n_1 controls and x2x_2 among n2n_2 treated, risk difference has Wald standard error p^1q^1/n1+p^2q^2/n2\sqrt{\hat p_1\hat q_1/n_1 + \hat p_2\hat q_2/n_2}, and relative effects use a logarithmic scale where the delta method gives

SE(log⁡OR^)≈1x1+1n1−x1+1x2+1n2−x2,SE(log⁡RR^)≈1x1−1n1+1x2−1n2,\mathrm{SE}(\log \widehat{\mathrm{OR}}) \approx \sqrt{\tfrac{1}{x_1} + \tfrac{1}{n_1 - x_1} + \tfrac{1}{x_2} + \tfrac{1}{n_2 - x_2}}, \qquad \mathrm{SE}(\log \widehat{\mathrm{RR}}) \approx \sqrt{\tfrac{1}{x_1} - \tfrac{1}{n_1} + \tfrac{1}{x_2} - \tfrac{1}{n_2}},

and the interval is obtained by exponentiating endpoints (hence asymmetric). With 40 of 400 versus 60 of 400: 5-point difference with 95 % interval [0.4, 9.6][0.4,\ 9.6], RR=1.50\mathrm{RR} = 1.50 with [1.03, 2.18][1.03,\ 2.18] and OR=1.59\mathrm{OR} = 1.59 with [1.04, 2.43][1.04,\ 2.43]. All three describe the same data; none alone suffices.

InteractiveOne effect on different scales
Two groups of 100 people: how many experience the event
Control: 5.0 in 100Treatment: 7.3 in 100
  • control
  • treatment
Treatment risk versus baseline risk with fixed OR =1.50= 1.50
2.3 ppmaximum gap 10 pp
  • treatment risk
  • no effect (OR = 1)
  • risk difference
Outcome type
5 %
1.50
Risk difference2.32 pp
Relative risk1.46
Odds ratio1.50
NNT (1 / risk difference)43
Cohen's hh (arcsine)0.097
With p0=5 %p_0 = 5\,\% and OR =1.50= 1.50, risk changes from 5.0 % to 7.3 %: RR =1.46= 1.46, which resembles OR only for rare events.
Two modes. For binary, choose baseline p0p_0 and odds ratio: risk difference and relative risk change with p0p_0 even when OR does not. For continuous, fix mean difference δ\delta in points and change dispersion σ\sigma: Cohen's dd moves from 'small' to 'large' with the same real improvement. In each case ask which number you would tell the decision-maker.

When standardization misleads

Standardization has a benefit and a cost. Benefit: comparing and combining studies measuring the same thing with different instruments (the basis of meta-analysis), and direct entry into power tables because λ=dn/2\lambda = d\sqrt{n/2} depends only on dd. Cost: d=δ/σd = \delta/\sigma mixes effect and population variability, the latter a property of context, not treatment.

  • Same effect, different dd. An intervention adding 5 points to a test has d=0.5d = 0.5 in a population with σ=10\sigma = 10 and d=0.25d = 0.25 in another with σ=20\sigma = 20. The effect on each person is identical.
  • Measurement reliability changes σ\sigma. A noisy instrument increases σ\sigma and shrinks dd without changing the phenomenon. Restricting the population (only university students, only one age range) reduces σ\sigma and raises dd.
  • Cohen’s labels are conventions. “Small, medium, large” (0.20.2, 0.50.5, 0.80.8) were Cohen’s suggestion when nothing else was known, not a relevance scale. A d=0.1d = 0.1 marker predicting mortality from a common disease may represent thousands of lives; d=1d = 1 on an irrelevant test, none.
  • Odds ratios are not relative risks. OR≈RR\mathrm{OR} \approx \mathrm{RR} only for rare events. With 40 % baseline and OR=2\mathrm{OR} = 2, risk rises to 57 %, relative risk 1.431.43. The same OR gives a risk difference of about 2 points at 2 % baseline and 17 points at 40 %, as shown.

Sample size

Given level α\alpha, desired power 1−β1 - \beta, and an effect worth detecting, sample size is the smallest nn achieving it.

Proof

Standard error of D^=yˉ−xˉ\hat D = \bar y - \bar x is SE=σ2/n\mathrm{SE} = \sigma\sqrt{2/n}, so λ=δ∗n/2/σ\lambda = \delta^\ast\sqrt{n/2}/\sigma. Power is Φ(λ−z1−α/2)+Φ(−λ−z1−α/2)\Phi(\lambda - z_{1-\alpha/2}) + \Phi(-\lambda - z_{1-\alpha/2}), with second term a negligible tail (less than 10−610^{-6} if α=0.05\alpha = 0.05 and power is 0.80.8). Setting Φ(λ−z1−α/2)=1−β\Phi(\lambda - z_{1-\alpha/2}) = 1 - \beta is equivalent to λ−z1−α/2=z1−β\lambda - z_{1-\alpha/2} = z_{1-\beta}, i.e. λ=z1−α/2+z1−β\lambda = z_{1-\alpha/2} + z_{1-\beta}. Solve for nn to obtain the formula.

∎

With α=0.05\alpha = 0.05 and power 0.80.8, z0.975+z0.8=1.960+0.842=2.802z_{0.975} + z_{0.8} = 1.960 + 0.842 = 2.802, and 2×2.8022≈15.72 \times 2.802^2 \approx 15.7. This gives the rule of thumb:

n≈16d2 por grupo.n \approx \frac{16}{d^2} \text{ por grupo}.

For d=0.2d = 0.2 this is 392.4392.4, i.e. 393 per group using the normal approximation; for d=0.5d = 0.5, 62.862.8; for d=1d = 1, 15.715.7. A “small” effect requires 25 times more data than a “large” one (0.2(0.2 versus 1)1), because n∝1/d2n \propto 1/d^2.

Variants

DesignSample sizeNotes
One sample or paired datan=σ2(z1−α/2+z1−β)2/δ∗2n = \sigma^2 (z_{1-\alpha/2} + z_{1-\beta})^2/\delta^{\ast 2}σ\sigma is the paired-difference standard deviation
Two samples, nn per groupn=2σ2(z1−α/2+z1−β)2/δ∗2n = 2\sigma^2 (z_{1-\alpha/2} + z_{1-\beta})^2/\delta^{\ast 2}previous theorem
One-sided testreplace z1−α/2z_{1-\alpha/2} with z1−αz_{1-\alpha}saves some sample if direction is prespecified
Unequal allocation, n1=k n2n_1 = k\,n_2n2=(1+1/k) σ2(z1−α/2+z1−β)2/δ∗2n_2 = (1 + 1/k)\,\sigma^2 (z_{1-\alpha/2} + z_{1-\beta})^2/\delta^{\ast 2}minimum total occurs at k=1k = 1
Two proportions p1,p2p_1, p_2n=(z1−α/22pˉqˉ+z1−βp1q1+p2q2)2(p1−p2)2n = \dfrac{\big(z_{1-\alpha/2}\sqrt{2\bar p\bar q} + z_{1-\beta}\sqrt{p_1 q_1 + p_2 q_2}\big)^2}{(p_1 - p_2)^2}pˉ=(p1+p2)/2\bar p = (p_1 + p_2)/2, q=1−pq = 1 - p

The proportion formula uses variance under H0H_0 (where both proportions equal pˉ\bar p) to set the threshold and variance under H1H_1 to evaluate power: the two-bell idea from the previous figure.

Minimum detectable effect

Read the formula backward. With nn fixed by budget, what effect can be detected? Solving for δ\delta gives the minimum detectable effect (MDE):

MDE=(z1−α/2+z1−β) SE≈2.8 SE.\mathrm{MDE} = (z_{1-\alpha/2} + z_{1-\beta})\,\mathrm{SE} \approx 2.8\,\mathrm{SE}.

This is the effect against which the study has the requested power; smaller effects are invisible to the study. Before collecting data, calculate MDE and compare with the relevant effect to ask the right question: “can this experiment see what matters to me?” If MDE exceeds any plausible effect, the design is not worth running. An example outside the lab: with independent returns, an annual Sharpe ratio estimated from TT years of data has standard error about 1/T1/\sqrt T, so distinguishing a Sharpe of 0.50.5 from zero at 80 % power requires T≈(2.8/0.5)2≈31T \approx (2.8/0.5)^2 \approx 31 years. This power calculation explains why in quantitative finance almost no strategy can be “proven” from its own history.

InteractiveThe cost of detecting small effects
Traffic days to detect the effect (p0=5 %p_0 = 5\,\%, α=0.05\alpha = 0.05, power 80%)
  • days required
  • with half the effect
  • 1 week, 1 month, 1 year
Each time the effect is halved, duration is multiplied by almost 4
this effect: 10.0 % relative6.2 dayshalf: 5.0 % relative24 daysone quarter: 2.5 % relative97 days
  • selected effect
  • half (≈ ×4)
  • one quarter (≈ ×16)
10.0 %
Baseline conversion p0p_0
10 000
Power
Absolute effect (percentage points)0.50 pp
Users per arm31 233
Total users62 467
Test duration6.2 days
With half the effect24 days
At 6.2 days the test is fast. Drag the effect to the left: each halving costs four times as much.
An A/B test with baseline conversion p0p_0 and daily total traffic. The curve gives days needed to detect a given relative improvement (80 % power, α=0.05\alpha = 0.05). Drag along the curve or use the slider toward smaller improvements. Right bars compare chosen effect, half, and one quarter. With p0=5 %p_0 = 5\,\% and 10 000 daily visitors, what does detecting a 10 % improvement cost? A 2 % improvement? What traffic makes 1 % improvements worth pursuing?

The figure is n∝1/δ2n \propto 1/\delta^2 in business units. With 5 % baseline, detecting 10 % relative improvement (half a percentage point) needs about 31 000 users per arm; half that effect about 122 000; 2 % about 753 000. At 10 000 daily visitors, these are 6 days, 24 days, and nearly five months. Practical consequence: some effects cannot be detected with available traffic, and it is honest to know beforehand rather than discover it during analysis.

Before trusting the number

The formula gives an exact number with highly uncertain inputs. Four precautions:

  • The reference effect is not the pilot’s. A small pilot with significant result inherits the winner’s curse below: its effect is inflated, and sizing from it guarantees an underpowered study. Use the smallest effect worth detecting or a conservative estimate from literature.
  • Variance is also estimated. A pilot σ\sigma with ν\nu degrees of freedom has uncertainty. Since νs2/σ2∼χν2\nu s^2/\sigma^2 \sim \chi^2_\nu, a 1−γ1 - \gamma upper confidence bound for σ\sigma is sν/χν;γ2s\sqrt{\nu/\chi^2_{\nu;\gamma}}, with χν;γ2\chi^2_{\nu;\gamma} the γ\gamma quantile. For a pilot of 10 per group (ν=18\nu = 18), the 80 % bound is 18 % above ss, increasing study cost by 40 % (the square). Underestimating variance is the most common route to insufficient power.
  • Participants drop out and are not independent. If fraction ff is expected to be lost, divide by 1−f1 - f. With clustering (classes, hospitals, users with multiple sessions), multiply by design effect 1+(m−1)ρ1 + (m - 1)\rho from sampling design.
  • One comparison is not the whole study. If mm hypotheses are tested, per-test level falls (α/m\alpha/m with Bonferroni) and sample size grows; see multiple comparisons.

A good habit: instead of one number, make a sensitivity table of required sizes for plausible effects and σ\sigma values.

The noncentral t and exact calculation

The normal formula assumes known σ\sigma. In practice the tt test is used, and under the alternative its statistic follows a distribution other than Student’s tt, allowing exact power calculation.

Proof

Divide numerator and denominator by σ2/n\sigma\sqrt{2/n}. The numerator (yˉ−xˉ)/(σ2/n)(\bar y - \bar x)/(\sigma\sqrt{2/n}) is normal with mean λ\lambda and variance 1. The denominator is sp2/σ2\sqrt{s_p^2/\sigma^2}, and νsp2/σ2=[(n−1)sx2+(n−1)sy2]/σ2∼χ2n−22\nu s_p^2/\sigma^2 = \big[(n-1)s_x^2 + (n-1)s_y^2\big]/\sigma^2 \sim \chi^2_{2n-2} as a sum of two independent χn−12\chi^2_{n-1}. Sample means are independent of sample variances (normal sampling theory), so numerator and denominator are independent and TT has exactly the definition’s form. Rejection is ∣T∣>c\abs{T} > c, with the formula’s probability.

∎

The normal formula differs slightly but consistently: estimating σ\sigma costs power, and the normal approximation underestimates required sample size. The next cell implements zz power, exact power via scipy.stats.nct, and search for the smallest integer nn.

[ ]Power and sample size: normal versus noncentral tBrowser
import numpy as np
from scipy import stats
from scipy.stats import norm, nct, t as tdist

def potencia_z(lam, alpha=0.05):
    """Potencia del test z bilateral con no centralidad lam."""
    z = norm.ppf(1 - alpha / 2)
    return norm.cdf(lam - z) + norm.cdf(-lam - z)

def n_z(d, alpha=0.05, potencia=0.8):
    """n por grupo (dos muestras), aproximación normal."""
    return 2 * ((norm.ppf(1 - alpha / 2) + norm.ppf(potencia)) / d) ** 2

def potencia_t(d, n, alpha=0.05):
    """Potencia exacta del t de dos muestras con n por grupo, vía t no central."""
    nu, lam = 2 * n - 2, d * np.sqrt(n / 2)
    c = tdist.ppf(1 - alpha / 2, nu)
    return nct.sf(c, nu, lam) + nct.cdf(-c, nu, lam)

def n_t(d, alpha=0.05, potencia=0.8):
    """Menor n entero con potencia exacta >= la pedida."""
    n = max(2, int(n_z(d, alpha, potencia)) - 2)
    while potencia_t(d, n, alpha) < potencia:
        n += 1
    return n

print(" d      n normal (redondeo)   n exacto (t)   potencia t con n normal")
for d in (0.2, 0.5, 0.8, 1.0, 1.5):
    nz = int(np.ceil(n_z(d)))
    print(f"{d:4.1f}   {n_z(d):8.2f} ({nz:4d})      {n_t(d):6d}         {potencia_t(d, nz):.4f}")

z = norm.ppf(0.975)
print("\ncorrección n_t ~ n_z + z^2/4:", [round(n_z(d) + z**2 / 4, 2) for d in (0.2, 0.5, 1.0)])

The pattern: a study sized for 80 % by the normal approximation actually has 73 %–80 % power: nearly no difference for small dd, considerably worse at small nn (with d=1.5d = 1.5, normal says 7 per group and exact 9). A useful approximation is add z1−α/22/4≈1z_{1-\alpha/2}^2/4 \approx 1 to per-group nn from the normal formula, matching exact values in the table (for d=0.5d = 0.5: 62.8+0.96=63.7562.8 + 0.96 = 63.75 versus 63.7763.77 exact before rounding).

Power by simulation

Formulas exist for a few tests on normal data. Once the test is permutation, rank-based, robust-error regression, mixed-model or sequential, or data have heavy tails, clustering or attrition, there is no formula. But one recipe always works.

This is a simulation study with one quantity of interest. Since rejection fraction is a mean of RR Bernoulli variables, its Monte Carlo error is π(1−π)/R\sqrt{\pi(1 - \pi)/R}, and knowing π\pi within ±0.01\pm0.01 (95 %) near 0.80.8 requires R≈1.962⋅0.16/0.012≈6000R \approx 1.96^2\cdot 0.16/0.01^2 \approx 6000. The full recipe:

  1. Write generator GG under the reference effect, including suspected design features: heavy tails, within-group correlation, losses, imbalance.
  2. Write analysis T\mathcal{T} exactly as performed on real data, including preprocessing decisions.
  3. Repeat RR times and count rejections. Report π^R\hat\pi_R with Monte Carlo error.
  4. To size the study, repeat over a grid of nn values (or bisect) using common random numbers (same seed for each nn), making the power-versus-nn curve smooth and monotone.
  5. Check that with δ=0\delta = 0 rejection rate is α\alpha: otherwise the procedure is miscalibrated and its power is meaningless.

To keep the cell fast, the generator returns all RR replicates at once as matrices and the test calculates RR p-values row by row.

[ ]A generic simulation power calculatorBrowser
import numpy as np
from scipy import stats
from scipy.stats import norm, rankdata

def potencia_sim(gen, test, n, R=4000, alpha=0.05, seed=0):
    """Fracción de rechazos en R estudios simulados y su error de Monte Carlo."""
    rng = np.random.default_rng(seed)
    x, y = gen(rng, n, R)                       # dos matrices (R, n)
    p = np.mean(test(x, y) < alpha)
    return p, np.sqrt(p * (1 - p) / R)

def contraste_t(x, y):
    return stats.ttest_ind(y, x, axis=1).pvalue

def contraste_rangos(x, y):
    """Suma de rangos de Wilcoxon (Mann-Whitney), aproximación normal, sin empates."""
    n = x.shape[1]
    r = rankdata(np.concatenate([x, y], axis=1), axis=1)
    W = r[:, n:].sum(1)
    z = (W - n * (2 * n + 1) / 2) / np.sqrt(n * n * (2 * n + 1) / 12)
    return 2 * norm.sf(np.abs(z))

def normales(d):
    return lambda rng, n, R: (rng.normal(0, 1, (R, n)), rng.normal(d, 1, (R, n)))

def colas_pesadas(desp):                         # t de Student con 3 g.l. desplazada
    return lambda rng, n, R: (rng.standard_t(3, (R, n)), rng.standard_t(3, (R, n)) + desp)

# 1) calibración: con efecto nulo el test debe rechazar el 5 %
for nombre, test in (("t", contraste_t), ("rangos", contraste_rangos)):
    print(f"nivel con efecto nulo, test {nombre:6s}: {potencia_sim(normales(0.0), test, 30, R=20000)[0]:.4f}")

# 2) acuerdo con la fórmula exacta: d = 0.5, n = 64 por grupo (potencia exacta 0.8015)
p, e = potencia_sim(normales(0.5), contraste_t, 64, R=20000)
print(f"\nsimulada {p:.4f} ± {1.96 * e:.4f}   exacta con t no central: 0.8015")

# 3) datos de cola pesada: aquí el test t pierde y los rangos ganan (n = 30 por grupo)
print("\nn = 30 por grupo, desplazamiento 0.7")
for nombre, gen in (("normales", normales(0.7)), ("t con 3 g.l.", colas_pesadas(0.7))):
    pt, _ = potencia_sim(gen, contraste_t, 30, R=6000)
    pr, _ = potencia_sim(gen, contraste_rangos, 30, R=6000)
    print(f"  {nombre:13s} potencia t = {pt:.3f}   potencia rangos = {pr:.3f}")

With normal data, the rank test loses slightly to tt (asymptotic relative efficiency 3/π≈0.9553/\pi \approx 0.955). With heavy tails it wins by much: power belongs to the study–test pair, not the study alone, and simulation is the only general way to choose before collecting data. The same recipe sizes comparisons with few machine-learning seeds (variance comes from seeds and splits), mixed-model tests, or clustered experiments.

Type S and M errors: what underpowered studies report

An underpowered study fails in two ways. The obvious one: it misses the effect. The subtle one: when it detects the effect, the result misleads. Gelman and Carlin (2014) named the two biases.

Neither appears in α\alpha or β\beta: type I assumes zero effect, type II ignores what happens upon rejection. S and M describe results that are published. They need only plausible effect θ\theta and standard error ss, and have closed forms in the normal case.

Proof

With U=(θ^−θ)/s∼N(0,1)U = (\hat\theta - \theta)/s \sim \Normal(0,1), θ^/s=λ+U\hat\theta/s = \lambda + U. Rejection with positive sign is {U>z−λ}\{U > z - \lambda\}, probability Φ+\Phi_+; with negative sign {U<−z−λ}\{U < -z - \lambda\}, probability Φ−\Phi_-. Power is their sum, and type S error the second divided by the sum. For type M, E[∣θ^∣ 1(sig.)]=s(E[(λ+U)1(U>z−λ)]−E[(λ+U)1(U<−z−λ)])\E[\abs{\hat\theta}\,\ind(\text{sig.})] = s\big(\E[(\lambda + U)\ind(U > z - \lambda)] - \E[(\lambda + U)\ind(U < -z - \lambda)]\big). Using E[U 1(U>a)]=φ(a)\E[U\,\ind(U > a)] = \varphi(a) and E[U 1(U<a)]=−φ(a)\E[U\,\ind(U < a)] = -\varphi(a),

E[(λ+U)1(U>z−λ)]=λΦ++φ(z−λ),−E[(λ+U)1(U<−z−λ)]=−λΦ−+φ(z+λ).\E[(\lambda + U)\ind(U > z - \lambda)] = \lambda\Phi_+ + \varphi(z - \lambda), \qquad -\E[(\lambda + U)\ind(U < -z - \lambda)] = -\lambda\Phi_- + \varphi(z + \lambda).

Dividing by θ (Φ++Φ−)\theta\,(\Phi_+ + \Phi_-) and using θ=λs\theta = \lambda s gives the formula. The bound follows because significance requires ∣θ^∣>z s\abs{\hat\theta} > z\,s, so E[∣θ^∣∣sig.]≥z s\E[\abs{\hat\theta} \given \text{sig.}] \ge z\,s.

∎

The lower bound is central: significance filtering sets a floor for the published estimate, z sz\,s, independent of true effect. If standard error greatly exceeds effect, the floor lies well above it, and everything published exaggerates it. With effect 0.250.25 and standard error 2/40=0.224\sqrt{2/40} = 0.224 (the opening study), the floor is 0.440.44, almost double truth, and the formula (assuming known σ\sigma) gives exaggeration factor 2.252.25, reproduced by the opening tt-test cell with twenty thousand replicates (2.222.22).

InteractiveThe winner's curse
2000 studies with d=0.25d = 0.25 and n=40n = 40 per group (significant if ∣t∣>1.99|t| > 1.99)
truthpublished mean
  • significant, correct sign
  • significant, opposite sign
  • not significant
  • truth
  • published mean
Exaggeration factor versus power (retrodesign, α=0.05\alpha = 0.05)
80 %×2.3
  • theoretical exaggeration
  • this study
  • no exaggeration (×1)
0.25
40
What to show
Power (simulated | normal theory)19 % | 20 %
Mean of all d^\hat d (true dd)0.254 (0.25)
Mean of significant results0.557
Exaggeration E[ ∣d^∣∣sig.]/d\E[\,|\hat d| \mid \text{sig.}]/d (sim | theory)×2.23 | ×2.25
Opposite sign among significant results (sim | theory)0.0 % | 0.5 %
At 20 % power, significant studies exaggerate the effect by a factor of 2.3 and 0.5 % have the opposite sign. The estimator is unbiased (mean of all: 0.254); the filter introduces bias.
Two thousand two-group studies with modest true effect dd. Blue and red are significant results with correct and incorrect sign; grey are nonsignificant. The magenta line is the significant-results mean: what a reader sees if accessing only published work. With d=0.25d = 0.25 and n=40n = 40 (20 % power), the published mean is more than twice truth. Press 'Only published' to hide nonsignificant studies. Increase nn and see exaggeration dissolve as filtering stops filtering. Right: exaggeration factor depends only on power, the same curve for any effect. Lower effect to 0.10.1 with n=20n = 20: how many significant results have the wrong sign?

Three readings of the figure:

  • The estimator is unbiased; selection is not. The mean over all studies equals true effect. Bias appears when conditioning on an event (significance) correlated with noise. This is the winner’s curse: the study winning the significance contest is often the luckiest.
  • Regression to the mean in published results. An effect “discovered” by a small study is on average smaller when replicated with more data, even if real. This helps explain shrinking effects in low-power literature: Button et al. (2013), using neuroscience meta-analyses published in 2011, estimated median field power between about 8 % and 31 % (21 % central estimate), and identified the same consequences, effect-size overestimation and low reproducibility.
  • Sign error is rare except at the extreme. With 20 % power, 0.5 % of significant results have the wrong sign, but at 6 % power nearly one in four do, as in Gelman and Carlin’s example (plausible effect 2 percentage points, standard error 8.1: power 6 %, type S 24 %, and exaggeration about 9.7 times according to their simulation). The next cell reproduces this with the closed formula: 5.7 % power, 24 % type S and type M 9.59.5.
[ ]Retrodesign: power, type S and type M from scratchBrowser
import numpy as np
from scipy.stats import norm

def retrodiseno(theta, se, alpha=0.05):
    """Potencia, probabilidad de error de signo y factor de exageración (aprox. normal)."""
    z = norm.ppf(1 - alpha / 2)
    lam = theta / se
    arriba, abajo = norm.sf(z - lam), norm.cdf(-z - lam)
    pot = arriba + abajo
    tipo_s = abajo / pot
    tipo_m = (lam * (arriba - abajo) + norm.pdf(z - lam) + norm.pdf(z + lam)) / (lam * pot)
    return pot, tipo_s, tipo_m

def retrodiseno_sim(theta, se, alpha=0.05, N=400_000, seed=0):
    """La misma cantidad por simulación: el filtro de significación aplicado a N estimaciones."""
    rng = np.random.default_rng(seed)
    est = theta + se * rng.standard_normal(N)
    sig = np.abs(est) > norm.ppf(1 - alpha / 2) * se
    return sig.mean(), (est[sig] < 0).mean(), np.abs(est[sig]).mean() / theta

escenarios = [
    ("estudio del inicio (d = 0.25, n = 40)", 0.25, np.sqrt(2 / 40)),
    ("el mismo con n = 160",                  0.25, np.sqrt(2 / 160)),
    ("estudio de potencia 80 %",              2.8,  1.0),
    ("Gelman y Carlin: efecto 2, se 8.1",     2.0,  8.1),
    ("ablación: 0.3 puntos, se 0.5",          0.3,  0.5),
]
print(f"{'escenario':40s} {'potencia':>9s} {'tipo S':>8s} {'tipo M':>7s}   (simulado: pot, S, M)")
for nombre, th, se in escenarios:
    pot, s, m = retrodiseno(th, se)
    ps, ss, ms = retrodiseno_sim(th, se)
    print(f"{nombre:40s} {pot:9.3f} {s:8.4f} {m:7.2f}   ({ps:.3f}, {ss:.4f}, {ms:.2f})")

print("\npotencia -> factor de exageración")
for pot in (0.1, 0.2, 0.5, 0.8, 0.9):
    lo, hi = 0.01, 8.0
    for _ in range(60):                          # bisección sobre lambda = theta / se
        mid = (lo + hi) / 2
        lo, hi = (mid, hi) if retrodiseno(mid, 1)[0] < pot else (lo, mid)
    print(f"  {pot:4.0%}  ->  x{retrodiseno(lo, 1)[2]:.2f}")

Remember the second table: at 80 % power exaggeration is 12 %, at 50 % it is 41 %, at 20 % more than double, and at 10 % nearly fourfold.

What to do

  • Retrodesign before interpreting. Given a plausible effect (not the observed one) and study standard error, calculate power, type S and type M. If type M exceeds 1.5, treat the estimate as an upper bound on effect rather than its value.
  • Size using conservative effects, never the estimate from a small significant study: selection has already inflated it.
  • Shrink estimates. Estimators shrinking toward the mean (hierarchical, empirical Bayesian models; see the Stein paradox) correct some selection bias.
  • Report everything. The winner’s curse needs a filter; registered reports and publication of null results remove it. When many tests are analyzed, the filter is in what is chosen to inspect (multiple comparisons, post-selection inference).

The post hoc power fallacy

A nonsignificant result invites the question: “did the study have enough power?” It is tempting to calculate power using the observed effect. Some packages call this “observed power”. But it adds no information beyond the p-value.

The guided exercise proves this. Its consequences are concrete. A result with p=0.2p = 0.2 always has observed power 0.250.25, one with p=0.5p = 0.5 has 0.100.10, and p=0.05p = 0.05 gives 0.500.50. Saying “the result was nonsignificant, but observed power was low” repeats the p-value under another name; saying “the study was underpowered because observed power was 25 %” is circular: every p=0.2p = 0.2 result has it regardless of study size. Hoenig and Heisey (2001) stated this clearly, and it remains valid.

The underlying issue: power is a property of the design against a hypothetical effect, while the estimated effect is random and cannot be treated as known. Legitimate alternatives:

  • Power (or MDE) against a practically relevant effect, calculated before or after without using the observed effect: “the study had 85 % power against a 5-point difference”.
  • The confidence interval, which already contains the information: if it excludes relevant effects, the nonsignificant result is informative; if it includes them, the study cannot rule them out.
  • An equivalence test, reversing the null to support a small effect (developed in hypothesis tests).

Using libraries

statsmodels.stats.power solves the same equations with noncentral tt, solving for any of four quantities (effect size, nn, α\alpha, power) from the other three: set the sought one to None. The cell compares our functions and calculates MDE and sample size for proportions.

[ ]statsmodels.stats.power versus our formulasBrowser
import numpy as np
from scipy.stats import norm, nct, t as tdist
from statsmodels.stats.power import TTestIndPower, NormalIndPower
from statsmodels.stats.proportion import proportion_effectsize

def potencia_t(d, n, alpha=0.05):
    nu, lam = 2 * n - 2, d * np.sqrt(n / 2)
    c = tdist.ppf(1 - alpha / 2, nu)
    return nct.sf(c, nu, lam) + nct.cdf(-c, nu, lam)

an = TTestIndPower()
print("n por grupo para d = 0.5, 80 %:", round(an.solve_power(effect_size=0.5, alpha=0.05, power=0.8), 3))
print("potencia con n = 64:           ", round(an.power(effect_size=0.5, nobs1=64, alpha=0.05), 5), "| a mano:", round(potencia_t(0.5, 64), 5))
print("MDE (en d) con n = 64, 80 %:    ", round(an.solve_power(nobs1=64, alpha=0.05, power=0.8), 4))
print("n unilateral (d = 0.5):         ", round(an.solve_power(effect_size=0.5, alpha=0.05, power=0.8, alternative="larger"), 2))
print("n normal (NormalIndPower):      ", round(NormalIndPower().solve_power(effect_size=0.5, alpha=0.05, power=0.8), 3))

# proporciones: 5 % -> 5.5 % (mejora relativa del 10 %); h de Cohen y fórmula propia
p1, p2 = 0.05, 0.055
h = proportion_effectsize(p2, p1)
n_h = NormalIndPower().solve_power(effect_size=h, alpha=0.05, power=0.8)
pb = (p1 + p2) / 2
za, zb = norm.ppf(0.975), norm.ppf(0.8)
n_propia = (za * np.sqrt(2 * pb * (1 - pb)) + zb * np.sqrt(p1 * (1 - p1) + p2 * (1 - p2))) ** 2 / (p2 - p1) ** 2
print(f"\nproporciones 5 % -> 5.5 %: h = {h:.4f}; n con h = {n_h:,.0f}; n con la fórmula de las dos varianzas = {n_propia:,.0f}")

Two observations: solve_power finds MDE by leaving effect size unspecified, and the two proportion methods (arcsine transform with hh and separate variances) give 31 217 and 31 233 per arm here: agreement within 0.1 % at moderate rates and small effects, diverging more near 0 or 1 or with large effects. Choose one and report it.

Common mistakes

Exercises

NumericPer-group size for a small effect
You want to detect a mean difference of 0.2σ0.2\sigma between two groups at two-sided α=0.05\alpha = 0.05 and power 0.80.8. Under the normal approximation, how many individuals per group are needed (round up)?
NumericPower of a one-sided z test
A one-sided zz test with α=0.05\alpha = 0.05 rejects when Z>z0.95Z > z_{0.95}. If the true effect satisfies n δ/σ=2\sqrt n\,\delta/\sigma = 2, what is its power?
NumericThe exaggeration factor
A study estimates an effect with standard error s=0.25s = 0.25 and true effect θ=0.5\theta = 0.5. With two-sided α=0.05\alpha = 0.05 and a normal approximation, what is the exaggeration factor (type M) among significant results?
ProofPost hoc power adds no information
Prove: In a level-α\alpha two-sided zz test, power π^\hat\pi calculated using observed effect δ^\hat\delta is a strictly decreasing function of the p-value. In particular, π^\hat\pi contains no more information than pp.
0
Let zobs=δ^/SEz_{\mathrm{obs}} = \hat\delta/\mathrm{SE}, z=z1−α/2z = z_{1-\alpha/2} and g(u)=Φ(u−z)+Φ(−u−z)g(u) = \Phi(u - z) + \Phi(-u - z) for u≥0u \ge 0.

Step 1 of 4. How is π^\hat\pi expressed in terms of zobsz_{\mathrm{obs}}?

CodeSimulated power of a permutation test
Complete potencia_permutacion(n, delta, R, B, alpha, seed): power estimated from R simulated studies of a two-group mean-difference permutation test with n per group (N(0,1)\Normal(0,1) data in the first and N(δ,1)\Normal(\delta,1) in the second). In each study calculate observed statistic ∣yˉ−xˉ∣\abs{\bar y - \bar x}, generate B label permutations (randomly divide the 2n2n observations into groups of size n) and obtain the p-value =(1+#{permutaciones con estadıˊstico≥observado})/(B+1)= (1 + \#\{\text{permutaciones con estadístico} \ge \text{observado}\})/(B + 1). Reject if p-value is at most alpha. Do not loop over permutations: generate all B at once with np.argsort(rng.random((B, 2 * n)), axis=1).
import numpy as np

def potencia_permutacion(n, delta, R=300, B=199, alpha=0.05, seed=0):
  """Potencia por simulación del test de permutación de la diferencia de medias."""
  rng = np.random.default_rng(seed)
  rechazos = 0
  for _ in range(R):
      x = rng.normal(0.0, 1.0, n)
      y = rng.normal(delta, 1.0, n)
      # tu código: estadístico observado, B permutaciones de las etiquetas y valor p con el +1
      pvalor = 1.0
      rechazos += pvalor <= alpha
  return rechazos / R
Shift+Enter to run
QuizA significant result with n = 20
A study with n=20n = 20 per group finds a significant difference (p=0.03p = 0.03) with d^=0.9\hat d = 0.9. Your prior power estimate for plausible effect (d=0.3d = 0.3) was 15 %. Which claims are correct?

More than one answer may be correct.

QuizHalf the effect
A study is sized to detect δ∗\delta^\ast with α=0.05\alpha = 0.05 and 80 % power. To retain the same power and level while detecting only δ∗/2\delta^\ast/2, how does required sample size change?
QuizSame effect, different d
Two trials measure the same intervention on a score. A finds mean improvement 4 points with σ=8\sigma = 8; B finds improvement 4 points with σ=20\sigma = 20. Which conclusion is correct?

More than one answer may be correct.

Summary

Key idea
Power is a property of test, design and effect: π(δ)\pi(\delta) depends on δ/SE\delta/\mathrm{SE}, so detecting half the effect costs four times the data, and when an underpowered study does reject, its estimate is inflated by the significance filter itself.
  • Power function. π(δ)=Φ(λ−z1−α/2)+Φ(−λ−z1−α/2)\pi(\delta) = \Phi(\lambda - z_{1-\alpha/2}) + \Phi(-\lambda - z_{1-\alpha/2}) with λ=δ/SE\lambda = \delta/\mathrm{SE}; it equals α\alpha at 0, increases in ∣δ∣\abs\delta and nn, and is 50 % when effect is 1.961.96 standard errors, 80 % when 2.82.8.
  • Effect size. Absolute (original units), relative (RR, OR) or standardized (dd, hh). dd changes with population variability; OR differs from RR except for rare events. Always report effect in original units with its interval.
  • Sample size. n=2σ2(z1−α/2+z1−β)2/δ2≈16/d2n = 2\sigma^2(z_{1-\alpha/2} + z_{1-\beta})^2/\delta^2 \approx 16/d^2 per group; MDE≈2.8 SE\mathrm{MDE} \approx 2.8\,\mathrm{SE}. Size for the smallest relevant effect with conservative σ\sigma, correcting for losses, clustering and multiple comparisons.
  • Noncentral t. T∼t2n−2(dn/2)T \sim t_{2n-2}(d\sqrt{n/2}): exact tt-test power. Normal approximation underestimates size by about z2/4≈1z^2/4 \approx 1 per group.
  • Simulation. Generator under reference effect, analysis as planned, rejection fraction with Monte Carlo error, common random numbers to search nn, and check that zero effect rejects at α\alpha.
  • S and M errors. Conditional on significance, exaggeration factor is at least z s/θz\,s/\theta; at 20 % power it exceeds 2, and at 80 % is 1.12. Retrodesign with plausible effects, not the observed effect.
  • Post hoc power. Power at the observed effect decreases with the p-value and adds no information. Use MDE, power for a relevant effect, or a confidence interval.