Seeds and shared random streams
The same seed gives different numbers in Python and R. See why, what the app does about it, and what a seed does and doesn't promise.
What runs in CodeSplash
- Permutation test (two independent groups) Verified in Python and R
- Bootstrap confidence interval Verified in Python and R
You will be able to
- Explain why set.seed(1) and a numpy seed of 1 produce different numbers
- Use the shared random stream to reproduce a draw in both languages
- Say why a result that needs one lucky seed isn't a stable result
Read first
Same seed, different numbers
ReadSet a seed of 1 in each language and draw three normal values.
import numpy as np
np.random.default_rng(1).normal(size=3)
# 0.3456, 0.8216, 0.3304
np.random.RandomState(1).normal(size=3)
# 1.6243, -0.6118, -0.5282set.seed(1)
rnorm(3)
# -0.6265, 0.1836, -0.8356Three different answers. Two of them are in the same language.
Why not the same?
PredictPredict first
Why do these differ?
Reveal
A seed only picks a starting point. numpy's default_rng uses a different generator (PCG64) from R's default (Mersenne Twister). RandomState does use Mersenne Twister, but it's seeded differently and turns uniform draws into normals differently. None is more random. Each is reproducible within its own language.
See it on a result
In the appHere's a permutation test. In 1,999 shuffles of the labels, 130 gave a difference at least as large as the one observed. Press Verify on the result, and the other engine counts exactly the same shuffles.
permutation test, Δ = 3.70, p = .066
- Mean difference (OJ − VC)
- 3.700
- p
- .066
- Permutations
- 1,999
Effect size
- Cohen's d 0.4945
Plots
View data
| supp | len |
|---|---|
| VC | 4.200 |
| VC | 11.500 |
| VC | 7.300 |
| VC | 5.800 |
| VC | 6.400 |
| VC | 10 |
| VC | 11.200 |
| VC | 11.200 |
| VC | 5.200 |
| VC | 7 |
| VC | 16.500 |
| VC | 16.500 |
| VC | 15.200 |
| VC | 17.300 |
| VC | 22.500 |
| VC | 17.300 |
| VC | 13.600 |
| VC | 14.500 |
| VC | 18.800 |
| VC | 15.500 |
| VC | 23.600 |
| VC | 18.500 |
| VC | 33.900 |
| VC | 25.500 |
| VC | 26.400 |
| VC | 32.500 |
| VC | 26.700 |
| VC | 21.500 |
| VC | 23.300 |
| VC | 29.500 |
| OJ | 15.200 |
| OJ | 21.500 |
| OJ | 17.600 |
| OJ | 9.700 |
| OJ | 14.500 |
| OJ | 10 |
| OJ | 8.200 |
| OJ | 9.400 |
| OJ | 16.500 |
| OJ | 9.700 |
| OJ | 19.700 |
| OJ | 23.300 |
| OJ | 23.600 |
| OJ | 26.400 |
| OJ | 20 |
| OJ | 25.200 |
| OJ | 25.800 |
| OJ | 21.200 |
| OJ | 14.500 |
| OJ | 27.300 |
| OJ | 25.500 |
| OJ | 26.400 |
| OJ | 22.400 |
| OJ | 24.500 |
| OJ | 24.800 |
| OJ | 30.900 |
| OJ | 26.400 |
| OJ | 27.300 |
| OJ | 29.400 |
| OJ | 23 |
Assumptions
- Exchangeability — Variance ratio 1.57.
- Difference = OJ − VC; 1999 Monte Carlo permutations, seed 42; alternative: two-sided. p = (count + 1) / (permutations + 1).
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 6a63b6b68eef47d9
# Dataset: toothgrowth (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/toothgrowth.parquet", col_select = c("len", "supp")))
n_input <- nrow(df)
df[["supp"]] <- factor(df[["supp"]], levels = c("OJ", "VC")) # stored level order
df <- df[stats::complete.cases(df[c("len", "supp")]), , 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("len", "supp")) # infinite values stop the run (registry/errors.yaml)
# %% Two samples (independent groups or paired measurements, from the bound roles)
y <- "len"
g <- "supp"
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 = 1999, 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, Δ = 3.70, p = .066
- Mean difference (OJ − VC)
- 3.700
- p
- .066
- Permutations
- 1,999
Effect size
- Cohen's d 0.4945
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Exchangeability — Variance ratio 1.57.
- Difference = OJ − VC; 1999 Monte Carlo permutations, seed 42; alternative: two-sided. p = (count + 1) / (permutations + 1).
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 6a63b6b68eef47d9
# Dataset: toothgrowth (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/toothgrowth.parquet", columns=["len", "supp"])
n_input = len(df)
df["supp"] = pd.Categorical(df["supp"], categories=["OJ", "VC"]) # stored level order
df = df.dropna(subset=["len", "supp"]) # listwise deletion over the analysis columns
df["supp"] = df["supp"].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, ["len", "supp"]) # infinite values stop the run (registry/errors.yaml)
# %% Two samples (independent groups or paired measurements, from the bound roles)
y = "len"
g = "supp"
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(1999), 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)})],
})
The Seed option is under Reproducibility in the setup. Change it, and the count moves a little. That's the Monte Carlo error.
What a seed doesn't promise
ExploreA seed makes a run reproducible. It doesn't make it right.
Try this: in the example above, change the seed three times, and note the p-value each time. If a result would cross your threshold with one seed and not another, the result isn't stable, and a more convenient seed won't fix it. Increase the number of shuffles until the p-value settles.
A Monte Carlo p-valueMonte Carlo p-valueA p-value estimated from simulated or resampled statistics, with its own small sampling error. has its own standard error. With 2,000 shuffles and , that's about half a percentage point.
Check your understanding
CheckpointCheck yourself
Your colleague runs your R script with set.seed(42), translated to Python with np.random.seed(42). What should they expect?
Show the answer
Answer: b
The generators and conversion methods differ. To match across languages you need a shared generator; otherwise compare the conclusions with their Monte Carlo error.
Check yourself
With seed 1 your bootstrap interval excludes zero, and with seed 2 it doesn't. What's the honest response?
Show the answer
Answer: c
Trying seeds until one looks good is a forking path. If the seed changes your conclusion, you need more resamples, or you need to accept the result is on the edge.
Check yourself
The standard error of a Monte Carlo p-value is . For and , what is it? Give four decimals.
Show the answer
Answer: 0.0049
, about half a percentage point.
Your own seeds
ReflectWhich of your analyses uses randomness: a bootstrap, a split, a simulation? If you reran it with a different seed, would you say the same thing? If you aren't sure, you've found your next check.
Recap
Recap- A seed picks a starting point in one generator; different generators give different numbers.
- CodeSplash's random methods share one generator, so Python and R draw identical numbers.
- A seed gives you reproducibility. Stability comes from enough draws.
Concepts in this lesson