Exact, asymptotic, permutation or bootstrap
The same statistic can get its reference distribution from four places. Learn what each one assumes and when the choice changes your answer.
What runs in CodeSplash
- Permutation test (two independent groups) Verified in Python and R
- Mann–Whitney U test Verified in Python and R
- Bootstrap confidence interval Verified in Python and R
- Two-sample t-test (Welch / Student, or z test) Verified in Python and R
You will be able to
- Name the four sources of a reference distribution
- Explain when an asymptotic approximation can be trusted
- Choose a calibration for a small or irregular sample
Read first
Where does the p-value come from?
ReadA test turns data into a statistic, then asks how unusual that statistic is. "Unusual" needs a reference distribution, and there are four places to get one.
| Source | How | Relies on |
|---|---|---|
| ExactExact testA test whose p-value comes from the exact distribution of the statistic, with no large-sample approximation. | Enumerate every possible outcome | A discrete null you can count |
| AsymptoticAsymptotic approximationA p-value or interval that is accurate when the sample is large enough, computed from a limiting distribution. | A formula such as , or | Large enough or a model |
| PermutationPermutation testBuilds the null distribution by reshuffling group labels, so it needs no distributional assumption. | Shuffle labels and recompute | Exchangeable units under the null |
| BootstrapBootstrapEstimates uncertainty by recomputing a statistic on many samples drawn with replacement from your data. | Resample your data | The sample standing in for the population |
Do it by counting
ReadTwo groups of 6 can be labeled in ways. An exact permutation test tries 924 of them, every one, and counts how many give a difference at least as large as the observed one: 6.
That gives p = .006, with no sampling error and no distribution assumed.
permutation test, Δ = −15.64, p = .006
- Mean difference (A − B)
- −15.636
- p
- .006
- Permutations
- 924
Effect size
- Cohen's d −1.957
Plots
View data
| section | after |
|---|---|
| A | 45.783 |
| A | 46.797 |
| A | 57.078 |
| A | 55.415 |
| A | 64.214 |
| A | 61.554 |
| B | 60.646 |
| B | 67.486 |
| B | 72.285 |
| B | 69.622 |
| B | 68.603 |
| B | 86.017 |
Assumptions
- Exchangeability — Variance ratio 1.24.
- Difference = A − B; exact (all splits); alternative: two-sided. p = count / total.
The exact R script · R R version 4.5.1 (2025-06-13)
# Permutation test (two independent groups)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method permutation.two_sample 1.0.2 · spec fa059dd1e42afbd6
# Dataset: scores (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/scores.parquet", col_select = c("after", "section")))
n_input <- nrow(df)
df[["section"]] <- factor(df[["section"]], levels = c("A", "B")) # stored level order
df <- df[stats::complete.cases(df[c("after", "section")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("after", "section")) # infinite values stop the run (registry/errors.yaml)
# %% Two samples (independent groups or paired measurements, from the bound roles)
y <- "after"
g <- "section"
levels_g <- levels(df[[g]])
if (length(levels_g) != 2) cs_error("CS_E_GROUP_COUNT", column = g, expected = 2, k = length(levels_g))
x1 <- df[[y]][df[[g]] == levels_g[1]]
x2 <- df[[y]][df[[g]] == levels_g[2]]
design <- "independent"
label_1 <- levels_g[1]
label_2 <- levels_g[2]
# %% Test
alternative <- "two-sided"
seed <- 42 # shared Wichmann-Hill stream: Python draws the same permutations
r <- cs_perm_two_sample(x1, x2, alternative = alternative, max_exact = 200000, b = 9999, seed = seed)
n1 <- length(x1)
n2 <- length(x2)
sp <- sqrt(((n1 - 1) * var(x1) + (n2 - 1) * var(x2)) / (n1 + n2 - 2))
# Cohen's d is undefined when neither sample varies (pooled SD 0): published as null.
no_spread <- length(unique(x1)) < 2 && length(unique(x2)) < 2
d <- if (no_spread) NA_real_ else r$diff / sp
# %% Assumptions
v1 <- var(x1)
v2 <- var(x2)
ratio <- if (min(v1, v2) > 0) max(v1, v2) / min(v1, v2) else Inf
assumptions <- list(list(key = "exchangeability", label = "Exchangeability", status = if (ratio > 4) "warn" else "pass",
detail = paste0(sprintf("Variance ratio %.2f", ratio),
if (ratio > 4) "; very different spreads make the labels non-exchangeable (consider Welch's test)." else ".")))
# %% Result
values <- list(diff = r$diff, p = r$p, n_perm = r$n_perm, exact = r$exact, count = r$count, mean_1 = mean(x1), mean_2 = mean(x2),
n_1 = n1, n_2 = n2, cohens_d = d, level_1 = label_1, level_2 = label_2)
chart_rows <- unique(round(seq(1, nrow(df), length.out = min(nrow(df), 5000))))
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0 # consult-a-statistician input
how <- if (r$exact) "exact (all splits)" else sprintf("%d Monte Carlo permutations, seed %d", as.integer(r$n_perm), as.integer(seed))
cs_publish(list(
method = "permutation.two_sample",
methodVersion = "1.0.2",
title = "Permutation test",
engine = cs_engine_info("stats", "nanoparquet"),
n = n1 + n2,
summary = sprintf("Difference in means %.3f; permutation %s (%s).", r$diff, cs_fmt_p(r$p), how),
apa = sprintf("permutation test, Δ = %s, %s", cs_fmt_num(r$diff), cs_fmt_p(r$p)),
statistics = list(list(key = "diff", label = sprintf("Mean difference (%s − %s)", label_1, label_2), value = r$diff),
list(key = "p", label = "p", value = r$p, format = "p"),
list(key = "n_perm", label = "Permutations", value = r$n_perm, format = "integer")),
effectSizes = list(list(key = "cohens_d", label = "Cohen's d", value = d, method = "pooled SD")),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("Difference = %s − %s; %s; alternative: %s. ", label_1, label_2, how, alternative),
if (r$exact) "p = count / total." else "p = (count + 1) / (permutations + 1).")),
values = values,
charts = list(cs_chart("distribution", "raincloud", sprintf("%s by %s", y, g),
list(y = cs_col(y, df[[y]][chart_rows]), group = cs_col(g, as.character(df[[g]][chart_rows]), levels = levels_g))))
))
permutation test, Δ = −15.64, p = .006
- Mean difference (A − B)
- −15.636
- p
- .006
- Permutations
- 924
Effect size
- Cohen's d −1.957
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Exchangeability — Variance ratio 1.24.
- Difference = A − B; exact (all splits); alternative: two-sided. p = count / total.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Permutation test (two independent groups)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method permutation.two_sample 1.0.2 · spec fa059dd1e42afbd6
# Dataset: scores (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import permutation
# %% Data
df = pd.read_parquet("tests/parity/fixtures/scores.parquet", columns=["after", "section"])
n_input = len(df)
df["section"] = pd.Categorical(df["section"], categories=["A", "B"]) # stored level order
df = df.dropna(subset=["after", "section"]) # listwise deletion over the analysis columns
df["section"] = df["section"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["after", "section"]) # infinite values stop the run (registry/errors.yaml)
# %% Two samples (independent groups or paired measurements, from the bound roles)
y = "after"
g = "section"
levels = [str(x) for x in df[g].cat.categories]
if len(levels) != 2:
cs.cs_error("CS_E_GROUP_COUNT", column=g, expected=2, k=len(levels))
x1 = df.loc[df[g] == df[g].cat.categories[0], y].to_numpy(dtype=float)
x2 = df.loc[df[g] == df[g].cat.categories[1], y].to_numpy(dtype=float)
design, label_1, label_2 = "independent", levels[0], levels[1]
# %% Test
alternative = "two-sided"
seed = 42 # shared Wichmann–Hill stream: R draws the same permutations
r = permutation.two_sample(x1, x2, alternative=alternative, max_exact=200000, b=int(9999), seed=seed)
n1, n2 = len(x1), len(x2)
sp = np.sqrt(((n1 - 1) * np.var(x1, ddof=1) + (n2 - 1) * np.var(x2, ddof=1)) / (n1 + n2 - 2))
# Cohen's d is undefined when neither sample varies (pooled SD 0): published as null, as in R.
no_spread = len(np.unique(x1)) < 2 and len(np.unique(x2)) < 2
d = None if no_spread else float(r["diff"] / sp)
# %% Assumptions
# A sample with no spread has exactly zero variance (np.var can leave rounding noise), as in R.
v1 = 0.0 if len(np.unique(x1)) < 2 else np.var(x1, ddof=1)
v2 = 0.0 if len(np.unique(x2)) < 2 else np.var(x2, ddof=1)
ratio = max(v1, v2) / min(v1, v2) if min(v1, v2) > 0 else float("inf")
assumptions = [{"key": "exchangeability", "label": "Exchangeability", "status": "warn" if ratio > 4 else "pass",
"detail": f"Variance ratio {ratio:.2f}" + ("; very different spreads make the labels non-exchangeable (consider Welch's test)." if ratio > 4 else ".")}]
# %% Result
values = {"diff": r["diff"], "p": r["p"], "n_perm": r["n_perm"], "exact": r["exact"], "count": r["count"], "mean_1": float(x1.mean()),
"mean_2": float(x2.mean()), "n_1": n1, "n_2": n2, "cohens_d": d, "level_1": label_1, "level_2": label_2}
chart_rows = np.unique(np.round(np.linspace(0, len(df) - 1, min(len(df), 5000))).astype(int))
how = "exact (all splits)" if r["exact"] else f"{r['n_perm']} Monte Carlo permutations, seed {seed}"
values["missing_share"] = n_dropped / n_input if n_input else 0.0 # consult-a-statistician input
cs.publish({
"method": "permutation.two_sample",
"methodVersion": "1.0.2",
"title": "Permutation test",
"engine": cs.engine_info("pandas", "numpy"),
"n": n1 + n2,
"summary": f"Difference in means {r['diff']:.3f}; permutation {cs.fmt_p(r['p'])} ({how}).",
"apa": f"permutation test, Δ = {cs.fmt_num(r['diff'])}, {cs.fmt_p(r['p'])}",
"statistics": [{"key": "diff", "label": f"Mean difference ({label_1} − {label_2})", "value": r["diff"]},
{"key": "p", "label": "p", "value": r["p"], "format": "p"},
{"key": "n_perm", "label": "Permutations", "value": r["n_perm"], "format": "integer"}],
"effectSizes": [{"key": "cohens_d", "label": "Cohen's d", "value": d, "method": "pooled SD"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Difference = {label_1} − {label_2}; {how}; alternative: {alternative}. "
+ ("p = count / total." if r["exact"] else "p = (count + 1) / (permutations + 1).")],
"values": values,
"charts": [cs.chart("distribution", "raincloud", f"{y} by {g}", {
"y": cs.col(y, df[y].to_numpy(dtype=float)[chart_rows]),
"group": cs.col(g, df[g].astype(str).to_numpy()[chart_rows], levels=levels)})],
})
Larger groups have too many arrangements to count, so a Monte Carlo version samples them.
When does the formula break?
ExploreThe normal approximation to a binomial test is the classic case. Change and the null proportion, and compare the exact p with the two approximations. Look for the rare-event settings.
EExplorable · Exact test or normal approximation?
When can you trust the normal approximation to a binomial test?
What is the exact two-sided p-value here?
Colored bars count toward the exact two-sided p: every outcome no more likely than the one you saw. The curve is the normal approximation.
Commit your prediction above to see the result
Make your prediction to see the result.
Approximations are good in the middle and poor near boundaries: small counts, rare events, many ties. Sample size alone isn't the test. What matters is how much information sits in the tail you are reading.
Will they agree on ToothGrowth?
PredictPredict first
Sixty animals, no dramatic outliers. The Welch t test gives p = .061. How close will a Monte Carlo permutation test and an asymptotic Mann–Whitney test come?
Reveal
Within .01: permutation gives p = .066 and Mann–Whitney gives p = .064. With a moderate sample and a well-behaved outcome, the calibration rarely changes the conclusion. Mann–Whitney tests something different from the mean, though, so treat its agreement as support, not as the same answer.
What the bootstrap adds
ReadThe bootstrap's main job is intervals, for statistics that have no handy formula. For the difference in medians it gives an interval of 0.598 to 10.5 around 6.20.
Permutation and bootstrap differ in the question. Permutation builds the world where the null is true, which makes it a test. Bootstrap imitates sampling from the world that produced your data, which makes it a measure of uncertainty.
Check your understanding
CheckpointCheck yourself
You have 3 events in 40 trials and want a p-value for a proportion. Which calibration should you reach for?
Show the answer
Answer: a
Three events is the size of information that matters here. " above 30" isn't protection when the event is rare.
Check yourself
Which situation breaks the logic of a simple label shuffle between two groups?
Show the answer
Answer: c
Shuffling assumes units are exchangeable under the null. Here the classroom is the unit, so you must shuffle classrooms rather than students.
Check yourself
Two groups of 3 observations each. How many ways can the 6 observations be split into two labeled groups of 3?
Show the answer
Answer: 20
. The smallest possible two-sided exact p is therefore 2/20, which is why tiny samples can't reach .05.
Choose it in CodeSplash
In the appMany methods let you pick the calibration. Open the permutation test and try it on your own groups. The same seed gives the same p in Python and R, because both draw from one shared random generator.
Recap
Recap- Exact counts, asymptotic uses a formula, permutation shuffles, and bootstrap resamples.
- Formulas fail in the tails: rare events, small counts, ties.
- Use permutation to test and bootstrap to measure uncertainty, and respect the design when you shuffle.
Concepts in this lesson