ADescribe · variance.one_sample
One-sample variance test
Is the spread of one measurement different from a target standard deviation?
Compares a sample's standard deviation with a specified value: the chi-square test (exact for normal data) or Bonett's kurtosis-adjusted test (robust to non-normal data), with an interval for the standard deviation and the variance.
A real result
Example “Chisq guide”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
χ²(9) = 3.40, p = .107
- χ²
- 3.400
- df
- 9
- p
- .107
Effect size
- Standard deviation 0.6146 95% CI [0.4228, 1.122]
Plots
View data
| x |
|---|
| 4.200 |
| 5.100 |
| 5.400 |
| 4.800 |
| 6 |
| 5.800 |
| 4.900 |
| 5.600 |
| 6.200 |
| 5 |
Assumptions
- Normality — Shapiro–Wilk p = 0.934.
95% interval
| Quantity | Estimate | Lower | Upper |
|---|---|---|---|
| Standard deviation | 0.6146 | 0.4228 | 1.122 |
| Variance | 0.3778 | 0.1787 | 1.259 |
- Target SD 1 (variance 1).
χ²(9) = 3.40, p = .107
- χ²
- 3.400
- df
- 9
- p
- .107
Effect size
- Standard deviation 0.6146 95% CI [0.4228, 1.122]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Normality — Shapiro–Wilk p = 0.934.
95% interval
| Quantity | Estimate | Lower | Upper |
|---|---|---|---|
| Standard deviation | 0.6146 | 0.4228 | 1.122 |
| Variance | 0.3778 | 0.1787 | 1.259 |
- Target SD 1 (variance 1).
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
- Chisq guidec3_variance_pairs · outcome: x
- Chisq greaterc3_onevar · outcome: strength
- Chisq lesspefr · outcome: wright
- Bonett skewedc3_onevar · outcome: wait
- Bonett normalc3_onevar · outcome: strength
- Degenerate constantc3_variance_pairs · outcome: x
- Degenerate n1c3_variance_pairs · outcome: x
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Assess variance: Levene, Brown–Forsythe · Statistics Guide · A — Describe data
What you need
- Measurementnumeric · 1 column
- The values whose spread is compared with the target.
Choices you make
hypothesis
- Target standard deviationdefault 1
The standard deviation the null hypothesis assumes (a specification limit or a historical value), in the data's units.
- Alternative hypothesisdefault two-sided
Decide the direction before looking at the data.
- SD ≠ target(default) — The spread may be larger or smaller than the target.
- SD > target — One-sided: the spread exceeds the target (e.g. a precision specification is violated).
- SD < target — One-sided: the spread is below the target.
- Confidence leveldefault 0.95
Confidence level of the interval for the standard deviation.
statistics
- Testdefault chisq
The chi-square test is exact only for normal data; Bonett's test keeps its error rate with skewed or heavy-tailed data.
- Chi-square test(default) — (n − 1)s²/σ₀² against χ² with n − 1 df; exact under normality, unreliable otherwise.
- Bonett's test (robust) — Adjusts the log-variance interval for the sample kurtosis; needs at least five values.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Normality
Shapiro–Wilk; the chi-square test needs normal data even in large samples, Bonett's test does not.
- If violated → Bonett's test — Adjusts the interval for the sample's kurtosis, so it keeps its error rate with non-normal data.
Independent observations
Each value is a separate unit; autocorrelated series understate or overstate the spread.
What it reports
- test
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- statistic
- One test of "every component null holds" from several independent tests' p-values.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- n
- How many independent units the analysis used; it sets precision and power.
- sd
- The typical distance of values from their mean, in the data's own units.
- variance
- The average squared distance from the mean; the SD squared.
- sigma0
- The typical distance of values from their mean, in the data's own units.
- sd_ratio_null
- Sample SD divided by the hypothesized SD. 1 means the spread matches the null value; above 1 means more spread.
- method_label
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
Per group, level or term: df, sd_ci_high, sd_ci_low, ci_low, ci_high (when finite), kurtosis (Bonett's test)
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Bonett's p-value is the smallest α whose interval excludes the target, found by the same 200-step bisection in both engines (Minitab reports the same quantity).
The exact script CodeSplash ran for example “Chisq guide” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# One-sample variance test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method variance.one_sample 1.0.1 · spec b304bd5c1fa82d04
# Dataset: c3_variance_pairs (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import spread
# %% Data
df = pd.read_parquet("tests/parity/fixtures/c3_variance_pairs.parquet", columns=["x"])
n_input = len(df)
df = df.dropna(subset=["x"]) # listwise deletion over the analysis columns
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, ["x"]) # infinite values stop the run (registry/errors.yaml)
# %% Options
y = "x"
sigma0 = float(1)
test = "chisq" or "chisq"
alternative = "two-sided" or "two-sided"
conf_level = float(0.95 or 0.95)
# %% Test
x = df[y].to_numpy(dtype=float)
if len(x) < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="A one-sample variance test", min=2, n=len(x))
if len(np.unique(x)) < 2: # a sample variance of 0: the tests' normal (or kurtosis) model breaks down
cs.cs_error("CS_E_CONSTANT", column=y)
res = spread.variance_one_sample(x, sigma0, test, alternative=alternative, conf_level=conf_level)
warnings.extend(res["warnings"])
n, s, stat, p, name = res["n"], res["sd"], float(res["statistic"]), float(res["p"]), res["label"]
# %% Assumptions
if 3 <= n <= 5000:
sw_p = float(stats.shapiro(x).pvalue)
if sw_p < 0.05 and test == "chisq":
status, detail = "warn", f"Shapiro–Wilk p = {sw_p:.3f}: the chi-square test is not reliable for non-normal data, even with many values; prefer Bonett's test."
elif sw_p < 0.05:
status, detail = "info", f"Shapiro–Wilk p = {sw_p:.3f}; Bonett's test does not assume normality."
else:
status, detail = "pass", f"Shapiro–Wilk p = {sw_p:.3f}."
else:
status, detail = "info", "Too few (or too many) values for Shapiro–Wilk; inspect the distribution."
assumptions = [{"key": "normality", "label": "Normality", "status": status, "detail": detail}]
# %% Result
dir_text = {"two-sided": "differs from", "greater": "exceeds", "less": "is below"}[alternative]
verdict = (f"The spread {dir_text} the target ({cs.fmt_p(p)})." if p < 0.05
else f"No evidence that the spread {dir_text} the target ({cs.fmt_p(p)}).")
summary = f"The SD of {y} is {s:.4g} over {n} values against a target of {sigma0:g}. {name}: {verdict}"
values = {"test": test, "statistic": stat, "p": p, "n": n, "sd": s, "variance": res["variance"], "sigma0": sigma0,
"sd_ratio_null": res["sd_ratio_null"], "method_label": name}
for key in ("df", "ci_low", "ci_high", "sd_ci_low", "sd_ci_high", "kurtosis"):
v = res.get(key)
if v is not None and math.isfinite(v):
values[key] = float(v)
if test == "chisq":
apa = f"χ²({res['df']:g}) = {cs.fmt_num(stat)}, {cs.fmt_p(p)}"
statistics = [{"key": "statistic", "label": "χ²", "value": stat}, {"key": "df", "label": "df", "value": res["df"]}]
else:
apa = f"Bonett's test, z = {cs.fmt_num(stat)}, {cs.fmt_p(p)}"
statistics = [{"key": "statistic", "label": "z (log variance)", "value": stat}]
statistics.append({"key": "p", "label": "p", "value": p, "format": "p"})
sd_ci = {"key": "sd", "label": "Standard deviation", "value": s, "method": name}
if math.isfinite(res["sd_ci_high"]):
sd_ci.update({"ciLow": res["sd_ci_low"], "ciHigh": res["sd_ci_high"], "ciLevel": conf_level})
notes = [f"Target SD {sigma0:g} (variance {sigma0**2:g})."]
if test == "bonett":
notes.append("Bonett's p-value is the smallest α at which the kurtosis-adjusted interval excludes the target variance.")
chart_rows = np.unique(np.round(np.linspace(0, len(df) - 1, min(len(df), 5000))).astype(int))
cs.publish({
"method": "variance.one_sample",
"methodVersion": "1.0.1",
"title": name,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": apa,
"statistics": statistics,
"tables": [{
"key": "interval", "title": f"{conf_level:.0%} interval",
"columns": [{"key": "quantity", "label": "Quantity", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
{"key": "low", "label": "Lower", "type": "number"}, {"key": "high", "label": "Upper", "type": "number"}],
"rows": [
{"quantity": "Standard deviation", "estimate": s, "low": res["sd_ci_low"],
"high": res["sd_ci_high"] if math.isfinite(res["sd_ci_high"]) else None},
{"quantity": "Variance", "estimate": res["variance"], "low": res["ci_low"],
"high": res["ci_high"] if math.isfinite(res["ci_high"]) else None},
],
}],
"effectSizes": [sd_ci],
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"charts": [cs.chart("distribution", "histogram", f"Distribution of {y}", {"x": cs.col(y, x[chart_rows])})],
"values": values,
})
The exact script CodeSplash ran for example “Chisq guide” · R version 4.5.1 (2025-06-13)
# One-sample variance test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method variance.one_sample 1.0.1 · spec b304bd5c1fa82d04
# Dataset: c3_variance_pairs (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/c3_variance_pairs.parquet", col_select = c("x")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("x")]), , 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("x")) # infinite values stop the run (registry/errors.yaml)
# %% Options
y <- "x"
`%||%` <- function(a, b) if (is.null(a)) b else a
sigma0 <- as.double(1)
test <- "chisq" %||% "chisq"
alternative <- "two-sided" %||% "two-sided"
conf_level <- as.double(0.95 %||% 0.95)
# %% Test
x <- as.double(df[[y]])
if (length(x) < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "A one-sample variance test", min = 2, n = length(x))
if (length(unique(x)) < 2) cs_error("CS_E_CONSTANT", column = y) # a sample variance of 0: the tests' model breaks down
res <- cs_variance_one_sample(x, sigma0, test, alternative = alternative, conf_level = conf_level)
warnings <- c(warnings, res$warnings)
n <- res$n
s <- res$sd
stat <- res$statistic
p <- res$p
name <- res$label
# %% Assumptions
if (n >= 3 && n <= 5000) {
sw_p <- stats::shapiro.test(x)$p.value
if (sw_p < 0.05 && test == "chisq") {
status <- "warn"
detail <- sprintf("Shapiro–Wilk p = %.3f: the chi-square test is not reliable for non-normal data, even with many values; prefer Bonett's test.", sw_p)
} else if (sw_p < 0.05) {
status <- "info"
detail <- sprintf("Shapiro–Wilk p = %.3f; Bonett's test does not assume normality.", sw_p)
} else {
status <- "pass"
detail <- sprintf("Shapiro–Wilk p = %.3f.", sw_p)
}
} else {
status <- "info"
detail <- "Too few (or too many) values for Shapiro–Wilk; inspect the distribution."
}
assumptions <- list(list(key = "normality", label = "Normality", status = status, detail = detail))
# %% Result
dir_text <- switch(alternative, "two-sided" = "differs from", greater = "exceeds", less = "is below")
verdict <- if (p < 0.05) sprintf("The spread %s the target (%s).", dir_text, cs_fmt_p(p)) else
sprintf("No evidence that the spread %s the target (%s).", dir_text, cs_fmt_p(p))
summary <- sprintf("The SD of %s is %s over %d values against a target of %s. %s: %s", y, formatC(s, digits = 4, format = "g"),
n, format(sigma0), name, verdict)
values <- list(test = test, statistic = stat, p = p, n = n, sd = s, variance = res$variance, sigma0 = sigma0,
sd_ratio_null = res$sd_ratio_null, method_label = name)
for (key in c("df", "ci_low", "ci_high", "sd_ci_low", "sd_ci_high", "kurtosis")) {
v <- res[[key]]
if (!is.null(v) && is.finite(v)) values[[key]] <- v
}
if (test == "chisq") {
apa <- sprintf("χ²(%s) = %s, %s", format(res$df), cs_fmt_num(stat), cs_fmt_p(p))
statistics <- list(list(key = "statistic", label = "χ²", value = stat), list(key = "df", label = "df", value = res$df))
} else {
apa <- sprintf("Bonett's test, z = %s, %s", cs_fmt_num(stat), cs_fmt_p(p))
statistics <- list(list(key = "statistic", label = "z (log variance)", value = stat))
}
statistics <- c(statistics, list(list(key = "p", label = "p", value = p, format = "p")))
sd_ci <- list(key = "sd", label = "Standard deviation", value = s, method = name)
if (is.finite(res$sd_ci_high)) {
sd_ci$ciLow <- res$sd_ci_low
sd_ci$ciHigh <- res$sd_ci_high
sd_ci$ciLevel <- conf_level
}
notes <- list(sprintf("Target SD %s (variance %s).", format(sigma0), format(sigma0^2)))
if (test == "bonett") {
notes <- c(notes, list("Bonett's p-value is the smallest α at which the kurtosis-adjusted interval excludes the target variance."))
}
fin <- function(v) if (is.finite(v)) v else NA_real_
chart_rows <- unique(round(seq(1, nrow(df), length.out = min(nrow(df), 5000))))
cs_publish(list(
method = "variance.one_sample",
methodVersion = "1.0.1",
title = name,
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = apa,
statistics = statistics,
tables = list(list(
key = "interval", title = sprintf("%s%% interval", format(round(conf_level * 100))),
columns = list(list(key = "quantity", label = "Quantity", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
list(key = "low", label = "Lower", type = "number"), list(key = "high", label = "Upper", type = "number")),
rows = data.frame(quantity = c("Standard deviation", "Variance"), estimate = c(s, res$variance),
low = c(res$sd_ci_low, res$ci_low), high = c(fin(res$sd_ci_high), fin(res$ci_high)))
)),
effectSizes = list(sd_ci),
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = list(cs_chart("distribution", "histogram", sprintf("Distribution of %s", y), list(x = cs_col(y, x[chart_rows])))),
values = values
))
Sources
- NIST/SEMATECH e-Handbook of Statistical Methods, §1.3.5.8 Chi-square test for the variance.
- Bonett, D. G. (2006). Approximate confidence interval for standard deviation of nonnormal distributions. Computational Statistics & Data Analysis, 50, 775–782.
From the CodeSplash method registry · variance.one_sample v1.0.1.