Skip to main content

The Folk Theorem of Statistical Computing

Building and checking models
Principle or heuristic
Advanced
When you have computational problems, often there’s a problem with your model.
Published

November 9, 2026

Modified

November 13, 2026

Entry #5 in Andrew Gelman’s Handy Statistical Lexicon. Original discussion: The folk theorem of statistical computing.

Filed under Building and checking models · Principle or heuristic · Advanced.

Related terms: MCMC convergence, R-hat, non-identifiability, reparameterization.

Source check: ✓ The explanation was checked against the source.

What it is

When a sampler won’t converge, an optimizer runs off to infinity, or a fit takes hours, the instinct is to blame the algorithm. The folk theorem says to look at the model first. Computational trouble is often a symptom of a model that is poorly identified, badly parameterized, or inconsistent with the data.

Gelman says he “mentioned this in class all the time”. His post links a 2004 paper on parameterization that makes a related point: “Progress in statistical computation often leads to advances in statistical modeling.” A reparameterization introduced only to help the computation often suggests a new family of models, and in a Bayesian framework a new family of prior distributions.

Why it matters

People spend days tuning step sizes, adding iterations, or switching software when the real fix is a prior that rules out absurd values, a reparameterization, or dropping a redundant parameter. Worse, if you force the computation to “succeed” without fixing the model, the answer you get may be meaningless.

How it works

Common patterns:

  • Non-identification. Two parameters enter the likelihood only through their sum, so the posterior is a long ridge. Samplers wander along it forever.
  • Flat priors on scale parameters in hierarchical models create funnels that samplers cannot explore.
  • Separation in logistic regression sends coefficients to infinity.
  • Model–data conflict, such as a misspecified likelihood, produces multimodal or extremely skewed posteriors.

In each case, the fix is in the model: add weakly informative priors, rescale, reparameterize, or simplify.

Simulated example

The data are \(y_i \sim \mathrm{N}(a + b, 1)\), so only \(a + b\) is identified. Two Metropolis chains sample \((a, b)\) under independent \(\mathrm{N}(0, \tau)\) priors. With a huge \(\tau\) (a nearly flat prior), the chains drift without settling. Shrink \(\tau\) to a weakly informative value and the same algorithm works.

Show simulation code

The R version uses base R, and the Python version uses NumPy and Matplotlib. Where the simulation draws random numbers, each language draws its own, so exact numbers differ slightly but show the same pattern. The numbered markers in the R code are explained under it.

import {rng, range, mean, fmt} from "../js/stats.js"

viewof logTau = Inputs.range([0, 4], {value: 3.5, step: 0.25, label: "log10 prior sd τ"})
viewof iters = Inputs.range([500, 5000], {value: 3000, step: 250, label: "Iterations per chain"})
viewof seed = Inputs.range([1, 500], {value: 21, step: 1, label: "Random seed"})

chains = {
  const r = rng(seed);
  const y = r.normals(50, 1.5, 1), ybar = mean(y), n = y.length;
  const tau = 10 ** logTau;
  const logPost = (a, b) => -0.5 * n * (ybar - a - b) ** 2 - 0.5 * (a * a + b * b) / (tau * tau);
  const run = (a, b, chain) => {
    const out = [];
    let lp = logPost(a, b);
    for (let t = 0; t < iters; t++) {
      const a2 = a + r.normal(0, 0.3), b2 = b + r.normal(0, 0.3);
      const lp2 = logPost(a2, b2);
      if (Math.log(r()) < lp2 - lp) { a = a2; b = b2; lp = lp2; }
      out.push({t, a, chain});
    }
    return out;
  };
  return [...run(-5, 5, "Chain 1"), ...run(5, -5, "Chain 2")];
}

Plot.plot({
  ariaLabel: "The Folk Theorem of Statistical Computing: simulation chart",
  ariaDescription: "Horizontal axis: Iteration. Vertical axis: Draws of a. The chart updates with the controls above it, and the summary below the charts states the result in words.",
  height: 300,
  x: {label: "Iteration"},
  y: {label: "Draws of a", grid: true},
  color: {legend: true, range: ["#2166ac", "#d6604d"]},
  marks: [Plot.line(chains, {x: "t", y: "a", stroke: "chain", strokeWidth: 0.8})]
})
# The Folk Theorem: computational trouble often means a model problem.
1log_tau <- 3.5 # log10 of the prior sd; large means nearly unidentified
iters <- 3000 # iterations per chain
2set.seed(21)

