Skip to content

BA/B tests · experiment.power

A/B test planning — sample size, MDE and duration

How many users, and how many days, does an A/B test need to detect the effect we care about?

Plans an online experiment for a conversion, continuous or ratio metric: units per arm, the minimum detectable effect at a given size, or the power, with CUPED variance reduction, several treatment arms (Bonferroni, Šidák or Dunnett) and the duration at the expected daily traffic, rounded to whole weeks — for superiority, non-inferiority, equivalence (two one-sided tests) or minimum-effect hypotheses, with Farrington–Manning variances for conversion rates.

Verified in Python and R Python and R agree to 10 decimals Also called A/B test sample size, sample size calculator, minimum detectable effect…

A real result

Example “Conversion n duration”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

A/B test planRecorded · Python and R agreeRecorded 2026-11-09 · 26 values compared · largest relative difference 5.0e-16
R

57,760 units per treatment arm, 57,760 control (115,520 total); MDE 5.00% relative, power 0.800.

Units per treatment arm
57,760
Control units
57,760
Total units
115,520
Relative MDE
5.0%
Absolute MDE
0.0050
Power
0.8000
Days
49

Plots

Power by units per treatment armHow does power grow with sample size (or effect size), and where does it reach the target?
View data
PowerEffectUnits per treatment arm
0.10223.8% lift5,776
0.12403.8% lift8125.56
0.14613.8% lift10475.12
0.16833.8% lift12824.68
0.19063.8% lift15174.24
0.21293.8% lift17523.80
0.23523.8% lift19873.36
0.25743.8% lift22222.92
0.27943.8% lift24572.47
0.30133.8% lift26922.03
0.32303.8% lift29271.59
0.34443.8% lift31621.15
0.36553.8% lift33970.71
0.38633.8% lift36320.27
0.40683.8% lift38669.83
0.42693.8% lift41019.39
0.44663.8% lift43368.95
0.46603.8% lift45718.51
0.48493.8% lift48068.07
0.50343.8% lift50417.63
0.52153.8% lift52767.19
0.53913.8% lift55116.75
0.55633.8% lift57466.31
0.57303.8% lift59815.86
0.58933.8% lift62165.42
0.60523.8% lift64514.98
0.62053.8% lift66864.54
0.63553.8% lift69214.10
0.65003.8% lift71563.66
0.66403.8% lift73913.22
0.67763.8% lift76262.78
0.69073.8% lift78612.34
0.70353.8% lift80961.90
0.71583.8% lift83311.46
0.72773.8% lift85661.02
0.73923.8% lift88010.58
0.75023.8% lift90360.14
0.76093.8% lift92709.69
0.77123.8% lift95059.25
0.78113.8% lift97408.81
0.79073.8% lift99758.37
0.79993.8% lift102107.93
0.80883.8% lift104457.49
0.81733.8% lift106807.05
0.82553.8% lift109156.61
0.83333.8% lift111506.17
0.84093.8% lift113855.73
0.84813.8% lift116205.29
0.85513.8% lift118554.85
0.86183.8% lift120904.41
0.86823.8% lift123253.97
0.87433.8% lift125603.53
0.88023.8% lift127953.08
0.88583.8% lift130302.64
0.89123.8% lift132652.20
0.89643.8% lift135001.76
0.90133.8% lift137351.32
0.90603.8% lift139700.88
0.91053.8% lift142050.44
0.91493.8% lift144,400

First 60 of 180 rows.

Minimum detectable effect by duration (80% power)

WeeksUnits per treatment armAbsolute MDERelative MDE
18,7500.013113.1%
217,5000.00929.2%
326,2500.00757.5%
435,0000.00646.4%
543,7500.00585.8%
652,5000.00525.2%
761,2500.00494.9%
870,0000.00454.5%
  • Normal approximation for a difference in means; conversion rates use unpooled per-arm variances, ratio metrics the delta method.
  • Sizes are rounded up; the power is recomputed at the rounded size and includes both rejection tails for two-sided tests.
Python

57,760 units per treatment arm, 57,760 control (115,520 total); MDE 5.00% relative, power 0.800.

Units per treatment arm
57,760
Control units
57,760
Total units
115,520
Relative MDE
5.0%
Absolute MDE
0.0050
Power
0.8000
Days
49

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

Minimum detectable effect by duration (80% power)

