Skip to content

The binomial distribution

Count successes in a fixed number of independent tries. Check the conditions, compute by hand, and test a proportion in the app.

Introductory ~10 min8 steps

What runs in CodeSplash

You will be able to

  • State the four conditions of a binomial count
  • Compute binomial probabilities, the mean and the standard deviation
  • Test a proportion with an exact binomial test

Read first

01

Counting successes

Read

The binomial distributionBinomial distributionThe count of successes in n independent tries that each have the same chance p of success. counts successes when four things are true:

  • a fixed number of tries, nn
  • two outcomes per try
  • the same chance of success, pp, each time
  • tries that don't affect each other

Its probabilities come from counting arrangements:

Pr⁡(X=k)=(nk)pk(1−p)n−k,E[X]=np,Var⁡(X)=np(1−p)\Pr(X = k) = \binom{n}{k} p^k (1 - p)^{n - k}, \qquad E[X] = np, \qquad \operatorname{Var}(X) = np(1 - p)
02

How often exactly half?

Predict

Predict first

You flip a fair coin 10 times. How likely is it that you get exactly 5 heads?

About 25%About 50%About 75%
Reveal

About 25%: (105)/210=252/1024≈0.246\binom{10}{5} / 2^{10} = 252 / 1024 \approx 0.246. The most likely single count is still unlikely. That's why you ask about ranges of counts.

03

See the shape

Explore

Here Parameter 1 is nn, and Parameter 2 sets pp through p=b/(b+1)p = b / (b + 1). Raise nn and watch the bars approach a bell shape. Lower pp and they pile up against zero.

AExplorable · The distribution zoo

What do the common distributions look like, and when is a normal approximation good enough?

Which is larger for this distribution: the mean or the median?

How sure?

Family

10.0

μ, df, shape, α, meanlog, min, n or λ depending on the family.

1.0

σ, rate, scale, β, sdlog or width; for the binomial p = b/(b + 1).

Solid: the distribution. Dashed: a normal with the same mean and SD.

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.

04

Exact, or the normal shortcut?

Explore

The normal curve approximates the binomial when npnp and n(1−p)n(1 - p) are both large. Guess the exact p-value, then find a count where the two methods disagree about 0.05.

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?

0.50
How sure?
20
0.10
5

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 first; the figure appears when you commit.

Make your prediction to see the result.

05

Test a proportion

Read

Is 13 of 32 cars with manual gearboxes compatible with a true share of a half? The observed share is 40.6%. The exact test gives p = .377, and the 95% interval runs from 25.5% to 57.7%.

So a half is compatible with these data, along with a wide range of other shares.

One proportion: exact binomial testRecorded · Python and R agreeRecorded 2026-11-21 · 14 values compared
R

13/32 = .41, 95% CI [.26, .58], exact binomial test p = .377

Proportion true
0.4063
95% CI (Wilson score)
[0.2552, 0.5774]
p (exact binomial test)
.377
z (score)
−1.061
p (exact)
.377
p (score)
.289

Effect size

  • Cohen's h −0.1886 · negligible

Plots

Proportion trueHow large are several estimates, how precise, and which exclude the null?

Wilson score interval; the line marks p0 = 0.5.

View data
Proportion truehighmanuallow
0.40630.5774true0.2552

Assumptions

  • Independent trials — Each row is one independent trial with the same probability.
  • Large enough for the score test — The exact test needs no normal approximation.

Counts

manualnShare
false190.5938
true130.4063
  • Event: manual = true (all other levels count as non-events); H0 proportion 0.5; alternative: two-sided.
The exact R script · R R version 4.5.1 (2025-06-13)
# One proportion (exact binomial / score test)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method proportion.binomial 1.2.0 · spec b4abe3ecd1bd6f47
# Dataset: mtcars (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_prop_ci, cs_score_test (twins of codesplash.stats.proportions)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/mtcars.parquet", col_select = c("manual")))
n_input <- nrow(df)
df[["manual"]] <- factor(df[["manual"]], levels = c("false", "true"))  # stored level order
df <- df[stats::complete.cases(df[c("manual")]), , 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("manual"))  # infinite values stop the run (registry/errors.yaml)