y <- rnorm(50, 1.5, 1)
ybar <- mean(y)
n <- 50
tau <- 10^log_tau
# y depends on a + b only, so a and b are identified only by the prior
3log_post <- function(a, b) {
  -0.5 * n * (ybar - a - b)^2 -
    0.5 * (a^2 + b^2) / tau^2
}
4run <- function(a, b) { # random-walk Metropolis
  out <- numeric(iters)
  lp <- log_post(a, b)
  for (t in 1:iters) {
    a2 <- a + rnorm(1, 0, 0.3)
    b2 <- b + rnorm(1, 0, 0.3)
    lp2 <- log_post(a2, b2)
    if (log(runif(1)) < lp2 - lp) {
      a <- a2
      b <- b2
      lp <- lp2
    }
    out[t] <- a
  }
  out
}
c1 <- run(-5, 5)
c2 <- run(5, -5)
h <- (iters / 2 + 1):iters # second halves
m <- length(h)
W <- (var(c1[h]) + var(c2[h])) / 2
B <- m * (mean(c1[h]) - mean(c2[h]))^2 / 2
5rhat <- sqrt(((m - 1) / m * W + B / m) / W)

cat("R-hat for a:", round(rhat, 2), "(well above 1.01: chains disagree)\n")
cat("Try log_tau <- 0: a weakly informative prior fixes the computation.\n")

6matplot(1:iters, cbind(c1, c2),
  type = "l", lty = 1,
  col = c("#2166ac", "#d6604d"), xlab = "Iteration",
  ylab = "Parameter a"
)
1
The page’s controls: the prior standard deviation (as a power of ten) and the number of iterations per chain.
2
Fixes the random numbers so the run is reproducible.
3
The log posterior. The data see only a + b, so with a nearly flat prior the posterior is a long ridge.
4
A random-walk Metropolis sampler, started from a given point.
5
R-hat from the second halves of the two chains. Values well above 1.01 mean the chains disagree.
6
The two chains’ draws of a. When the computation struggles, the problem is the model: a and b are not identified.
# The Folk Theorem: computational trouble often means a model problem.
import numpy as np
import matplotlib.pyplot as plt

log_tau = 3.5  # log10 of the prior sd; large means nearly unidentified
iters = 3000   # iterations per chain
rng = np.random.default_rng(21)

y = rng.normal(1.5, 1, 50)
ybar, n = y.mean(), 50
tau = 10 ** log_tau


def log_post(a, b):
    """y depends on a + b only: a and b are identified only by the prior."""
    return -0.5 * n * (ybar - a - b) ** 2 - 0.5 * (a * a + b * b) / tau ** 2


def run(a, b):  # random-walk Metropolis
    out, lp = np.empty(iters), log_post(a, b)
    for t in range(iters):
        a2, b2 = a + rng.normal(0, 0.3), b + rng.normal(0, 0.3)
        lp2 = log_post(a2, b2)
        if np.log(rng.uniform()) < lp2 - lp:
            a, b, lp = a2, b2, lp2
        out[t] = a
    return out


c1, c2 = run(-5, 5), run(5, -5)
h1, h2 = c1[iters // 2:], c2[iters // 2:]  # second halves
m = len(h1)
W = (h1.var(ddof=1) + h2.var(ddof=1)) / 2
B = m * (h1.mean() - h2.mean()) ** 2 / 2
rhat = np.sqrt(((m - 1) / m * W + B / m) / W)
print(f"R-hat for a: {rhat:.2f} (well above 1.01: chains disagree)")
print("Try log_tau = 0: a weakly informative prior fixes the computation.")

plt.plot(c1, color="#2166ac", linewidth=0.8, label="Chain 1")
plt.plot(c2, color="#d6604d", linewidth=0.8, label="Chain 2")
plt.xlabel("Iteration")
plt.ylabel("Parameter a")
plt.legend()
plt.show()

Key takeaways

  • Treat convergence failures as diagnostic information about your model, not just as an engineering annoyance.
  • Weakly informative priors, rescaling and reparameterizing often fix “computational” problems.
  • If brute force makes the problem go away, ask whether the answer means anything.

Source

Back to top