WeeksUnits per treatment armAbsolute MDERelative MDE
18,7500.013113.1%
217,5000.00929.2%
326,2500.00757.5%
435,0000.00646.4%
543,7500.00585.8%
652,5000.00525.2%
761,2500.00494.9%
870,0000.00454.5%
  • Normal approximation for a difference in means; conversion rates use unpooled per-arm variances, ratio metrics the delta method.
  • Sizes are rounded up; the power is recomputed at the rounded size and includes both rejection tails for two-sided tests.

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 n durationNo data needed
  • Continuous mde cupedNo data needed
  • Ratio power one sidedNo data needed
  • Multi arm dunnett sqrtNo data needed
  • Mde from days decreaseNo data needed
  • Noninferiority fmNo data needed
  • Equivalence continuousNo data needed
  • Minimum effect powerNo data needed

In the guides

Where it sits in the decision guides

  • Sample-size planning · Statistics Guide · Step 0 — Prepare your data
  • Sample size and power · Statistics Guide · Additional considerations
  • A/B testing (hypothesis testing) · DS & ML Decision Guide · Optimize / decide

Choices you make

hypothesis

Solve fordefault n

Which quantity to compute from the others: the sample size, the power, or the smallest effect you could detect.

  • Sample size and duration(default) — Finds the sample per arm and how long it takes at your traffic; the usual question before a test.
  • Minimum detectable effect — Finds the smallest effect your sample can detect; pick it when the traffic is fixed.
  • Power — Finds the chance of detecting your effect at this sample; pick it when the sample size is fixed.
Metricdefault binary

Kind of metric being powered: a conversion rate, a mean, or a ratio such as clicks per session.

  • Conversion rate (yes/no per unit)(default) — Each unit converts or doesn't; pick it for signup, purchase or click rates.
  • Mean of a continuous metric (revenue, time …) — Each unit has a number; pick it for revenue or time spent.
  • Ratio metric (Σ numerator / Σ denominator, e.g. clicks per session) — Divides two totals across units; pick it for metrics such as clicks per session.
Baseline (control) conversion rate or meandefault 0.1

Conversion: a proportion between 0 and 1. Continuous: the control mean (used for relative effects).

Standard deviation per unitdefault 1

Standard deviation of the metric per unit, from past data.

Mean numerator per unitdefault 0.6

Average numerator per unit for a ratio metric (e.g. clicks per user).

Mean denominator per unitdefault 3

Average denominator per unit for a ratio metric (e.g. sessions per user).

SD of the numeratordefault 0.9

Standard deviation of the numerator per unit.

SD of the denominatordefault 2

Standard deviation of the denominator per unit.

Correlation of numerator and denominatordefault 0.6

Correlation between numerator and denominator per unit (delta method).

Effect expressed asdefault relative

Whether the effect is a relative change (lift) or an absolute difference.

  • Relative change (lift, e.g. 0.05 = +5%)(default) — Enter the effect as a share of the baseline (0.05 = +5%); the usual way to state an A/B lift.
  • Absolute difference — Enter the effect in the metric's own units; pick it when a fixed gain matters whatever the baseline.
Hypothesisdefault superiority

What you need to show: any improvement, not worse by a margin, within a margin, or better by a margin.

  • Superiority — any difference (or improvement)(default) — H₀: no difference. The usual A/B test: detect an effect at least as large as the MDE.
  • Non-inferiority — not worse by more than a margin — H₀: the treatment is worse by the margin or more. For guardrails and cheaper alternatives that must not hurt.
  • Equivalence — within ± a margin (two one-sided tests) — H₀: the difference is at least the margin in either direction. Shows a change makes no practical difference.
  • Minimum effect — better by at least a margin — H₀: the improvement is at most the margin. Ship only if the gain clears a cost or risk threshold.