# %% Helpers
magnitude <- function(x, cuts, labels = c("negligible", "small", "medium", "large")) {
  # Benchmark label for an effect size (rule set named in the result)
  if (is.null(x) || !is.finite(x)) return("undetermined")
  labels[findInterval(abs(x), cuts) + 1]
}

# %% Test
v <- "manual"
levels_v <- c("false", "true")  # stored level order
event <- ""
if (!nzchar(event)) event <- levels_v[length(levels_v)]  # default: the last level (for true/false columns, "true")
if (!event %in% levels_v) stop(sprintf("'%s' is not a level of %s: %s", event, v, paste(levels_v, collapse = ", ")))
x <- as.character(df[[v]])
k <- sum(x == event)
n <- length(x)
p0 <- 0.5
alternative <- "two-sided"
conf <- 0.95
test <- "exact"  # "exact" binomial or "score" z
ci_method <- "wilson"

p_exact <- binom.test(k, n, p = p0, alternative = sub("-", ".", alternative, fixed = TRUE))$p.value  # exact binomial test
sc <- cs_score_test(k, n, p0, alternative)  # score z (= prop.test(correct = FALSE))
z <- sc[1]
p_score <- sc[2]
p <- if (test == "exact") p_exact else p_score
ci <- cs_prop_ci(k, n, conf, ci_method)
phat <- k / n
h <- 2 * asin(sqrt(phat)) - 2 * asin(sqrt(p0))  # Cohen's h
test_label <- if (test == "exact") "exact binomial test" else "score z test"
# Optional calibrations (Stage 12.7; the defaults leave everything above unchanged)
extra <- list()
if (FALSE) {
  extra$p_midp <- cs_binom_midp(k, n, p0, alternative)
  if (test == "exact") {
    p <- extra$p_midp
    test_label <- "exact binomial test (mid-p)"
  }
}
if (FALSE) {
  scc <- cs_score_test_cc(k, n, p0, alternative)
  extra$z_cc <- unname(scc[["z"]])
  extra$p_score_cc <- unname(scc[["p"]])
  if (test == "score") {
    p <- extra$p_score_cc
    test_label <- "score z test with continuity correction"
  }
}
ci_label <- c(wilson = "Wilson score", "wilson-cc" = "Wilson score with continuity correction", "clopper-pearson" = "Clopper–Pearson (exact)",
              jeffreys = "Jeffreys", "agresti-coull" = "Agresti–Coull", wald = "Wald")[[ci_method]]

# %% Assumptions
small <- min(n * p0, n * (1 - p0))
assumptions <- list(list(key = "independence", label = "Independent trials", status = "info", detail = "Each row is one independent trial with the same probability."))
assumptions[[2]] <- if (test == "score") {
  list(key = "sample_size", label = "Large enough for the score test", status = if (small >= 5) "pass" else "warn",
       detail = sprintf("min(n·p0, n·(1 − p0)) = %.1f%s", small, if (small < 5) " (< 5): use the exact test." else "."))
} else {
  list(key = "sample_size", label = "Large enough for the score test", status = "info", detail = "The exact test needs no normal approximation.")
}

# %% Result
alpha <- 1 - conf
pct <- sprintf("%.0f%%", conf * 100)
size <- magnitude(h, c(0.2, 0.5, 0.8))
significance <- if (p < alpha) {
  sprintf("The proportion differs significantly from %s (%s).", format(p0), cs_fmt_p(p))
} else {
  sprintf("The data are compatible with a proportion of %s (%s).", format(p0), cs_fmt_p(p))
}
summary <- sprintf("%d of %d rows (%.1f%%) have %s = %s; %s CI [%.1f%%, %.1f%%] (%s). %s Cohen's h = %.2f (%s).",
                   k, n, phat * 100, v, event, pct, ci[1] * 100, ci[2] * 100, ci_label, significance, h, size)
