Skip to content

Power, by formula and by simulation

Plan a study around an effect worth detecting, compute the sample by formula, check it by simulation, and know why observed power tells you nothing new.

Applied ~13 min9 steps

What runs in CodeSplash

You will be able to

  • Explain power and the four quantities that determine it
  • Compute a sample size in CodeSplash from an effect worth detecting
  • Check a power calculation by simulation
  • Explain why observed power should not be reported

Read first

01

Four dials

Read

PowerStatistical powerThe chance a test detects an effect of a given size, if that effect is real. is the chance of detecting an effect that is really there. Four quantities are tied together, so fixing three sets the fourth:

  • the effect size
  • the sample size
  • α\alpha, the false-positive rate you accept
  • the power

Power is a property of a design at a particular effect, not of a result. "This study has 80% power" means nothing until you say for which effect.

02

Feel the dials

Explore

Move the true effect and the group size. Find a setting with power near 0.8. Then halve the effect and see how far you have to raise nn to get back there.

BExplorable · Power explorer

How likely is my study to detect an effect that is really there?

Guess the power: the chance this study rejects H0 if the effect is real.

0.50
How sure?
0.50

Standardized difference between the group means.

30

α

Alternative

1

Each outcome is tested at α ÷ this number.

E[t] = 1.94H₁

Solid: t under H₀. Dashed: t if the effect is real. Shaded orange: power, the alternative's area inside the hatched rejection region.

80%

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

03

How much more data?

Predict

Predict first

At d=0.5d = 0.5, two-sided α=.05\alpha = .05 and 80% power, a two-sample t test needs 64 per group. If the effect you need to detect is half as large, how many will you need?

Twice as manyFour times as manyTen times as many
Reveal

About four times as many. Sample size grows with 1/d21/d^2, because the standard error shrinks only with n\sqrt{n}. At a very small effect this becomes daunting: dd = 0.0500 at a stricter α\alpha = 0.00500 needs 10,653 per group.

04

Pick the effect honestly

Read

The hardest input is the effect size, and the usual sources mislead.

  • Pilot estimates are noisy, and the optimistic ones are the ones that get followed up.
  • Published effects are inflated by selection.
  • Benchmarks like "medium" know nothing about your field.

The defensible choice is the smallest effect size of interestSmallest effect size of interestThe smallest effect that would matter in practice; below it, an effect is treated as negligible.: the smallest effect that would change what someone does. If you can't name it, you aren't ready to plan.

Power analysis: two-sample t-testRecorded · Python and R agreeRecorded 2026-11-09 · 11 values compared
R

n = 64 + 64 (N = 128), d = 0.50, α = 0.05, 1 − β = 0.801

Group 1 / pairs / participants
64
Group 2
64
Total
128
Power
0.8015
Effect size d
0.5000
df
126
Noncentrality δ
2.828

Plots

Power by sample sizeHow does power grow with sample size (or effect size), and where does it reach the target?
View data
PowerEffectSample size (group 1)
0.0565d = 0.382
0.0902d = 0.385.950
0.1240d = 0.389.900
0.1581d = 0.3813.850
0.1925d = 0.3817.800
0.2268d = 0.3821.750
0.2610d = 0.3825.700
0.2949d = 0.3829.650
0.3282d = 0.3833.600
0.3609d = 0.3837.550
0.3929d = 0.3841.500
0.4241d = 0.3845.450
0.4544d = 0.3849.400
0.4837d = 0.3853.350
0.5121d = 0.3857.300
0.5394d = 0.3861.250
0.5656d = 0.3865.200
0.5908d = 0.3869.150
0.6149d = 0.3873.100
0.6379d = 0.3877.050
0.6599d = 0.3881
0.6808d = 0.3884.950
0.7007d = 0.3888.900
0.7196d = 0.3892.850
0.7376d = 0.3896.800
0.7545d = 0.38100.75
0.7706d = 0.38104.70
0.7857d = 0.38108.65
0.8000d = 0.38112.60
0.8135d = 0.38116.55
0.8262d = 0.38120.50
0.8381d = 0.38124.45
0.8493d = 0.38128.40
0.8598d = 0.38132.35
0.8697d = 0.38136.30
0.8789d = 0.38140.25
0.8875d = 0.38144.20
0.8956d = 0.38148.15
0.9032d = 0.38152.10
0.9102d = 0.38156.05
0.9168d = 0.38160
0.0615d = 0.502
0.1223d = 0.505.950
0.1835d = 0.509.900
0.2448d = 0.5013.850
0.3051d = 0.5017.800
0.3636d = 0.5021.750
0.4199d = 0.5025.700
0.4733d = 0.5029.650
0.5236d = 0.5033.600
0.5707d = 0.5037.550
0.6143d = 0.5041.500
0.6546d = 0.5045.450
0.6916d = 0.5049.400
0.7253d = 0.5053.350
0.7560d = 0.5057.300
0.7837d = 0.5061.250
0.8088d = 0.5065.200
0.8313d = 0.5069.150
0.8515d = 0.5073.100

