Skip to content

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.

Applied ~8 min8 steps

What runs in CodeSplash

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

01

Same seed, different numbers

Read

Set a seed of 1 in each language and draw three normal values.

Python
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.5282
R
set.seed(1)
rnorm(3)
# -0.6265, 0.1836, -0.8356

Three different answers. Two of them are in the same language.

02

Why not the same?

Predict

Predict first

Why do these differ?

One is less randomGenerators and conversions differA seed doesn't work across machines
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.

03

What the engines do

Explore

Parity on a simulation would be impossible with those generators. So every random method in CodeSplash draws from one small generator, Wichmann–Hill, written identically in both languages.

Run these and compare: the draws match to every digit.

Python
from codesplash.stats.rng import Rng

Rng(1).uniform(3)
# 0.8598604, 0.1131918, 0.3054099

Rng(1).normal(3)
# 1.079692, -1.209727, -0.508904
R
library(codesplashr)

cs_runif(cs_rng(1), 3)
# 0.8598604, 0.1131918, 0.3054099

cs_rnorm(cs_rng(1), 3)
# 1.079692, -1.209727, -0.508904

Integers differ by one, and only because Python counts from 0 and R from 1.

04

See it on a result

In the app

Here'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 testRecorded · Python and R agreeRecorded 2026-11-25 · 13 values compared
R

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

len by suppHow do groups compare in shape, summary and individual observations at once?
View data
supplen
VC4.200
VC11.500
VC7.300
VC5.800
VC6.400
VC10
VC11.200
VC11.200
VC5.200
VC7
VC16.500
VC16.500
VC15.200
VC17.300
VC22.500
VC17.300
VC13.600
VC14.500
VC18.800
VC15.500
VC23.600
VC18.500
VC33.900
VC25.500
VC26.400
VC32.500
VC26.700
VC21.500
VC23.300
VC29.500
OJ15.200
OJ21.500
OJ17.600
OJ9.700
OJ14.500
OJ10
OJ8.200
OJ9.400
OJ16.500
OJ9.700
OJ19.700
OJ23.300
OJ23.600
OJ26.400
OJ20
OJ25.200
OJ25.800
OJ21.200
OJ14.500
OJ27.300
OJ25.500
OJ26.400
OJ22.400
OJ24.500
OJ24.800
OJ30.900
OJ26.400
OJ27.300
OJ29.400
OJ23

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))))
))
Python

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.

05

What a seed doesn't promise

Explore

A 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 p≈0.05p \approx 0.05, that's about half a percentage point.

06

Check your understanding

Checkpoint

Check 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 p(1−p)/B\sqrt{p(1-p)/B}. For p=0.05p = 0.05 and B=2000B = 2000, what is it? Give four decimals.

Show the answer

Answer: 0.0049

0.05×0.95/2000=0.00002375≈0.0049\sqrt{0.05 \times 0.95 / 2000} = \sqrt{0.00002375} \approx 0.0049, about half a percentage point.

07

Your own seeds

Reflect

Which 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.

08

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