Margin (in the effect's units)default 0.02

Relative or absolute, as set by “Effect expressed as”. Justify it before seeing data.

Expected true effectdefault 0

Positive = better. Usually 0 for non-inferiority and equivalence; above the margin for minimum effect.

Variance at the margin (conversion rates)default fm

Variance used at the margin for conversion rates. Farrington–Manning is the standard choice.

  • Farrington–Manning (restricted MLE)(default) — Variance at the null boundary, as the Farrington–Manning score test uses; the standard for rate differences.
  • Wald (unrestricted) — The alternative's variance everywhere; simpler, slightly optimistic near 0 or 1.
Effect to detect (or the planned effect when solving for power)default 0.05

Smallest effect worth detecting, or the planned effect when solving for power.

Direction of the effectdefault increase

Matters for conversion rates (their variance depends on the rate) and one-sided tests.

  • Increase(default) — Plans for the metric going up; pick it when a rise is what you hope to see.
  • Decrease — Plans for the metric going down; pick it for metrics you want lower, such as churn.
Significance level (α)default 0.05

The false-alarm rate you accept: the chance of a significant result when there is truly no effect. 0.05 is conventional.

Target power (1 − β)default 0.8

Chance of detecting the effect if it is real. 0.8 is common; 0.9 is stricter and needs more data.

Testdefault two-sided

Which direction counts as evidence. Keep two-sided unless you fixed the direction before seeing the data.

  • Two-sided(default) — Plans for a test in either direction; the usual choice, though it needs more data than one-sided.
  • One-sided (in the expected direction) — Plans for a test in the expected direction only; needs less data, but can't claim an effect the other way.

options

Arms (including the control)default 2

Number of arms including the control.

Control sizedefault equal

Size of the control arm relative to each treatment arm.

  • Same as each treatment arm(default) — Gives the control arm the same size as each treatment arm; the plain split, and best with one treatment.
  • √(treatment arms) × a treatment arm (best for many-to-one) — Makes control √(treatment arms) times a treatment arm; gives the most power when every arm is compared with one control.
  • Custom ratio — Uses the control-to-treatment ratio you enter; pick it when traffic or cost fixes the split.
Control units per treatment unitdefault 1

Control units per treatment unit, for a custom allocation.

Several treatment armsdefault dunnett

Only used with more than two arms.

  • Dunnett (many-to-one)(default) — Compares every arm with the control using their shared correlation; the most powerful many-to-one choice.
  • Bonferroni — Divides α by the number of comparisons; the plainest choice, and conservative with many arms.
  • Šidák — A touch less strict than Bonferroni; exact when the comparisons are independent.
  • No correction — Plans each arm at full α; fine for one comparison, and overstated for several.
CUPED: correlation with the pre-period metric (0 = none)default 0

Variance shrinks by 1 − ρ²; estimate ρ from history.

Sample size given asdefault n

Give the sample size as units per arm, or as days of traffic.

  • Units per treatment arm(default) — Enter the units per arm; pick it when you know the sample.
  • Days of traffic — Enter days of traffic; pick it when the test length is fixed, and daily traffic gives the sample.
Units per treatment armdefault 10000

Units per treatment arm.

Days of trafficdefault 14

Days the experiment runs.

Eligible units per daydefault —

Needed for the duration and for sizes given in days.

Share of traffic in the experimentdefault 1

Share of traffic that enters the experiment (1 = all of it).

Round the duration up to whole weeksdefault on

Covers every weekday equally (weekly seasonality).

Longest acceptable duration (days)default —

Longest you are willing to run. The plan warns if it needs more.

What it reports

n_treatment
How many independent units the analysis used; it sets precision and power.
n_control
How many independent units the analysis used; it sets precision and power.
n_total
How many independent units the analysis used; it sets precision and power.
n_exact
How many independent units the analysis used; it sets precision and power.
power
The chance a test detects an effect of a given size, if that effect is real.
alpha_comparison
The false-positive rate you accept before looking at the data, usually 0.05.
z_crit
An estimate in standard-error units, compared with the standard normal distribution.
baseline_mean
The sum divided by the count; the balance point of the data, pulled by extreme values.
variance_control
The average squared distance from the mean; the SD squared.
variance_treatment
The average squared distance from the mean; the SD squared.
cuped_factor
Uses each user's pre-experiment metric to remove noise, shrinking intervals without bias.
control_ratio
Control units planned per treatment unit, from the allocation rule; 1 means the control is as big as each treatment arm.
comparisons
Running many tests raises the chance that at least one is a false positive.
hypothesis
What the plan must show: superiority, noninferiority, equivalence, or minimum_effect (better by at least a margin).
alpha
The α this run used for its decisions and boundaries.

Per group, level or term: days, margin_abs, mde_abs, mde_rel, target_power, true_effect_abs

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses scipy, codesplash; R uses stats, codesplashr.

Default traps between the two languages

  • Closed-form normal sizes and MDEs; Dunnett's critical value comes from Brent root finding (brentq ↔ uniroot, tol 1e-12) of the deterministic Gauss–Legendre twin.
Python

The exact script CodeSplash ran for example “Conversion n duration” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# A/B test planning — sample size, MDE and duration
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method experiment.power 1.1.0 · spec 283eba1c2058868f
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import math

from scipy.special import ndtri

import codesplash as cs
from codesplash.experiment import design as xd  # closed-form A/B planning (twin of R cs_exp_*)

# %% Inputs
solve_for = "n"  # n | mde | power
kind = "binary"  # binary | continuous | ratio
baseline = 0.1
mde_type = "relative"  # relative | absolute
mde_in = 0.05
direction = "increase"
alpha = 0.05
target = 0.8
alternative = "two-sided"
arms = int(2)
allocation = "equal"
rho = 0
correction = "dunnett" if arms > 2 else "none"
size_from = "n" if solve_for != "n" else "n"
n_given = 10000
days_given = 14
daily = 5000  # eligible units per day (None = unknown)
exposure = 0.5
whole_weeks = True
max_days = None
warnings = []
if kind == "binary" and not 0 < baseline < 1:
    raise ValueError("A conversion-rate baseline must be between 0 and 1.")

mean0, var0 = xd.unit_variance(
    kind, baseline, sd=1, num_mean=0.6, den_mean=3,
    num_sd=0.9, den_sd=2, corr=0.6,
)
if var0 <= 0:
    raise ValueError("The metric's variance must be positive (check the ratio-metric inputs).")
shrink = 1.0 - rho**2  # CUPED keeps 1 − ρ² of the variance
v0 = var0 * shrink
comparisons = arms - 1
ratio = xd.allocation(arms, allocation, 1)  # control units per treatment unit
lam = math.sqrt(1.0 / (1.0 + ratio))  # correlation root of two comparisons sharing the control (under H0)
z_crit, alpha_cmp = xd.crit(alpha, comparisons, correction, alternative, lam)
z_pow = float(ndtri(target))
sign = -1.0 if direction == "decrease" else 1.0
delta_planned = sign * (mde_in * abs(mean0) if mde_type == "relative" else mde_in)
hypothesis = "superiority"  # superiority | noninferiority | equivalence | minimum_effect
margin_hyp = hypothesis != "superiority"
m_abs = e_true = None
sds = (None, None, None)
if margin_hyp:
    # Margin tests are one-sided (equivalence: two one-sided tests, each at the per-comparison α).
    if solve_for == "mde":
        raise ValueError("With a margin-based hypothesis, solve for the sample size or the power.")
    z_crit, alpha_cmp = xd.crit(alpha, comparisons, correction, "one-sided", lam)
    scale = abs(mean0) if mde_type == "relative" else 1.0
    m_abs = 0.02 * scale
    e_true = 0 * scale  # in the better direction
    margin_method = "fm"

# Equivalent idiom (two arms, conversion): power.prop.test in R / statsmodels NormalIndPower in Python.
# %% Solve
n_exact = None
if size_from == "days" and daily is None:
    raise ValueError("Sizes given in days need the eligible units per day.")
if size_from == "days":
    n_t = math.floor(days_given * daily * exposure / (comparisons + ratio))
    if n_t < 2:
        raise ValueError("Too little traffic: fewer than two units per arm in that many days.")
elif solve_for != "n":
    n_t = n_given
if margin_hyp:
    delta = sign * e_true
    if kind == "binary" and not 0 < mean0 + delta < 1:
        raise ValueError("The treatment conversion rate implied by the effect is outside (0, 1).")
    v1 = xd.treatment_variance(kind, mean0, var0, delta) * shrink
    sds = xd.margin_sds(kind, mean0, delta, v1, v0, ratio, m_abs, sign, margin_method, shrink)
    if solve_for == "n":
        n_exact = xd.margin_n(hypothesis, e_true, m_abs, *sds, z_crit, z_pow, target)
        n_t = int(math.ceil(n_exact - 1e-9))
    power = xd.margin_power(hypothesis, e_true, m_abs, *sds, n_t, z_crit)
elif solve_for == "n":
    delta = delta_planned
    v1 = xd.treatment_variance(kind, mean0, var0, delta) * shrink
    if kind == "binary" and not 0 < mean0 + delta < 1:
        raise ValueError("The treatment conversion rate implied by the effect is outside (0, 1).")
    n_exact = xd.n_required(delta, v1, v0, ratio, z_crit, z_pow)
    n_t = int(math.ceil(n_exact - 1e-9))
    power = xd.power(delta, v1, v0, n_t, ratio, z_crit, alternative)
elif solve_for == "mde":
    delta = xd.mde(kind, mean0, var0, n_t, ratio, z_crit, z_pow, shrink, direction)
    v1 = xd.treatment_variance(kind, mean0, var0, delta) * shrink
    power = xd.power(delta, v1, v0, n_t, ratio, z_crit, alternative)
else:
    delta = delta_planned
    v1 = xd.treatment_variance(kind, mean0, var0, delta) * shrink
    power = xd.power(delta, v1, v0, n_t, ratio, z_crit, alternative)
n_c = int(math.ceil(ratio * n_t - 1e-9))
n_total = comparisons * n_t + n_c
mde_abs = abs(delta) if not margin_hyp else None
mde_rel = (abs(delta / mean0) if mean0 != 0 else math.nan) if not margin_hyp else None

# %% Duration
days = weeks = days_exact = None
tables = []
if daily is not None:
    days, weeks, days_exact = xd.duration(n_total, daily, exposure, whole_weeks)
    if max_days is not None and days > max_days:
        warnings.append(f"The test needs {days} days, longer than the {int(max_days)}-day limit; consider a larger effect, more traffic or CUPED.")
    rows = []
    for w in (range(1, 9) if not margin_hyp else []):
        nt_w = math.floor(7 * w * daily * exposure / (comparisons + ratio))
        if nt_w < 2:
            continue
        d_w = xd.mde(kind, mean0, var0, nt_w, ratio, z_crit, z_pow, shrink, direction)
        rows.append({"weeks": w, "n": nt_w, "mde_abs": abs(d_w), "mde_rel": abs(d_w / mean0) if mean0 else None})
    tables.extend([] if margin_hyp else [{
        "key": "mde_by_duration", "title": f"Minimum detectable effect by duration ({target:.0%} power)",
        "columns": [{"key": "weeks", "label": "Weeks", "type": "integer"}, {"key": "n", "label": "Units per treatment arm", "type": "integer"},
                    {"key": "mde_abs", "label": "Absolute MDE", "type": "number"}, {"key": "mde_rel", "label": "Relative MDE", "type": "percent"}],
        "rows": rows,
    }])
if comparisons > 1 and correction == "none":
    warnings.append("Several treatment arms without a correction inflate the chance of a false winner.")

# %% Power curve
grid = [max(2.0, n_t * (0.1 + 2.4 * i / 59)) for i in range(60)]
curve = []
if margin_hyp:
    curve = [(x, xd.margin_power(hypothesis, e_true, m_abs, *sds, x, z_crit), f"true effect {e_true:.4g}") for x in grid]
for s in ((0.75, 1.0, 1.25) if not margin_hyp else ()):
    d = delta * s
    if kind == "binary" and not 0 < mean0 + d < 1:
        continue
    v1s = xd.treatment_variance(kind, mean0, var0, d) * shrink
    label = f"{s * mde_rel:.1%} lift" if math.isfinite(mde_rel) else f"Δ = {d:.4g}"
    curve += [(x, xd.power(d, v1s, v0, x, ratio, z_crit, alternative), label) for x in grid]

# %% Result
cs.publish({
    "method": "experiment.power",
    "methodVersion": "1.1.0",
    "title": "A/B test plan",
    "engine": cs.engine_info("scipy"),
    "summary": (f"{n_t:,} units per treatment arm, {n_c:,} control ({n_total:,} total); MDE {mde_rel:.2%} relative, power {power:.3f}." if not margin_hyp
                else f"{hypothesis.replace('_', ' ')}: {n_t:,} units per treatment arm, {n_c:,} control ({n_total:,} total); margin {m_abs:.4g}, power {power:.3f}."),
    "statistics": [
        {"key": "n_treatment", "label": "Units per treatment arm", "value": n_t, "format": "integer"},
        {"key": "n_control", "label": "Control units", "value": n_c, "format": "integer"},
        {"key": "n_total", "label": "Total units", "value": n_total, "format": "integer"},
        *([{"key": "mde_rel", "label": "Relative MDE", "value": mde_rel, "format": "percent"},
           {"key": "mde_abs", "label": "Absolute MDE", "value": mde_abs}] if not margin_hyp else
          [{"key": "margin_abs", "label": "Margin", "value": m_abs}]),
        {"key": "power", "label": "Power", "value": power},
        *([{"key": "days", "label": "Days", "value": days, "format": "integer"}] if days is not None else []),
    ],
    "tables": tables,
    "warnings": warnings,
    "notes": [
        "Normal approximation for a difference in means; conversion rates use unpooled per-arm variances, ratio metrics the delta method.",
        "Sizes are rounded up; the power is recomputed at the rounded size and includes both rejection tails for two-sided tests.",
        *([f"{comparisons} treatment arms vs the control: {correction} correction, α = {alpha_cmp:.4g} per comparison."] if comparisons > 1 else []),
        *([f"CUPED with ρ = {rho:g} keeps {shrink:.1%} of the variance."] if rho > 0 else []),
    ],
    "charts": [cs.chart(
        "power", "power-curve", "Power by units per treatment arm",
        {"x": cs.col("Units per treatment arm", [c[0] for c in curve]), "power": cs.col("Power", [c[1] for c in curve]),
         "series": cs.col("Effect", [c[2] for c in curve])},
        controls={"target": target if solve_for != "power" else 0.8},
    )],
    "values": {
        "n_treatment": n_t, "n_control": n_c, "n_total": n_total, "n_exact": n_exact, "power": power,
        "target_power": target if solve_for != "power" else None, "mde_abs": mde_abs, "mde_rel": mde_rel,
        "alpha": alpha, "alpha_comparison": alpha_cmp, "z_crit": z_crit, "baseline_mean": mean0,
        "variance_control": v0, "variance_treatment": v1, "cuped_factor": shrink, "control_ratio": ratio,
        "comparisons": comparisons, "days": days, "weeks": weeks if days is not None else None, "days_exact": days_exact,
        "hypothesis": hypothesis, "margin_abs": m_abs, "true_effect_abs": e_true, "sd_alternative": sds[0],
        "sd_null_lower": sds[1], "sd_null_upper": sds[2],
    },
})
R

The exact script CodeSplash ran for example “Conversion n duration” · R version 4.5.1 (2025-06-13)

# A/B test planning — sample size, MDE and duration
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method experiment.power 1.1.0 · spec 283eba1c2058868f
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # closed-form A/B planning: cs_exp_* (twin of codesplash.experiment.design)

# %% Inputs
solve_for <- "n" # n | mde | power
kind <- "binary" # binary | continuous | ratio
baseline <- 0.1
mde_type <- "relative" # relative | absolute
mde_in <- 0.05
direction <- "increase"
alpha <- 0.05
target <- 0.8
alternative <- "two-sided"
arms <- as.integer(2)
allocation <- "equal"
rho <- 0
correction <- if (arms > 2) "dunnett" else "none"
size_from <- if (solve_for != "n") "n" else "n"
n_given <- 10000
days_given <- 14
daily <- 5000 # eligible units per day (NULL = unknown)
exposure <- 0.5
whole_weeks <- TRUE
max_days <- NULL
warnings <- list()
if (kind == "binary" && !(baseline > 0 && baseline < 1)) stop("A conversion-rate baseline must be between 0 and 1.")

mv <- cs_exp_variance(kind, baseline, sd = 1, num_mean = 0.6, den_mean = 3,
                      num_sd = 0.9, den_sd = 2, corr = 0.6)
mean0 <- mv[1]
var0 <- mv[2]
if (var0 <= 0) stop("The metric's variance must be positive (check the ratio-metric inputs).")
shrink <- 1 - rho^2 # CUPED keeps 1 - rho^2 of the variance
v0 <- var0 * shrink
comparisons <- arms - 1L
ratio <- cs_exp_allocation(arms, allocation, 1) # control units per treatment unit
lam <- sqrt(1 / (1 + ratio)) # correlation root of two comparisons sharing the control (under H0)
cr <- cs_exp_crit(alpha, comparisons, correction, alternative, lam)
z_crit <- cr[1]
alpha_cmp <- cr[2]
z_pow <- stats::qnorm(target)
sgn <- if (direction == "decrease") -1 else 1
delta_planned <- sgn * (if (mde_type == "relative") mde_in * abs(mean0) else mde_in)
hypothesis <- "superiority" # superiority | noninferiority | equivalence | minimum_effect
margin_hyp <- hypothesis != "superiority"
m_abs <- e_true <- NULL
sds <- c(NA, NA, NA)
if (margin_hyp) {
  # Margin tests are one-sided (equivalence: two one-sided tests, each at the per-comparison alpha).
  if (solve_for == "mde") stop("With a margin-based hypothesis, solve for the sample size or the power.")
  cr <- cs_exp_crit(alpha, comparisons, correction, "one-sided", lam)
  z_crit <- cr[1]
  alpha_cmp <- cr[2]
  scl <- if (mde_type == "relative") abs(mean0) else 1
  m_abs <- 0.02 * scl
  e_true <- 0 * scl # in the better direction
  margin_method <- "fm"
}

# Equivalent idiom (two arms, conversion): power.prop.test(p1 = baseline, p2 = baseline * (1 + mde), power = target)
# %% Solve
n_exact <- NA
if (size_from == "days" && is.null(daily)) stop("Sizes given in days need the eligible units per day.")
if (size_from == "days") {
  n_t <- floor(days_given * daily * exposure / (comparisons + ratio))
  if (n_t < 2) stop("Too little traffic: fewer than two units per arm in that many days.")
} else if (solve_for != "n") {
  n_t <- n_given
}
if (margin_hyp) {
  delta <- sgn * e_true
  if (kind == "binary" && !(mean0 + delta > 0 && mean0 + delta < 1)) stop("The treatment conversion rate implied by the effect is outside (0, 1).")
  v1 <- cs_exp_treatment_variance(kind, mean0, var0, delta) * shrink
  sds <- cs_exp_margin_sds(kind, mean0, delta, v1, v0, ratio, m_abs, sgn, margin_method, shrink)
  if (solve_for == "n") {
    n_exact <- cs_exp_margin_n(hypothesis, e_true, m_abs, sds[1], sds[2], sds[3], z_crit, z_pow, target)
    n_t <- as.integer(ceiling(n_exact - 1e-9))
  }
  power <- cs_exp_margin_power(hypothesis, e_true, m_abs, sds[1], sds[2], sds[3], n_t, z_crit)
} else if (solve_for == "n") {
  delta <- delta_planned
  v1 <- cs_exp_treatment_variance(kind, mean0, var0, delta) * shrink
  if (kind == "binary" && !(mean0 + delta > 0 && mean0 + delta < 1)) stop("The treatment conversion rate implied by the effect is outside (0, 1).")
  n_exact <- cs_exp_n(delta, v1, v0, ratio, z_crit, z_pow)
  n_t <- as.integer(ceiling(n_exact - 1e-9))
  power <- cs_exp_power(delta, v1, v0, n_t, ratio, z_crit, alternative)
} else if (solve_for == "mde") {
  delta <- cs_exp_mde(kind, mean0, var0, n_t, ratio, z_crit, z_pow, shrink, direction)
  v1 <- cs_exp_treatment_variance(kind, mean0, var0, delta) * shrink
  power <- cs_exp_power(delta, v1, v0, n_t, ratio, z_crit, alternative)
} else {
  delta <- delta_planned
  v1 <- cs_exp_treatment_variance(kind, mean0, var0, delta) * shrink
  power <- cs_exp_power(delta, v1, v0, n_t, ratio, z_crit, alternative)
}
n_c <- as.integer(ceiling(ratio * n_t - 1e-9))
n_total <- comparisons * n_t + n_c
mde_abs <- if (margin_hyp) NA else abs(delta)
mde_rel <- if (margin_hyp) NA else if (mean0 != 0) abs(delta / mean0) else NaN

# %% Duration
days <- weeks <- days_exact <- NULL
tables <- list()
if (!is.null(daily)) {
  du <- cs_exp_duration(n_total, daily, exposure, whole_weeks)
  days <- du$days
  weeks <- du$weeks
  days_exact <- du$exact
  if (!is.null(max_days) && days > max_days) {
    warnings <- c(warnings, sprintf("The test needs %d days, longer than the %d-day limit; consider a larger effect, more traffic or CUPED.", days, as.integer(max_days)))
  }
  rows <- list()
  for (w in if (margin_hyp) integer(0) else 1:8) {
    nt_w <- floor(7 * w * daily * exposure / (comparisons + ratio))
    if (nt_w < 2) next
    d_w <- cs_exp_mde(kind, mean0, var0, nt_w, ratio, z_crit, z_pow, shrink, direction)
    rows[[length(rows) + 1]] <- list(weeks = w, n = nt_w, mde_abs = abs(d_w), mde_rel = if (mean0 != 0) abs(d_w / mean0) else NULL)
  }
  if (!margin_hyp) tables <- list(list(
    key = "mde_by_duration", title = sprintf("Minimum detectable effect by duration (%.0f%% power)", 100 * target),
    columns = list(list(key = "weeks", label = "Weeks", type = "integer"), list(key = "n", label = "Units per treatment arm", type = "integer"),
                   list(key = "mde_abs", label = "Absolute MDE", type = "number"), list(key = "mde_rel", label = "Relative MDE", type = "percent")),
    rows = rows
  ))
}
if (comparisons > 1 && correction == "none") warnings <- c(warnings, "Several treatment arms without a correction inflate the chance of a false winner.")

# %% Power curve
grid <- pmax(2, n_t * (0.1 + 2.4 * (0:59) / 59))
curve <- NULL
if (margin_hyp) {
  curve <- data.frame(x = grid, power = vapply(grid, function(x) cs_exp_margin_power(hypothesis, e_true, m_abs, sds[1], sds[2], sds[3], x, z_crit), numeric(1)),
                      series = sprintf("true effect %.4g", e_true))
}
for (s in if (margin_hyp) numeric(0) else c(0.75, 1, 1.25)) {
  d <- delta * s
  if (kind == "binary" && !(mean0 + d > 0 && mean0 + d < 1)) next
  v1s <- cs_exp_treatment_variance(kind, mean0, var0, d) * shrink
  label <- if (is.finite(mde_rel)) sprintf("%.1f%% lift", 100 * s * mde_rel) else sprintf("Δ = %.4g", d)
  curve <- rbind(curve, data.frame(x = grid, power = vapply(grid, function(x) cs_exp_power(d, v1s, v0, x, ratio, z_crit, alternative), numeric(1)), series = label))
}

# %% Result
stats_list <- list(
  list(key = "n_treatment", label = "Units per treatment arm", value = n_t, format = "integer"),
  list(key = "n_control", label = "Control units", value = n_c, format = "integer"),
  list(key = "n_total", label = "Total units", value = n_total, format = "integer"),
  list(key = "power", label = "Power", value = power)
)
stats_list <- append(stats_list, if (margin_hyp) list(list(key = "margin_abs", label = "Margin", value = m_abs))
                     else list(list(key = "mde_rel", label = "Relative MDE", value = mde_rel, format = "percent"),
                               list(key = "mde_abs", label = "Absolute MDE", value = mde_abs)), after = 3)
if (!is.null(days)) stats_list <- c(stats_list, list(list(key = "days", label = "Days", value = days, format = "integer")))
cs_publish(list(
  method = "experiment.power",
  methodVersion = "1.1.0",
  title = "A/B test plan",
  engine = cs_engine_info("stats"),
  summary = if (!margin_hyp) sprintf("%s units per treatment arm, %s control (%s total); MDE %.2f%% relative, power %.3f.",
                    format(n_t, big.mark = ","), format(n_c, big.mark = ","), format(n_total, big.mark = ","), 100 * mde_rel, power)
            else sprintf("%s: %s units per treatment arm, %s control (%s total); margin %.4g, power %.3f.", gsub("_", " ", hypothesis),
                    format(n_t, big.mark = ","), format(n_c, big.mark = ","), format(n_total, big.mark = ","), m_abs, power),
  statistics = stats_list,
  tables = tables,
  warnings = warnings,
  notes = c("Normal approximation for a difference in means; conversion rates use unpooled per-arm variances, ratio metrics the delta method.",
            "Sizes are rounded up; the power is recomputed at the rounded size and includes both rejection tails for two-sided tests.",
            if (comparisons > 1) sprintf("%d treatment arms vs the control: %s correction, α = %.4g per comparison.", comparisons, correction, alpha_cmp),
            if (rho > 0) sprintf("CUPED with ρ = %g keeps %.1f%% of the variance.", rho, 100 * shrink)),
  charts = list(cs_chart(
    "power", "power-curve", "Power by units per treatment arm",
    list(x = cs_col("Units per treatment arm", curve$x), power = cs_col("Power", curve$power), series = cs_col("Effect", curve$series)),
    controls = list(target = if (solve_for != "power") target else 0.8)
  )),
  values = list(
    n_treatment = n_t, n_control = n_c, n_total = n_total, n_exact = n_exact, power = power,
    target_power = if (solve_for != "power") target else NA, mde_abs = mde_abs, mde_rel = mde_rel,
    alpha = alpha, alpha_comparison = alpha_cmp, z_crit = z_crit, baseline_mean = mean0,
    variance_control = v0, variance_treatment = v1, cuped_factor = shrink, control_ratio = ratio,
    comparisons = comparisons, days = if (is.null(days)) NA else days, weeks = if (is.null(days)) NA else weeks,
    days_exact = if (is.null(days_exact)) NA else days_exact,
    hypothesis = hypothesis, margin_abs = if (is.null(m_abs)) NA else m_abs, true_effect_abs = if (is.null(e_true)) NA else e_true,
    sd_alternative = sds[1], sd_null_lower = sds[2], sd_null_upper = sds[3]
  )
))

Sources

  • Farrington, C. P., & Manning, G. (1990). Test statistics and sample size formulae for comparative binomial trials with null hypothesis of non-zero risk difference or non-unity relative risk. Statistics in Medicine, 9, 1447–1454.
  • Chow, S.-C., Shao, J., Wang, H., & Lokhnygina, Y. (2017). Sample Size Calculations in Clinical Research (3rd ed.). CRC Press.
  • Kohavi, R., Tang, D., & Xu, Y. (2020). Trustworthy online controlled experiments. Cambridge University Press.
  • Deng, A., Xu, Y., Kohavi, R., & Walker, T. (2013). Improving the sensitivity of online controlled experiments by utilizing pre-experiment data. WSDM '13.
  • Deng, A., Lu, J., & Litz, J. (2017). Trustworthy analysis of online A/B tests: pitfalls, challenges and solutions. WSDM '17.
  • Dunnett, C. W. (1955). A multiple comparison procedure for comparing several treatments with a control. JASA, 50, 1096–1121.

From the CodeSplash method registry · experiment.power v1.1.0.