First 60 of 123 rows.

Required size of group 1 (or pairs / participants) by power

Effect70% power80% power90% power95% power
d = 0.3889113151186
d = 0.50516486105
d = 0.6233425568
  • Noncentral t; two-sided power adds both rejection tails. Required sizes are rounded up and the power is recomputed at the rounded size.
  • Group 2 = ceiling(1 × group 1).
The exact R script · R R version 4.5.1 (2025-06-13)
# Power analysis — t tests
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method power.ttest 1.0.0 · spec 91cdd5784bea1eda
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_power_t() and the Brent solvers (twin of codesplash.stats.power)

# %% Inputs
solve_for <- "n" # n | power | effect
design <- "two-sample" # two-sample | paired | one-sample
alpha <- 0.05
alternative <- "two-sided" # two-sided adds both rejection tails (power.t.test(strict = TRUE))
two <- design == "two-sample"
ratio <- if (two) 1 else NA # n2 / n1
d <- 0.5
n_given <- 30
target <- 0.8
warnings <- list()
lo <- if (two) max(2, 2 / ratio) else 2 # smallest size with a defined test (n2 >= 2 too)

power_at <- function(n1, eff, n2 = NULL) {
  # Power with n1 in group 1 (n2 = ratio * n1 unless given) - noncentral t
  if (two) cs_power_t(eff, n1, if (is.null(n2)) ratio * n1 else n2, alpha, alternative)
  else cs_power_t(eff, n1, NULL, alpha, alternative)
}

# Equivalent idiom for equal groups: power.t.test(delta = d, sd = 1, sig.level = alpha, power = target,
# type = "two.sample", strict = TRUE) - solved here with tighter tolerances so R and Python agree.
# %% Solve
n_exact <- NA
target_power <- NA
if (solve_for == "n") {
  target_power <- target
  n_exact <- cs_power_solve_increasing(function(n) power_at(n, d), target, lo, max(2 * lo, 10), 1e7)
  if (is.nan(n_exact)) warnings <- c(warnings, "The target power is not reached below 10,000,000 participants.")
  n1 <- cs_power_ceil(n_exact)
} else if (solve_for == "power") {
  n1 <- n_given
} else {
  target_power <- target
  n1 <- n_given
  d <- cs_power_solve_increasing(function(e) power_at(n1, e), target, 1e-6, 1, 1000)
  if (is.nan(d)) warnings <- c(warnings, "No effect size up to d = 1000 reaches the target power with this sample.")
}
n2 <- if (two) cs_power_ceil(ratio * n1) else NA
power <- power_at(n1, d, if (two) n2 else NULL)
n_total <- if (two) n1 + n2 else n1
df <- if (two) n1 + n2 - 2 else n1 - 1
ncp <- if (two) abs(d) * sqrt(n1 * n2 / (n1 + n2)) else abs(d) * sqrt(n1)
crit <- stats::qt(alpha / (if (alternative == "two-sided") 2 else 1), df, lower.tail = FALSE)
if (is.finite(n1) && (n1 < 2 || (two && n2 < 2))) warnings <- c(warnings, "Each group needs at least two participants.")