cs_publish(list(
  method = "proportion.binomial",
  methodVersion = "1.2.0",
  title = paste("One proportion:", test_label),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("%d/%d = %s, %s CI [%s, %s], %s %s", k, n, cs_fmt_num(phat, leading_zero = FALSE), pct,
                cs_fmt_num(ci[1], leading_zero = FALSE), cs_fmt_num(ci[2], leading_zero = FALSE), test_label, cs_fmt_p(p)),
  statistics = list(
    list(key = "proportion", label = paste("Proportion", event), value = phat),
    list(key = "ci", label = sprintf("%s CI (%s)", pct, ci_label), value = c(ci[1], ci[2])),
    list(key = "p", label = sprintf("p (%s)", test_label), value = p, format = "p"),
    list(key = "z", label = "z (score)", value = z),
    list(key = "p_exact", label = "p (exact)", value = p_exact, format = "p"),
    list(key = "p_score", label = "p (score)", value = p_score, format = "p")
  ),
  tables = list(list(
    key = "counts", title = "Counts",
    columns = list(list(key = "level", label = v, type = "string"), list(key = "n", label = "n", type = "integer"),
                   list(key = "share", label = "Share", type = "number")),
    rows = data.frame(level = levels_v, n = vapply(levels_v, function(lv) sum(x == lv), numeric(1)),
                      share = vapply(levels_v, function(lv) mean(x == lv), numeric(1)), row.names = NULL)
  )),
  effectSizes = list(list(key = "cohens_h", label = "Cohen's h", value = h, method = "2·asin√p̂ − 2·asin√p0", magnitude = size, ruleSet = "Cohen (1988)")),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Event: %s = %s (all other levels count as non-events); H0 proportion %s; alternative: %s.", v, event, format(p0), alternative)),
  charts = list(cs_chart(
    "proportion", "forest", paste("Proportion", event),
    list(label = cs_col(v, event), estimate = cs_col(paste("Proportion", event), phat),
         low = cs_col("low", ci[1]), high = cs_col("high", ci[2])),
    controls = list(reference = p0), note = sprintf("%s interval; the line marks p0 = %s.", ci_label, format(p0))
  )),
  values = c(list(k = k, n = n, proportion = phat, p = p, ci_low = ci[1], ci_high = ci[2], cohens_h = h, p0 = p0,
                z = z, p_exact = p_exact, p_score = p_score, event = event, test_label = test_label, ci_label = ci_label), extra)
))
Python

13/32 = .41, 95% CI [.26, .58], exact binomial test p = .377

Proportion true
0.4063
95% CI (Wilson score)
[0.2552, 0.5774]
p (exact binomial test)
.377
z (score)
−1.061
p (exact)
.377
p (score)
.289

Effect size

  • Cohen's h −0.1886 · negligible

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

Assumptions

  • Independent trials — Each row is one independent trial with the same probability.
  • Large enough for the score test — The exact test needs no normal approximation.

Counts

manualnShare
false190.5938
true130.4063
  • Event: manual = true (all other levels count as non-events); H0 proportion 0.5; alternative: two-sided.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# One proportion (exact binomial / score test)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method proportion.binomial 1.2.0 · spec b4abe3ecd1bd6f47
# Dataset: mtcars (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
from scipy import stats

import codesplash as cs
from codesplash.stats import proportions as csp  # intervals and the score test (twins of codesplashr)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/mtcars.parquet", columns=["manual"])
n_input = len(df)
df["manual"] = pd.Categorical(df["manual"], categories=["false", "true"])  # stored level order
df = df.dropna(subset=["manual"])  # listwise deletion over the analysis columns
df["manual"] = df["manual"].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, ["manual"])  # infinite values stop the run (registry/errors.yaml)

