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

snippet
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));
}