# %% Curves and sensitivity
labels <- c("two-sample" = "two-sample t-test", "paired" = "paired t-test", "one-sample" = "one-sample t-test")
n_ref <- if (is.finite(n1)) n1 else 100
xs <- cs_power_grid(lo, max(2.5 * n_ref, lo + 10))
effects <- if (is.finite(d)) c(0.75 * d, d, 1.25 * d) else 0.5
curve <- do.call(rbind, lapply(effects, function(e) {
  data.frame(x = xs, power = vapply(xs, function(x) power_at(x, e), numeric(1)), series = sprintf("d = %.2f", e))
}))
tables <- list()
if (solve_for == "n" && is.finite(d)) {
  rows <- lapply(effects, function(e) {
    row <- list(effect = sprintf("d = %.2f", e))
    for (tp in c(0.7, 0.8, 0.9, 0.95)) {
      row[[sprintf("p%d", round(tp * 100))]] <-
        cs_power_ceil(cs_power_solve_increasing(function(n) power_at(n, e), tp, lo, max(2 * lo, 10), 1e7))
    }
    row
  })
  tables <- list(list(
    key = "sensitivity", title = "Required size of group 1 (or pairs / participants) by power",
    columns = c(list(list(key = "effect", label = "Effect", type = "string")),
                lapply(c(70, 80, 90, 95), function(p) list(key = sprintf("p%d", p), label = sprintf("%d%% power", p), type = "integer"))),
    rows = rows
  ))
}

# %% Result
size_text <- if (two) sprintf("%s + %s (N = %s)", format(n1, big.mark = ","), format(n2, big.mark = ","), format(n_total, big.mark = ",")) else format(n1, big.mark = ",")
stats_list <- list(
  list(key = "n", label = if (two) "Group 1 / pairs / participants" else if (design == "paired") "Pairs" else "Participants", value = n1, format = "integer")
)
if (two) {
  stats_list <- c(stats_list, list(list(key = "n2", label = "Group 2", value = n2, format = "integer"),
                                   list(key = "n_total", label = "Total", value = n_total, format = "integer")))
}
stats_list <- c(stats_list, list(
  list(key = "power", label = "Power", value = power),
  list(key = "d", label = "Effect size d", value = d),
  list(key = "df", label = "df", value = df),
  list(key = "ncp", label = "Noncentrality δ", value = ncp)
))
cs_publish(list(
  method = "power.ttest",
  methodVersion = "1.0.0",
  title = sprintf("Power analysis: %s", labels[[design]]),
  engine = cs_engine_info("stats"),
  summary = sprintf("%s: n = %s, d = %.3f, power = %.3f at %s alpha = %s.", labels[[design]], size_text, d, power, alternative, format(alpha)),
  apa = sprintf("n = %s, d = %s, α = %s, 1 − β = %.3f", size_text, cs_fmt_num(d), format(alpha), power),
  statistics = stats_list,
  tables = tables,
  warnings = warnings,
  notes = c("Noncentral t; two-sided power adds both rejection tails. Required sizes are rounded up and the power is recomputed at the rounded size.",
            if (two) sprintf("Group 2 = ceiling(%s × group 1).", format(ratio))),
  charts = list(cs_chart(
    "power", "power-curve", "Power by sample size",
    list(x = cs_col(if (two) "Sample size (group 1)" else "Sample size", curve$x),
         power = cs_col("Power", curve$power),
         series = cs_col("Effect", curve$series)),
    controls = list(target = if (is.na(target_power)) 0.8 else target)
  )),
  values = list(
    n = n1, n2 = n2, n_total = n_total, n_exact = n_exact, power = power, target_power = target_power,
    d = d, df = df, ncp = ncp, crit = crit, alpha = alpha
  )
))
Python

n = 64 + 64 (N = 128), d = 0.50, α = 0.05, 1 − β = 0.801

Group 1 / pairs / participants
64
Group 2
64
Total
128
Power
0.8015
Effect size d
0.5000
df
126
Noncentrality δ
2.828

To keep this page light, the plots are shown once, under the R tab.

Required size of group 1 (or pairs / participants) by power

Effect70% power80% power90% power95% power
d = 0.3889113151186
d = 0.50516486105
d = 0.6233425568
  • Noncentral t; two-sided power adds both rejection tails. Required sizes are rounded up and the power is recomputed at the rounded size.
  • Group 2 = ⌈1 × group 1⌉.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Power analysis — t tests
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method power.ttest 1.0.0 · spec 91cdd5784bea1eda
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import math

import numpy as np
from scipy import stats

import codesplash as cs
from codesplash.stats import power as pw  # noncentral-t power and Brent solvers (twin of R cs_power_*)