# %% Helpers
def magnitude(x, cuts, labels=("negligible", "small", "medium", "large")):
    """Benchmark label for an effect size (rule set named in the result)."""
    if x is None or not np.isfinite(x):
        return "undetermined"
    for cut, label in zip(cuts, labels):
        if abs(x) < cut:
            return label
    return labels[-1]

# %% Test
v = "manual"
levels = ["false", "true"]  # stored level order
event = "" or levels[-1]  # default: the last level (for true/false columns, "true")
if event not in levels:
    raise ValueError(f"{event!r} is not a level of {v}: {', '.join(levels)}")
k = int((df[v].astype(str) == event).sum())
n = len(df)
p0 = 0.5
alternative = "two-sided"
conf = 0.95
test = "exact"  # "exact" binomial or "score" z
ci_method = "wilson"

p_exact = float(stats.binomtest(k, n, p=p0, alternative=alternative).pvalue)  # exact binomial test
z, p_score = csp.score_test(k, n, p0, alternative)  # score z (= prop.test(correct = FALSE))
p = p_exact if test == "exact" else p_score
ci_low, ci_high = csp.prop_ci(k, n, conf, ci_method)
phat = k / n
h = 2 * np.arcsin(np.sqrt(phat)) - 2 * np.arcsin(np.sqrt(p0))  # Cohen's h
test_label = "exact binomial test" if test == "exact" else "score z test"
# Optional calibrations (Stage 12.7; the defaults leave everything above unchanged)
from codesplash.stats import stat_options as csopt
extra = {}
if False:
    extra["p_midp"] = csopt.binom_midp(k, n, p0, alternative)
    if test == "exact":
        p = extra["p_midp"]
        test_label = "exact binomial test (mid-p)"
if False:
    extra["z_cc"], extra["p_score_cc"] = csopt.score_test_cc(k, n, p0, alternative)
    if test == "score":
        p = extra["p_score_cc"]
        test_label = "score z test with continuity correction"
ci_label = csp.CI_LABELS[ci_method]

# %% Assumptions
small = min(n * p0, n * (1 - p0))
assumptions = [{"key": "independence", "label": "Independent trials", "status": "info", "detail": "Each row is one independent trial with the same probability."}]
if test == "score":
    assumptions.append({"key": "sample_size", "label": "Large enough for the score test", "status": "pass" if small >= 5 else "warn",
                        "detail": f"min(n·p0, n·(1 − p0)) = {small:.1f}" + (" (< 5): use the exact test." if small < 5 else ".")})
else:
    assumptions.append({"key": "sample_size", "label": "Large enough for the score test", "status": "info", "detail": "The exact test needs no normal approximation."})

