Standard Deviation for Population and Sample
Compute population or sample standard deviation over validated numbers, with clear errors for insufficient sample sizes.
Code
export type VarianceKind = "population" | "sample";
export function standardDeviation(
values: readonly number[],
kind: VarianceKind = "population",
): number {
if (!Array.isArray(values)) throw new TypeError("values must be an array");
if (values.length === 0) throw new RangeError("values must not be empty");
if (!values.every(Number.isFinite)) {
throw new TypeError("values must be finite numbers");
}
if (kind !== "population" && kind !== "sample") {
throw new RangeError("kind must be population or sample");
}
if (kind === "sample" && values.length < 2) {
throw new RangeError("sample standard deviation needs at least two values");
}
const count = values.length;
const mean = values.reduce((total, value) => total + value, 0) / count;
const sumSquares = values.reduce((total, value) => total + (value - mean) ** 2, 0);
return Math.sqrt(sumSquares / (kind === "sample" ? count - 1 : count));
}Inside the snippet
Count the function standardDeviation as the entire surface area of Standard Deviation for Population and Sample.
Failure is loud: TypeError and RangeError aborts the current operation instead of degrading it.
What to watch for
- The guard
values.length === 0short-circuits the flow with an earlythrowwhen its condition holds.
Using it
The primary signature is export function standardDeviation( values: readonly number[], kind: VarianceKind = "population", )
The surface worth importing is standardDeviation; the helpers around it are private to the snippet.
Key statements
const sumSquares = values.reduce((total, value) => total + (value - mean) ** 2, 0);
const mean = values.reduce((total, value) => total + value, 0) / count;
throw new RangeError("sample standard deviation needs at least two values");
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Statistics CalculatorCompute count, sum, mean, median, minimum, maximum, range, variance, and standard deviation for a number list.
FAQ
- What happens on invalid input?
- The code refuses to continue: `TypeError` and `RangeError` is thrown while the state is still recoverable.
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. The file defines `standardDeviation` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.