Skip to main content
Module

x/statistics/src/harmonic_mean.ts

Deno basic statistics module.
Latest
File
/** * The [Harmonic Mean](https://en.wikipedia.org/wiki/Harmonic_mean) is * a mean function typically used to find the average of rates. * This mean is calculated by taking the reciprocal of the arithmetic mean * of the reciprocals of the input numbers. * * This is a [measure of central tendency](https://en.wikipedia.org/wiki/Central_tendency): * a method of finding a typical or central value of a set of numbers. * * This runs on `O(n)`, linear time in respect to the array. * * @param {number[]} x sample of one or more data points * @returns {number} harmonic mean * @throws {Error} if x is empty * @throws {Error} if x contains a negative number * @example * harmonicMean([2, 3]).toFixed(2) // => '2.40' */export function harmonicMean(x: number[]): number { if (!x.length) { throw new Error("harmonicMean requires at least one data point"); }
let reciprocalSum = 0;
for (let i = 0; i < x.length; i++) { // the harmonic mean is only valid for positive numbers if (x[i] <= 0) { throw new Error( "harmonicMean requires only positive numbers as input" ); }
reciprocalSum += 1 / x[i]; }
// divide n by the the reciprocal sum return x.length / reciprocalSum;}