# %% Inputs
solve_for = "n"  # n | power | effect
design = "two-sample"  # two-sample | paired | one-sample
alpha = 0.05
alternative = "two-sided"  # two-sided adds both rejection tails (power.t.test(strict = TRUE))
ratio = 1 if design == "two-sample" else None  # n2 / n1
d = 0.5
n_given = 30
target = 0.8
warnings = []
two = design == "two-sample"
lo = max(2.0, 2.0 / ratio) if two else 2.0  # smallest size with a defined test (n2 ≥ 2 too)


def power_at(n1, eff, n2=None):
    """Power with n1 in group 1 (n2 = ratio · n1 unless given) — noncentral t."""
    if two:
        return pw.t_power(eff, n1, ratio * n1 if n2 is None else n2, alpha, alternative)
    return pw.t_power(eff, n1, None, alpha, alternative)


# Equivalent idiom: statsmodels.stats.power.TTestIndPower().solve_power(effect_size=d, alpha=alpha,
# power=target, ratio=ratio) — solved here with tighter tolerances so Python and R agree.
# %% Solve
n_exact = None
target_power = None
if solve_for == "n":
    target_power = target
    n_exact = pw.solve_increasing(lambda n: power_at(n, d), target, lo, max(2.0 * lo, 10.0), 1e7)
    if math.isnan(n_exact):
        warnings.append("The target power is not reached below 10,000,000 participants.")
    n1 = pw.ceil_n(n_exact)
elif solve_for == "power":
    n1 = n_given
else:
    target_power = target
    n1 = n_given
    d = pw.solve_increasing(lambda e: power_at(n1, e), target, 1e-6, 1.0, 1000.0)
    if math.isnan(d):
        warnings.append("No effect size up to d = 1000 reaches the target power with this sample.")
n2 = pw.ceil_n(ratio * n1) if two else None
power = power_at(n1, d, n2)
n_total = n1 + n2 if two else n1
df = n1 + n2 - 2.0 if two else n1 - 1.0
ncp = abs(d) * math.sqrt(n1 * n2 / (n1 + n2)) if two else abs(d) * math.sqrt(n1)
crit = float(stats.t.isf(alpha / (2 if alternative == "two-sided" else 1), df))
if n1 < 2 or (two and n2 < 2):
    warnings.append("Each group needs at least two participants.")

# %% Curves and sensitivity
labels = {"two-sample": "two-sample t-test", "paired": "paired t-test", "one-sample": "one-sample t-test"}
n_ref = n1 if math.isfinite(n1) else 100.0
xs = pw.grid(lo, max(2.5 * n_ref, lo + 10.0))
effects = [0.75 * d, d, 1.25 * d] if math.isfinite(d) else [0.5]
curve_x, curve_power, curve_series = [], [], []
for e in effects:
    for x in xs:
        curve_x.append(float(x))
        curve_power.append(power_at(float(x), e))
        curve_series.append(f"d = {e:.2f}")
tables = []
if solve_for == "n" and math.isfinite(d):
    rows = []
    for e in effects:
        row = {"effect": f"d = {e:.2f}"}
        for tp in (0.7, 0.8, 0.9, 0.95):
            row[f"p{round(tp * 100)}"] = pw.ceil_n(pw.solve_increasing(lambda n: power_at(n, e), tp, lo, max(2.0 * lo, 10.0), 1e7))
        rows.append(row)
    tables.append({
        "key": "sensitivity", "title": "Required size of group 1 (or pairs / participants) by power",
        "columns": [{"key": "effect", "label": "Effect", "type": "string"}]
        + [{"key": f"p{p}", "label": f"{p}% power", "type": "integer"} for p in (70, 80, 90, 95)],
        "rows": rows,
    })

