DDecisions · bandit.simulate
Multi-armed bandit simulation
Which allocation policy earns the most (loses the least) while learning which option is best?
Simulates bandit policies — ε-greedy, decaying ε, UCB1, Thompson sampling and softmax — against a fixed A/B allocation on Bernoulli (conversion) or Gaussian arms, over many replications with common random numbers from a shared seeded stream, so every policy faces the same rewards and Python and R agree exactly. Reports cumulative regret with 10th–90th percentile bands, how often the best arm is played and how allocation shifts over time; optional delayed feedback.
A real result
Example “Conversion default”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Over 600 decisions and 40 simulated runs, Softmax (Boltzmann) lost the least to always playing the best arm (arm 3): mean cumulative regret 4.41, 80% of runs between 0.08 and 11.77; it played the best arm 50% of the time. A fixed A/B allocation lost 6.04.
- Lowest regret
- Softmax (Boltzmann)
- Mean cumulative regret
- 4.411
- Best arm played
- 50.3%
Policies (cumulative regret at the horizon)
| Policy | Mean regret | SD | 10th pct | 90th pct | Best arm share | Mean total reward |
|---|---|---|---|---|---|---|
| Fixed A/B allocation | 6.040 | 0.1997 | 5.750 | 6.291 | 32.9% | 30.175 |
| ε-greedy | 6.902 | 3.632 | 1.490 | 11.126 | 31.2% | 29.075 |
| Decaying ε-greedy | 4.588 | 3.385 | 0.7840 | 10.236 | 43.2% | 33.025 |
| UCB1 | 5.660 | 0.3693 | 5.187 | 6.075 | 36.3% | 30.750 |
| Thompson sampling | 4.538 | 1.557 | 2.760 | 6.673 | 46.5% | 32.275 |
| Softmax (Boltzmann) | 4.411 | 4.418 | 0.0770 | 11.767 | 50.3% | 31.850 |
- Arms: Arm 1 (0.04), Arm 2 (0.05), Arm 3 (0.06) (conversion); seed 42; regret = best mean − mean of the arm played, summed over decisions.
- Every policy faces the same simulated rewards in each run (common random numbers), so differences are due to the policies.
Over 600 decisions and 40 simulated runs, Softmax (Boltzmann) lost the least to always playing the best arm (arm 3): mean cumulative regret 4.41, 80% of runs between 0.08 and 11.77; it played the best arm 50% of the time. A fixed A/B allocation lost 6.04.
- Lowest regret
- Softmax (Boltzmann)
- Mean cumulative regret
- 4.411
- Best arm played
- 50.3%
Policies (cumulative regret at the horizon)
| Policy | Mean regret | SD | 10th pct | 90th pct | Best arm share | Mean total reward |
|---|---|---|---|---|---|---|
| Fixed A/B allocation | 6.040 | 0.1997 | 5.750 | 6.291 | 32.9% | 30.175 |
| ε-greedy | 6.902 | 3.632 | 1.490 | 11.126 | 31.2% | 29.075 |
| Decaying ε-greedy | 4.588 | 3.385 | 0.7840 | 10.236 | 43.2% | 33.025 |
| UCB1 | 5.660 | 0.3693 | 5.187 | 6.075 | 36.3% | 30.750 |
| Thompson sampling | 4.538 | 1.557 | 2.760 | 6.673 | 46.5% | 32.275 |
| Softmax (Boltzmann) | 4.411 | 4.418 | 0.0770 | 11.767 | 50.3% | 31.850 |
- Arms: Arm 1 (0.04), Arm 2 (0.05), Arm 3 (0.06) (conversion); seed 42; regret = best mean − mean of the arm played, summed over decisions.
- Every policy faces the same simulated rewards in each run (common random numbers), so differences are due to the policies.
Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Conversion defaultNo data needed
- Gaussian delayNo data needed
- Two arms subsetNo data needed
In the guides
Where it sits in the decision guides
- A/B testing (hypothesis testing) · DS & ML Decision Guide · Optimize / decide
- Reinforcement learning (bandits, RL) · DS & ML Decision Guide · Optimize / decide
- Optimize / decide: expected value / reward; conversion / business impact; regret, cumulative reward; constraint satisfaction · DS & ML Decision Guide · How to evaluate — common metrics by question type
- Optimize / decide: short-term vs. long-term value; exploration vs. exploitation; business constraints · DS & ML Decision Guide · Key trade-offs by question type
Choices you make
options
- Reward typedefault bernoulli
Reward type of the arms: conversions (yes/no) or continuous amounts.
- Conversion (yes/no, Bernoulli)(default) — Each arm pays 0 or 1 with its own probability; pick it for conversions or clicks.
- Continuous (Gaussian) — Each arm pays a normally distributed amount; pick it for revenue or time spent.
- True arm meansdefault 0.04,0.05,0.06
One value per arm (conversion rates for yes/no rewards). The simulation knows them; the policies must learn them.
- Reward SD (Gaussian arms)default 1
Standard deviation of rewards for Gaussian arms. Larger values make the best arm harder to identify.
- Horizon (decisions per run)default 2000
Number of decisions in each simulated run.
- Replicationsdefault 200
Independent simulated runs; bands are the 10th–90th percentiles across them.
Advanced
- Feedback delay (decisions)default 0
Rewards become visible this many decisions after the pull.
- Decay constant c (εₜ = min(1, c·K/t))default 5
How quickly decaying ε-greedy stops exploring. Larger c explores longer.
- Softmax temperature τdefault 0.01
On the reward scale: small τ is greedy, large τ explores.
statistics
- Fixed A/B allocationdefault on
Uniform random allocation for the whole horizon — the classic A/B/n test.
- ε-greedydefault on
Include ε-greedy: explore a random arm with probability ε, otherwise play the best arm so far.
- Decaying ε-greedydefault on
Include decaying ε-greedy: explores a lot at first, then less as evidence builds.
- UCB1default on
Include UCB1: plays the arm with the highest upper confidence bound.
- Thompson samplingdefault on
Include Thompson sampling: plays each arm with the probability that it is the best.
- Softmax (Boltzmann)default on
Include softmax: picks arms with probability rising with their estimated reward.
- ε (exploration rate)default 0.1
Share of decisions ε-greedy spends exploring a random arm instead of the best one so far.
What it reports
- best_policy
- Code of the policy with the smallest mean cumulative regret across the simulated runs, such as ucb1 or thompson.
- best_arm
- Allocates traffic while learning, shifting it toward what seems best to lose less during the test.
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- horizon
- How many periods ahead a forecast predicts; uncertainty grows with the horizon.
- reps
- How many samples were simulated for a p-value. More gives a steadier p-value; it does not change what is tested.
- best_policy_label
- Name of the policy with the best result in this run, as the summary names it.
- best_regret
- Reward the best policy gave up against always playing the best arm, summed over the run and averaged over replications.
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses numpy, scipy, codesplash; R uses stats, codesplashr.
Default traps between the two languages
- Thompson sampling inverts the Beta distribution (scipy betaincinv vs R qbeta) and Gaussian rewards use Φ⁻¹ (ndtri vs qnorm); they agree to ~1e-15, so a different choice would need two posterior draws closer than that.
The exact script CodeSplash ran for example “Conversion default” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Multi-armed bandit simulation
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bandit.simulate 1.0.0 · spec 6493f434cec9832a
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import codesplash as cs
from codesplash.decide import bandits # twin of codesplashr::cs_bandit_simulate (shared Wichmann–Hill stream)
# %% Inputs
arm_kind = "bernoulli" # bernoulli | gaussian
means = [float(m) for m in [0.04, 0.05, 0.06]] # true arm means (unknown to the policies)
sd = 1 # Gaussian arms only
horizon = int(600)
reps = int(40)
delay = int(0)
epsilon = 0.1
decay_c = 5
temperature = 0.01
seed = 42 # common random numbers: every policy sees the same rewards
chosen = {
"ab": True, "epsilon": True, "decaying": True,
"ucb1": True, "thompson": True, "softmax": True,
}
policies = [p for p in bandits.POLICIES if chosen[p]]
if not policies:
raise ValueError("Choose at least one policy to simulate.")
if len(means) < 2:
raise ValueError("Enter at least two arm means.")
warnings = []
# %% Simulate
sim = bandits.simulate(means, policies, horizon=horizon, reps=reps, seed=seed, arm_kind=arm_kind, sd=sd, epsilon=epsilon,
decay_c=decay_c, temperature=temperature, delay=delay)
res = sim["policies"]
k = len(means)
arm_names = [f"Arm {i + 1} ({m:g})" for i, m in enumerate(means)]
best_policy = min(policies, key=lambda p: (res[p]["regret"], policies.index(p)))
best_arm = sim["best_arm"] + 1
if sorted(means)[-1] == sorted(means)[-2]:
warnings.append("Two arms share the best mean, so regret only measures time spent on worse arms.")
# %% Result
label = bandits.LABELS
summary = (
f"Over {horizon:,} decisions and {reps} simulated runs, {label[best_policy]} lost the least to always playing the best arm "
f"(arm {best_arm}): mean cumulative regret {res[best_policy]['regret']:.2f}, 80% of runs between {res[best_policy]['regret_p10']:.2f} "
f"and {res[best_policy]['regret_p90']:.2f}; it played the best arm {res[best_policy]['best_share']:.0%} of the time."
)
if "ab" in res and best_policy != "ab":
summary += f" A fixed A/B allocation lost {res['ab']['regret']:.2f}."
rows = [
{"policy": label[p], "regret": res[p]["regret"], "sd": res[p]["regret_sd"], "p10": res[p]["regret_p10"], "p90": res[p]["regret_p90"],
"best_share": res[p]["best_share"], "reward": res[p]["reward"]}
for p in policies
]
grid = sim["grid"]
band_t, band_mean, band_low, band_high, band_policy = [], [], [], [], []
share_t, share_v, share_arm, share_policy = [], [], [], []
for p in policies:
band_t += grid.tolist()
band_mean += res[p]["curve_mean"].tolist()
band_low += res[p]["curve_low"].tolist()
band_high += res[p]["curve_high"].tolist()
band_policy += [label[p]] * len(grid)
for gi, g in enumerate(grid):
for a in range(k):
share_t.append(int(g))
share_v.append(float(res[p]["shares"][gi, a]))
share_arm.append(arm_names[a])
share_policy.append(label[p])
values = {"best_policy": best_policy, "best_policy_label": label[best_policy], "best_regret": res[best_policy]["regret"],
"best_arm": best_arm, "k": k, "horizon": horizon, "reps": reps}
for p in policies:
values[f"regret[{p}]"] = res[p]["regret"]
values[f"regret_sd[{p}]"] = res[p]["regret_sd"]
values[f"regret_p10[{p}]"] = res[p]["regret_p10"]
values[f"regret_p90[{p}]"] = res[p]["regret_p90"]
values[f"best_share[{p}]"] = res[p]["best_share"]
values[f"reward[{p}]"] = res[p]["reward"]
values[f"curve[{p}]"] = res[p]["curve_mean"].tolist()
cs.publish({
"method": "bandit.simulate",
"methodVersion": "1.0.0",
"title": "Multi-armed bandit simulation",
"engine": cs.engine_info("numpy", "scipy"),
"n": reps,
"summary": summary,
"statistics": [
{"key": "best_policy", "label": "Lowest regret", "value": label[best_policy]},
{"key": "best_regret", "label": "Mean cumulative regret", "value": res[best_policy]["regret"]},
{"key": "best_share", "label": "Best arm played", "value": res[best_policy]["best_share"], "format": "percent"},
],
"tables": [{
"key": "policies", "title": "Policies (cumulative regret at the horizon)",
"columns": [
{"key": "policy", "label": "Policy", "type": "string"}, {"key": "regret", "label": "Mean regret", "type": "number"},
{"key": "sd", "label": "SD", "type": "number"}, {"key": "p10", "label": "10th pct", "type": "number"},
{"key": "p90", "label": "90th pct", "type": "number"}, {"key": "best_share", "label": "Best arm share", "type": "percent"},
{"key": "reward", "label": "Mean total reward", "type": "number"},
],
"rows": rows,
}],
"warnings": warnings,
"notes": [
f"Arms: {', '.join(arm_names)} ({'conversion' if arm_kind == 'bernoulli' else f'Gaussian, SD {sd:g}'}); seed {seed}; "
+ (f"feedback delayed by {delay} decisions; " if delay else "")
+ "regret = best mean − mean of the arm played, summed over decisions.",
"Every policy faces the same simulated rewards in each run (common random numbers), so differences are due to the policies.",
],
"values": values,
"charts": [
cs.chart("regret", "regret-bands", "Cumulative regret (mean, 10th–90th percentile)", {
"t": cs.col("Decision", band_t), "mean": cs.col("Cumulative regret", band_mean),
"low": cs.col("10th percentile", band_low), "high": cs.col("90th percentile", band_high),
"policy": cs.col("Policy", band_policy, levels=[label[p] for p in policies]),
}),
cs.chart("shares", "arm-share", "Share of decisions per arm", {
"t": cs.col("Decision", share_t), "share": cs.col("Share", share_v),
"arm": cs.col("Arm", share_arm, levels=arm_names), "policy": cs.col("Policy", share_policy, levels=[label[p] for p in policies]),
}),
],
})
The exact script CodeSplash ran for example “Conversion default” · R version 4.5.1 (2025-06-13)
# Multi-armed bandit simulation
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bandit.simulate 1.0.0 · spec 6493f434cec9832a
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_bandit_simulate(): twin of codesplash.decide.bandits (shared Wichmann–Hill stream)
# %% Inputs
arm_kind <- "bernoulli" # bernoulli | gaussian
means <- as.numeric(unlist(c(0.04, 0.05, 0.06))) # true arm means (unknown to the policies)
sd <- 1 # Gaussian arms only
horizon <- as.integer(600)
reps <- as.integer(40)
delay <- as.integer(0)
epsilon <- 0.1
decay_c <- 5
temperature <- 0.01
seed <- 42 # common random numbers: every policy sees the same rewards
chosen <- c(ab = TRUE, epsilon = TRUE, decaying = TRUE,
ucb1 = TRUE, thompson = TRUE, softmax = TRUE)
label <- cs_bandit_policies()
policies <- names(label)[chosen[names(label)]]
if (!length(policies)) stop("Choose at least one policy to simulate.")
if (length(means) < 2) stop("Enter at least two arm means.")
warnings <- list()
# %% Simulate
sim <- cs_bandit_simulate(means, policies, horizon = horizon, reps = reps, seed = seed, arm_kind = arm_kind, sd = sd,
epsilon = epsilon, decay_c = decay_c, temperature = temperature, delay = delay)
res <- sim$policies
k <- length(means)
arm_names <- sprintf("Arm %d (%s)", seq_len(k), format(means, trim = TRUE, drop0trailing = TRUE))
regrets <- vapply(policies, function(p) res[[p]]$regret, numeric(1))
best_policy <- policies[which.min(regrets)]
best_arm <- sim$best_arm
sm <- sort(means, decreasing = TRUE)
if (sm[1] == sm[2]) warnings <- c(warnings, "Two arms share the best mean, so regret only measures time spent on worse arms.")
# %% Result
b <- res[[best_policy]]
summary <- sprintf(
"Over %s decisions and %d simulated runs, %s lost the least to always playing the best arm (arm %d): mean cumulative regret %.2f, 80%% of runs between %.2f and %.2f; it played the best arm %.0f%% of the time.",
format(horizon, big.mark = ","), reps, label[[best_policy]], best_arm, b$regret, b$regret_p10, b$regret_p90, 100 * b$best_share
)
if ("ab" %in% policies && best_policy != "ab") summary <- paste(summary, sprintf("A fixed A/B allocation lost %.2f.", res$ab$regret))
rows <- do.call(rbind, lapply(policies, function(p) {
v <- res[[p]]
data.frame(policy = label[[p]], regret = v$regret, sd = v$regret_sd, p10 = v$regret_p10, p90 = v$regret_p90,
best_share = v$best_share, reward = v$reward)
}))
grid <- sim$grid
band <- do.call(rbind, lapply(policies, function(p) {
data.frame(t = grid, mean = res[[p]]$curve_mean, low = res[[p]]$curve_low, high = res[[p]]$curve_high, policy = label[[p]])
}))
share <- do.call(rbind, lapply(policies, function(p) {
s <- res[[p]]$shares
data.frame(t = rep(grid, each = k), share = as.vector(t(s)), arm = rep(arm_names, times = length(grid)), policy = label[[p]])
}))
values <- list(best_policy = best_policy, best_policy_label = label[[best_policy]], best_regret = b$regret,
best_arm = best_arm, k = k, horizon = horizon, reps = reps)
for (p in policies) {
v <- res[[p]]
values[[sprintf("regret[%s]", p)]] <- v$regret
values[[sprintf("regret_sd[%s]", p)]] <- v$regret_sd
values[[sprintf("regret_p10[%s]", p)]] <- v$regret_p10
values[[sprintf("regret_p90[%s]", p)]] <- v$regret_p90
values[[sprintf("best_share[%s]", p)]] <- v$best_share
values[[sprintf("reward[%s]", p)]] <- v$reward
values[[sprintf("curve[%s]", p)]] <- v$curve_mean
}
cs_publish(list(
method = "bandit.simulate",
methodVersion = "1.0.0",
title = "Multi-armed bandit simulation",
engine = cs_engine_info("stats", "codesplashr"),
n = reps,
summary = summary,
statistics = list(
list(key = "best_policy", label = "Lowest regret", value = label[[best_policy]]),
list(key = "best_regret", label = "Mean cumulative regret", value = b$regret),
list(key = "best_share", label = "Best arm played", value = b$best_share, format = "percent")
),
tables = list(list(
key = "policies", title = "Policies (cumulative regret at the horizon)",
columns = list(
list(key = "policy", label = "Policy", type = "string"), list(key = "regret", label = "Mean regret", type = "number"),
list(key = "sd", label = "SD", type = "number"), list(key = "p10", label = "10th pct", type = "number"),
list(key = "p90", label = "90th pct", type = "number"), list(key = "best_share", label = "Best arm share", type = "percent"),
list(key = "reward", label = "Mean total reward", type = "number")
),
rows = rows
)),
warnings = warnings,
notes = list(
paste0("Arms: ", paste(arm_names, collapse = ", "), " (", if (arm_kind == "bernoulli") "conversion" else sprintf("Gaussian, SD %s", format(sd)),
"); seed ", seed, "; ", if (delay > 0) sprintf("feedback delayed by %d decisions; ", delay) else "",
"regret = best mean − mean of the arm played, summed over decisions."),
"Every policy faces the same simulated rewards in each run (common random numbers), so differences are due to the policies."
),
values = values,
charts = list(
cs_chart("regret", "regret-bands", "Cumulative regret (mean, 10th–90th percentile)", list(
t = cs_col("Decision", band$t), mean = cs_col("Cumulative regret", band$mean), low = cs_col("10th percentile", band$low),
high = cs_col("90th percentile", band$high), policy = cs_col("Policy", band$policy, levels = unname(label[policies]))
)),
cs_chart("shares", "arm-share", "Share of decisions per arm", list(
t = cs_col("Decision", share$t), share = cs_col("Share", share$share), arm = cs_col("Arm", share$arm, levels = arm_names),
policy = cs_col("Policy", share$policy, levels = unname(label[policies]))
))
)
))
Sources
- Sutton, R. S., & Barto, A. G. (2018). Reinforcement learning: An introduction (2nd ed.). MIT Press.
- Auer, P., Cesa-Bianchi, N., & Fischer, P. (2002). Finite-time analysis of the multiarmed bandit problem. Machine Learning, 47, 235–256.
- Agrawal, S., & Goyal, N. (2012). Analysis of Thompson sampling for the multi-armed bandit problem. COLT, 23, 39.1–39.26.
- Scott, S. L. (2015). Multi-armed bandit experiments in the online service economy. Applied Stochastic Models in Business and Industry, 31, 37–45.
From the CodeSplash method registry · bandit.simulate v1.0.0.