# %% Result
alpha = 1 - conf
size = magnitude(h, (0.2, 0.5, 0.8))
significance = (
    f"The proportion differs significantly from {p0:g} ({cs.fmt_p(p)})." if p < alpha
    else f"The data are compatible with a proportion of {p0:g} ({cs.fmt_p(p)})."
)
summary = f"{k} of {n} rows ({phat:.1%}) have {v} = {event}; {conf:.0%} CI [{ci_low:.1%}, {ci_high:.1%}] ({ci_label}). {significance} Cohen's h = {h:.2f} ({size})."
cs.publish({
    "method": "proportion.binomial",
    "methodVersion": "1.2.0",
    "title": "One proportion: " + test_label,
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"{k}/{n} = {cs.fmt_num(phat, leading_zero=False)}, {conf:.0%} CI [{cs.fmt_num(ci_low, leading_zero=False)}, {cs.fmt_num(ci_high, leading_zero=False)}], {test_label} {cs.fmt_p(p)}",
    "statistics": [
        {"key": "proportion", "label": f"Proportion {event}", "value": phat},
        {"key": "ci", "label": f"{conf:.0%} CI ({ci_label})", "value": [ci_low, ci_high]},
        {"key": "p", "label": f"p ({test_label})", "value": p, "format": "p"},
        {"key": "z", "label": "z (score)", "value": z},
        {"key": "p_exact", "label": "p (exact)", "value": p_exact, "format": "p"},
        {"key": "p_score", "label": "p (score)", "value": p_score, "format": "p"},
    ],
    "tables": [{
        "key": "counts", "title": "Counts",
        "columns": [{"key": "level", "label": v, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
                    {"key": "share", "label": "Share", "type": "number"}],
        "rows": [{"level": lv, "n": int((df[v].astype(str) == lv).sum()), "share": float((df[v].astype(str) == lv).mean())} for lv in levels],
    }],
    "effectSizes": [{"key": "cohens_h", "label": "Cohen's h", "value": float(h), "method": "2·asin√p̂ − 2·asin√p0", "magnitude": size, "ruleSet": "Cohen (1988)"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Event: {v} = {event} (all other levels count as non-events); H0 proportion {p0:g}; alternative: {alternative}."],
    "charts": [cs.chart(
        "proportion", "forest", f"Proportion {event}",
        {"label": cs.col(v, [event]), "estimate": cs.col(f"Proportion {event}", [phat]),
         "low": cs.col("low", [ci_low]), "high": cs.col("high", [ci_high])},
        controls={"reference": p0}, note=f"{ci_label} interval; the line marks p0 = {p0:g}.",
    )],
    "values": {"k": k, "n": n, "proportion": phat, "p": p, "ci_low": ci_low, "ci_high": ci_high, "cohens_h": float(h), "p0": p0,
               "z": z, "p_exact": p_exact, "p_score": p_score, "event": event, "test_label": test_label, "ci_label": ci_label, **extra},
})
06

Check your reading

Checkpoint

Check yourself

With n=3n = 3 and p=0.5p = 0.5, what is the probability of exactly 2 successes?

Show the answer

Answer: 0.375

(32)×0.53=3/8=0.375\binom{3}{2} \times 0.5^3 = 3/8 = 0.375.

Check yourself

A defect appears in 10% of parts, and you inspect 20. What is the expected number of defects?

Show the answer

Answer: 2

np=20×0.1=2np = 20 \times 0.1 = 2.

Check yourself

You count how many of 30 patients in one household-based study caught a virus. Which binomial condition is most in doubt?

Show the answer

Answer: c

People in one household can infect each other, so the outcomes aren't independent. The count will vary more than a binomial predicts.

07

Test a share in the app

In the app

In Analyze, pick the outcome, its Event level and a Reference proportion (p0). Exact is the default Test, and you can choose a score test instead.

Python
from scipy import stats

result = stats.binomtest(k=13, n=32, p=0.5)
print(result.pvalue)
print(result.proportion_ci(confidence_level=0.95, method="wilson"))
R
binom.test(x = 13, n = 32, p = 0.5)$p.value
prop.test(x = 13, n = 32, p = 0.5, correct = FALSE)$conf.int

Notebook exercise · ~8 min

Binomial probabilities in code

Compute "at most" and "at least" binomial probabilities, and catch the off-by-one that trips everyone once.

  1. At most two

    Store P(X ≤ 2), the probability that at most two of the ten are resolved on first contact, in p_at_most_2.

    Show a solution
    Python
    p_at_most_2 = stats.binom.cdf(2, n, prob)
    R
    p_at_most_2 <- pbinom(2, n, prob)
  2. At least five

    Store P(X ≥ 5), the probability that five or more are resolved on first contact, in p_at_least_5.

    Show a solution
    Python
    p_at_least_5 = stats.binom.sf(4, n, prob)
    R
    p_at_least_5 <- pbinom(4, n, prob, lower.tail = FALSE)

In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.

08

Recap

Recap
  • The binomial counts successes in nn independent tries with the same chance pp.
  • Its mean is npnp and its variance is np(1−p)np(1 - p).
  • Check independence first: clustered tries vary more than the formula says.
  • Use the exact test when counts are small, as the normal shortcut can mislead there.

Concepts in this lesson