Standard Deviation for Population and Sample

Compute population or sample standard deviation over validated numbers, with clear errors for insufficient sample sizes.

TypescriptData Integrity

Code

typescriptsnippet
22 lines
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 === 0 short-circuits the flow with an early throw when 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

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.