# %% Result
size_text = f"{n1:,.0f} + {n2:,.0f} (N = {n_total:,.0f})" if two else f"{n1:,.0f}"
summary = f"{labels[design].capitalize()}: n = {size_text}, d = {d:.3f}, power = {power:.3f} at {alternative} α = {alpha}."
cs.publish({
    "method": "power.ttest",
    "methodVersion": "1.0.0",
    "title": f"Power analysis: {labels[design]}",
    "engine": cs.engine_info("numpy", "scipy"),
    "summary": summary,
    "apa": f"n = {size_text}, d = {cs.fmt_num(d)}, α = {alpha}, 1 − β = {power:.3f}",
    "statistics": [
        {"key": "n", "label": "Group 1 / pairs / participants" if two else ("Pairs" if design == "paired" else "Participants"), "value": n1, "format": "integer"},
        *([{"key": "n2", "label": "Group 2", "value": n2, "format": "integer"}, {"key": "n_total", "label": "Total", "value": n_total, "format": "integer"}] if two else []),
        {"key": "power", "label": "Power", "value": power},
        {"key": "d", "label": "Effect size d", "value": d},
        {"key": "df", "label": "df", "value": df},
        {"key": "ncp", "label": "Noncentrality δ", "value": ncp},
    ],
    "tables": tables,
    "warnings": warnings,
    "notes": [
        "Noncentral t; two-sided power adds both rejection tails. Required sizes are rounded up and the power is recomputed at the rounded size.",
        *([f"Group 2 = ⌈{ratio:g} × group 1⌉."] if two else []),
    ],
    "charts": [cs.chart(
        "power", "power-curve", "Power by sample size",
        {"x": cs.col("Sample size (group 1)" if two else "Sample size", curve_x),
         "power": cs.col("Power", curve_power),
         "series": cs.col("Effect", curve_series)},
        controls={"target": target if target_power is not None else 0.8},
    )],
    "values": {
        "n": n1, "n2": n2, "n_total": n_total, "n_exact": n_exact, "power": power, "target_power": target_power,
        "d": d, "df": df, "ncp": ncp, "crit": crit, "alpha": alpha,
    },
})

Design matters too. Pairing can reduce the sample a lot: dd = 0.600 needs only 24 pairs for power 0.804.

05

Simulate when no formula fits

Read

Formulas exist for standard designs. For anything messy, such as clusters, dropout, skew or sequential looks, simulate: generate data under your assumed effect, run the planned analysis, and count how often it rejects.

Python
import numpy as np
from scipy import stats

rng = np.random.default_rng(1)
rejections = 0
for _ in range(5000):
    a = rng.normal(0.5, 1, 64)
    b = rng.normal(0.0, 1, 64)
    rejections += stats.ttest_ind(a, b, equal_var=False).pvalue < 0.05
print(rejections / 5000)   # close to the formula's power
R
set.seed(1)
reject <- replicate(5000, {
  a <- rnorm(64, 0.5, 1)
  b <- rnorm(64, 0.0, 1)
  t.test(a, b)$p.value < 0.05
})
mean(reject)   # close to the formula's power

The formula gives 0.801 for this design. Simulation has its own uncertainty, about 0.8×0.2/5000\sqrt{0.8 \times 0.2 / 5000} here.

Check size before powerSize before powerRead a test's power only after its size holds α at the same settings; a test that rejects too often looks powerful.. Run the same simulation with no effect first. If the test rejects more or less often than α there, its rejection rate under the effect isn't power. The Simulation Lab's "Size before power" template does both for Student's and Welch's t in six scenarios, including serially dependent data, and grays out any power whose size fails.

06

The tempting mistake

Reflect

After a non-significant result, a colleague computes "observed power" from the effect the study found, gets 30%, and says the study was underpowered.

Think about what that number could possibly add. Observed power is a one-to-one function of the p-value: every p above .05 gives low observed power. It restates the p-value in other words. To discuss what a study could have detected, use the interval, or the power at your smallest effect of interest fixed in advance.

07

Check your understanding

Checkpoint

Check yourself

You want a standard error one third of its current size. By what factor must nn grow?

Show the answer

Answer: 9

The standard error scales with 1/n1/\sqrt{n}, so you need 32=93^2 = 9 times the data.

Check yourself

Which statement is right?

Show the answer

Answer: b

Power is conditional on a specified effect and belongs to the design. It says nothing about whether the effect exists.

Check yourself

Which is the best basis for the effect in a sample size calculation?

Show the answer

Answer: c

Plan for the effect worth detecting. Choosing an effect to fit the budget hides the fact that the study can't answer the question.

Check yourself

You lower α\alpha from .05 to .005 and keep nn and the effect the same. What happens to power?

Show the answer

Answer: a

A stricter threshold is harder for any effect to cross, so fewer true effects are detected unless nn grows.

08

Plan your own study

In the app

Enter your smallest effect of interest and read the required sample. In the Test Chooser, the Plan a study card routes to the right calculator for other designs.

09

Recap

Recap
  • Effect, sample, α\alpha and power are tied together; fix three and the fourth follows.
  • Sample size grows with the inverse square of the effect, so choose the effect by what matters.
  • Simulate when no formula fits, and don't report observed power.

Concepts in this lesson