Skip to content

Class: Statistics ​

Descriptive statistics, regressions, distributions and random sampling on arrays of numbers, as static methods (the simple-statistics library). The methods do not modify the arrays given; the ones needing a sorted array copy it first. Most of them throw an Error for an empty array (or too short: two numbers for the sample variance), and propagate NaN.

Example ​

typescript
import {Statistics} from 'lakutata/utils'

const latencies: number[] = [12, 15, 11, 90, 14, 13]
console.log(Statistics.mean(latencies), Statistics.median(latencies), Statistics.quantile(latencies, 0.9))
//25.833333333333332 13.5 90
console.log(Statistics.min(latencies), Statistics.max(latencies), Statistics.standardDeviation(latencies).toFixed(2))
//11 90 28.73
//A trend: y = 2x + 1
console.log(Statistics.linearRegression([[0, 1], [2, 5]]))
//{m: 2, b: 1}

Constructors ​

Constructor ​

new Statistics(): Statistics

Returns ​

Statistics

Properties ​

epsilon ​

static epsilon: number

The stopping tolerance of the iterative computations (binomialDistribution, poissonDistribution, the default tolerance of approxEqual): 0.0001. Changing it has no effect on them: they read their own copy.

Methods ​

addToAverage() ​

static addToAverage(average, n, newValue): number

Update a mean with a new value; the same as addToMean.

Parameters ​

average ​

number

The current mean.

n ​

number

The count of numbers the mean was computed from.

newValue ​

number

The number added.

Returns ​

number

The mean of the n + 1 numbers.


addToMean() ​

static addToMean(mean, n, newValue): number

Update a mean with a new value, without the list it was computed from: (mean * n + newValue) / (n + 1).

Parameters ​

mean ​

number

The current mean.

n ​

number

The count of numbers the mean was computed from.

newValue ​

number

The number added.

Returns ​

number

The mean of the n + 1 numbers.


approxEqual() ​

static approxEqual(actual, expected, tolerance): boolean

Tell whether a number is close to an expected one, by their relative difference: |actual - expected| / |expected| at most tolerance (two zeros are equal; an expected 0 with any other value is not).

Parameters ​

actual ​

number

The number to check.

expected ​

number

The expected number.

tolerance ​

number

The largest relative difference (0.01 is 1%). The type requires it; undefined gives epsilon.

Returns ​

boolean

true when the numbers are close enough.


average() ​

static average(x): number

Get the arithmetic mean of an array; the same as mean.

Parameters ​

x ​

number[]

The numbers.

Returns ​

number

The mean.

Throws ​

When x is empty.


bernoulliDistribution() ​

static bernoulliDistribution(p): number[]

Get the Bernoulli distribution of a probability: the probabilities of a failure (0) and of a success (1) of one trial, such as a coin toss.

Parameters ​

p ​

number

The probability of success, from 0 to 1.

Returns ​

number[]

[1 - p, p].

Throws ​

When p is out of 0 to 1.


binomialDistribution() ​

static binomialDistribution(trials, probability): number[] | undefined

Get the binomial distribution: the probabilities of 0, 1, 2… successes in a number of independent trials. The list stops once the probabilities add up to 1 - epsilon, so it may be shorter than trials + 1.

Parameters ​

trials ​

number

The number of trials, a positive integer.

probability ​

number

The probability of success of each trial, from 0 to 1.

Returns ​

number[] | undefined

The probability of each count of successes, by count; undefined when trials is not a positive integer or probability is out of 0 to 1.


bisect() ​

static bisect(func, start, end, maxIterations, errorTolerance): number

Find a root of a function (an x where it is 0) by bisection: the interval is halved, keeping the half where the function changes sign, until it is small enough. The function should change sign between start and end; when it does not, a bound is returned rather than an error.

Parameters ​

func ​

(x) => number

The function, of a number.

start ​

number

The lower bound of the interval.

end ​

number

The upper bound of the interval.

maxIterations ​

number

The most halvings before giving up.

errorTolerance ​

number

The half-width of the interval at which it stops.

Returns ​

number

The approximate root.

Throws ​

When the root is not found in maxIterations halvings (maximum number of iterations exceeded).


chunk() ​

static chunk(x, chunkSize): number[][]

Split an array into chunks of a given size, the last one smaller when the length is not a multiple of it (as PHP's array_chunk).

Parameters ​

x ​

number[]

The items; an empty array gives [].

chunkSize ​

number

The size of the chunks, a positive integer.

Returns ​

number[][]

A new array of chunks.

Throws ​

When chunkSize is not a positive integer.


coefficientOfVariation() ​

static coefficientOfVariation(x): number

Get the coefficient of variation of an array: its sample standard deviation divided by its mean, a spread without unit to compare series of different scales.

Parameters ​

x ​

number[]

The numbers, at least two.

Returns ​

number

The coefficient of variation; an infinity when the mean is 0.

Throws ​

When x has fewer than two numbers.


combinations() ​

static combinations(x, k): number[][]

List the combinations of k items of an array: its subsets of k items, regardless of order.

Parameters ​

x ​

number[]

The items to combine.

k ​

number

The size of the combinations: 0 gives the single empty combination [[]]; more than the length of x, a negative or fractional size gives [].

Returns ​

number[][]

The combinations, each an array of k items.


combinationsReplacement() ​

static combinationsReplacement(x, k): number[][]

List the combinations with replacement of k items of an array: the multisets of k items, an item possibly repeated, regardless of order.

Parameters ​

x ​

number[]

The items to combine.

k ​

number

The size of the combinations: 0 gives the single empty combination [[]]; a negative or fractional size gives [].

Returns ​

number[][]

The combinations, each an array of k items.


combineMeans() ​

static combineMeans(mean1, n1, mean2, n2): number

Get the mean of two lists merged, from their means and counts, without the lists.

Parameters ​

mean1 ​

number

The mean of the first list.

n1 ​

number

The count of numbers of the first list.

mean2 ​

number

The mean of the second list.

n2 ​

number

The count of numbers of the second list.

Returns ​

number

The mean of the n1 + n2 numbers.


combineVariances() ​

static combineVariances(variance1, mean1, n1, variance2, mean2, n2): number

Get the population variance of two lists merged, from their population variances, means and counts, without the lists.

Parameters ​

variance1 ​

number

The population variance of the first list.

mean1 ​

number

The mean of the first list.

n1 ​

number

The count of numbers of the first list.

variance2 ​

number

The population variance of the second list.

mean2 ​

number

The mean of the second list.

n2 ​

number

The count of numbers of the second list.

Returns ​

number

The population variance of the n1 + n2 numbers.


correlation() ​

static correlation(x, y): number

Get the sample correlation of two arrays (Pearson's r): from -1 (one goes down when the other goes up) to 1 (they go up together), 0 without linear relation.

Parameters ​

x ​

number[]

The first numbers.

y ​

number[]

The second numbers, as many as x.

Returns ​

number

The correlation; NaN when either array has all its numbers equal.

Throws ​

When the arrays have different lengths, or fewer than two numbers.


cumulativeStdLogisticProbability() ​

static cumulativeStdLogisticProbability(x): number

Compute the cumulative distribution function of the standard logistic distribution: 1 / (1 + e^-x), the sigmoid.

Parameters ​

x ​

number

The value.

Returns ​

number

The probability, from 0 to 1 (0.5 for 0).

See ​

https://en.wikipedia.org/wiki/Logistic_distribution


extent() ​

static extent(x): [number, number]

Get the smallest and the largest numbers of an array in one pass.

Parameters ​

x ​

number[]

The numbers.

Returns ​

[number, number]

[min, max].

Throws ​

When x is empty.


factorial() ​

static factorial(n): number

Compute the factorial of an integer: n! = 1 * 2 * … * n, with 0! = 1.

Parameters ​

n ​

number

A non-negative integer. Beyond 170 the result is Infinity, and beyond 18 it is not exact.

Returns ​

number

n!.

Throws ​

When n is negative or not an integer.


gamma() ​

static gamma(n): number

Compute the gamma function (Nemes' approximation): gamma(n) = (n - 1)! for the positive integers, extended to the real numbers.

Parameters ​

n ​

number

The value. Zero and the negative integers give NaN; beyond about 171 the result is Infinity.

Returns ​

number

The gamma of n (gamma(0.5) is √π, 1.7724538…), to about 10 significant digits.


gammaln() ​

static gammaln(n): number

Compute the natural logarithm of the gamma function (Lanczos' approximation), for the values too large for gamma (beyond 171).

Parameters ​

n ​

number

The value, positive; zero and the negative values give Infinity.

Returns ​

number

ln(gamma(n)).


geometricMean() ​

static geometricMean(x): number

Get the geometric mean of an array: the n-th root of the product of its n numbers, the mean suited to growth rates (the mean of the factors 1.8, 1.17 and 1.43 gives the constant yearly growth with the same result).

Parameters ​

x ​

number[]

The numbers, none negative.

Returns ​

number

The geometric mean.

Throws ​

When x is empty, or a number is negative.


harmonicMean() ​

static harmonicMean(x): number

Get the harmonic mean of an array: the reciprocal of the mean of the reciprocals, the mean suited to rates (speeds, prices per unit).

Parameters ​

x ​

number[]

The numbers, all positive.

Returns ​

number

The harmonic mean.

Throws ​

When x is empty, or a number is zero or negative.


interquartileRange() ​

static interquartileRange(x): number

Get the interquartile range of an array: the third quartile minus the first one, the spread of its middle half.

Parameters ​

x ​

number[]

The numbers.

Returns ​

number

The interquartile range.

Throws ​

When x is empty.


jenks() ​

static jenks(data, nClasses): number[] | null

Find the Jenks natural breaks of an array: the class bounds which minimize the variance within the classes, used to group the values of a choropleth map or a histogram.

Parameters ​

data ​

number[]

The numbers (copied before they are sorted).

nClasses ​

number

The count of classes, at most the length of data.

Returns ​

number[] | null

The nClasses + 1 bounds, from the smallest number to the largest; null when nClasses is greater than the length of data.


linearRegression() ​

static linearRegression(data): LinearRegression

Fit a line to points by least squares: the slope m and the intercept b of y = mx + b.

Parameters ​

data ​

[number, number][]

The points, as [x, y] pairs ([[0, 1], [1, 3], [2, 5]]). A single point gives a horizontal line through it; points all at the same x give NaN.

Returns ​

LinearRegression

The slope and the intercept.


linearRegressionLine() ​

static linearRegressionLine(mb): (x) => number

Turn the result of linearRegression into a function giving the y of an x on the line.

Parameters ​

mb ​

LinearRegression

The slope m and the intercept b.

Returns ​

The function x => m * x + b.

(x) => number


logAverage() ​

static logAverage(x): number

Get the geometric mean of an array through the logarithms (the exponential of the mean logarithm), which avoids the overflow of the product of large or many numbers.

Parameters ​

x ​

number[]

The numbers, none negative.

Returns ​

number

The geometric mean.

Throws ​

When x is empty, or a number is negative.


logit() ​

static logit(p): number

Compute the logit of a probability: ln(p / (1 - p)), the inverse of cumulativeStdLogisticProbability.

Parameters ​

p ​

number

The probability, strictly between 0 and 1.

Returns ​

number

The log-odds (0 for 0.5).

Throws ​

When p is not strictly between 0 and 1.

See ​

https://en.wikipedia.org/wiki/Logit


max() ​

static max(x): number

Get the largest number of an array, in linear time.

Parameters ​

x ​

number[]

The numbers. A NaN among them gives NaN.

Returns ​

number

The largest number.

Throws ​

When x is empty.


mean() ​

static mean(x): number

Get the arithmetic mean of an array: the sum of its numbers divided by their count.

Parameters ​

x ​

number[]

The numbers. A NaN among them gives NaN.

Returns ​

number

The mean.

Throws ​

When x is empty.


median() ​

static median(x): number

Get the median of an array: its middle number once sorted, or the mean of the two middle numbers for an even count. Less sensitive to the outliers than the mean. The array is copied before it is sorted.

Parameters ​

x ​

number[]

The numbers.

Returns ​

number

The median.

Throws ​

When x is empty.


medianAbsoluteDeviation() ​

static medianAbsoluteDeviation(x): number

Get the median absolute deviation of an array: the median of the distances to the median, a measure of the spread more robust to the outliers than the standard deviation.

Parameters ​

x ​

number[]

The numbers.

Returns ​

number

The median absolute deviation.

Throws ​

When x is empty.


min() ​

static min(x): number

Get the smallest number of an array, in linear time.

Parameters ​

x ​

number[]

The numbers. A NaN among them gives NaN.

Returns ​

number

The smallest number.

Throws ​

When x is empty.


mode() ​

static mode(x): number

Get the mode of an array: the number which appears most often. On a tie, the smallest of the most frequent numbers. Runs in O(n log n) (the array is copied and sorted).

Parameters ​

x ​

number[]

The numbers.

Returns ​

number

The most frequent number.

Throws ​

When x is empty.


poissonDistribution() ​

static poissonDistribution(lambda): number[] | undefined

Get the Poisson distribution of a rate: the probabilities of 0, 1, 2… events in an interval, for events happening independently at a known mean rate. The list stops once the probabilities add up to 1 - epsilon.

Parameters ​

lambda ​

number

The mean count of events in the interval, positive.

Returns ​

number[] | undefined

The probability of each count of events, by count; undefined when lambda is zero or negative.


probit() ​

static probit(p): number

Compute the probit of a probability: the quantile of the standard normal distribution, the number of standard deviations below which a fraction p of normal values fall (probit(0.975) is about 1.96).

Parameters ​

p ​

number

The probability, from 0 to 1. It is not validated: 0 and the values from 1 up are clamped to epsilon and 1 - epsilon (giving about -3.71 and 3.71), and a negative value gives NaN.

Returns ​

number

The quantile.


product() ​

static product(x): number

Multiply the numbers of an array.

Parameters ​

x ​

number[]

The numbers; an empty array gives 1.

Returns ​

number

The product.


quantile() ​

static quantile(x, p): number

Get a quantile of an array: the value below which a fraction p of the numbers fall (0.5 is the median, 0.25 the first quartile). Between two numbers, the quantile is their mean. The array is copied before it is sorted.

Parameters ​

x ​

number[]

The numbers.

p ​

number

The fraction, from 0 to 1.

Returns ​

number

The quantile.

Throws ​

When x is empty, or when p is out of 0 to 1.


quantileRank() ​

static quantileRank(x, value): number

Get the quantile rank of a value in an array: the fraction of the numbers below it, from 0 to 1 (the mean rank when the value appears several times). The array is copied before it is sorted.

Parameters ​

x ​

number[]

The numbers; an empty array gives NaN.

value ​

number

The value to rank: below all the numbers gives 0, above all 1.

Returns ​

number

The quantile rank.


quickselect() ​

static quickselect(arr, k, left?, right?): number[]

Partially sort a copy of an array so that its k-th item (from 0) is the one a full sort would put there, the smaller items before it and the larger after it, in linear time on average (Floyd-Rivest). Faster than a sort to get the k smallest numbers. The array given is not modified.

Parameters ​

arr ​

number[]

The numbers.

k ​

number

The index to place, from 0.

left? ​

number

The first index of the range to partition; 0 by default.

number

The last index of the range to partition; the last index of the array by default (0 is taken as the default too).

Returns ​

number[]

The partially sorted copy.


randomPickMany() ​

static randomPickMany(x, n): number[]

Pick numbers of an array at random, each item once at most; the same as sample.

Parameters ​

x ​

number[]

The numbers.

n ​

number

The count of numbers picked; more than the length of x gives all of them (shuffled).

Returns ​

number[]

A new array of n numbers at most.


randomPickOne() ​

static randomPickOne(x): number

Pick one number of an array at random.

Parameters ​

x ​

number[]

The numbers.

Returns ​

number

A number of x; undefined when x is empty (despite the return type).


rootMeanSquare() ​

static rootMeanSquare(x): number

Get the root mean square of an array: the square root of the mean of the squares, the magnitude of the numbers whatever their sign.

Parameters ​

x ​

number[]

The numbers.

Returns ​

number

The root mean square.

Throws ​

When x is empty.


rSquared() ​

static rSquared(data): number

Get the coefficient of determination (R²) of the least squares line of points: how well the line fits them, from 1 (all the points on the line) down (0: no better than their mean). It is computed against the line given by linearRegression.

Parameters ​

data ​

[number, number][]

The points, as [x, y] pairs ([[0, 1], [1, 3], [2, 5]]). Fewer than two points give 1.

Returns ​

number

The R² of the line.


sample() ​

static sample(x, n): number[]

Draw numbers from an array at random, without replacement: each item is drawn once at most, in a random order.

Parameters ​

x ​

number[]

The numbers to draw from.

n ​

number

The count of numbers drawn; more than the length of x gives all of them (shuffled).

Returns ​

number[]

A new array of n numbers at most.


sampleCovariance() ​

static sampleCovariance(x, y): number

Get the sample covariance of two arrays: how much they vary together (divided by n - 1). Positive when they go up together, negative when one goes down as the other goes up.

Parameters ​

x ​

number[]

The first numbers.

y ​

number[]

The second numbers, as many as x.

Returns ​

number

The sample covariance.

Throws ​

When the arrays have different lengths, or fewer than two numbers.


sampleSkewness() ​

static sampleSkewness(x): number

Get the sample skewness of an array: how much its distribution leans to one side of the mean (negative: a longer tail of small values; positive: of large values), the adjusted Fisher-Pearson coefficient of Excel, SPSS and SAS.

Parameters ​

x ​

number[]

The numbers, at least three.

Returns ​

number

The skewness; NaN when all the numbers are equal.

Throws ​

When x has fewer than three numbers.


sampleStandardDeviation() ​

static sampleStandardDeviation(x): number

Get the sample standard deviation of an array: the square root of sampleVariance.

Parameters ​

x ​

number[]

The numbers, at least two.

Returns ​

number

The sample standard deviation.

Throws ​

When x has fewer than two numbers.


sampleVariance() ​

static sampleVariance(x): number

Get the sample variance of an array: the squared deviations from the mean divided by n - 1 (Bessel's correction), the unbiased estimate of a population's variance from a sample of it.

Parameters ​

x ​

number[]

The numbers, at least two.

Returns ​

number

The sample variance.

Throws ​

When x has fewer than two numbers.


sampleWithReplacement() ​

static sampleWithReplacement(x, n): number[]

Draw numbers from an array at random, with replacement: the same item may be drawn several times.

Parameters ​

x ​

number[]

The numbers to draw from; an empty array gives [].

n ​

number

The count of numbers drawn.

Returns ​

number[]

A new array of n numbers.


shuffle() ​

static shuffle(x): number[]

Shuffle an array (Fisher-Yates, with Math.random) into a new one; the array given is not modified.

Parameters ​

x ​

number[]

The numbers.

Returns ​

number[]

A new array of the same numbers in a random order.


standardDeviation() ​

static standardDeviation(x): number

Get the population standard deviation of an array: the square root of variance. For a sample of a larger population, use sampleStandardDeviation.

Parameters ​

x ​

number[]

The numbers; a single number gives 0.

Returns ​

number

The standard deviation.

Throws ​

When x is empty.


subtractFromAverage() ​

static subtractFromAverage(mean, n, value): number

Update a mean when a value is removed; the same as subtractFromMean.

Parameters ​

mean ​

number

The current mean.

n ​

number

The count of numbers the mean was computed from; 1 gives NaN.

value ​

number

The number removed.

Returns ​

number

The mean of the n - 1 numbers.


subtractFromMean() ​

static subtractFromMean(mean, n, value): number

Update a mean when a value is removed, without the list it was computed from: (mean * n - value) / (n - 1).

Parameters ​

mean ​

number

The current mean.

n ​

number

The count of numbers the mean was computed from; 1 gives NaN.

value ​

number

The number removed.

Returns ​

number

The mean of the n - 1 numbers.


sum() ​

static sum(x): number

Add the numbers of an array, with Kahan-Babuska compensation (fewer rounding errors than a plain loop).

Parameters ​

x ​

number[]

The numbers; an empty array gives 0.

Returns ​

number

The sum.


sumNthPowerDeviations() ​

static sumNthPowerDeviations(x, n): number

Add the deviations from the mean raised to a power: n = 2 gives the sum of the squared deviations, n = 3 the sum of the cubed ones.

Parameters ​

x ​

number[]

The numbers.

n ​

number

The power.

Returns ​

number

The sum.

Throws ​

When x is empty.


tTest() ​

static tTest(x, expectedValue): number

Compute the one-sample t-statistic: how far the sample's mean is from an expected mean, in standard errors. Look it up in a t table (with x.length - 1 degrees of freedom) to get the p-value. Note: it divides by the population standard deviation of the sample (standardDeviation), not by the sample one.

Parameters ​

x ​

number[]

The sample.

expectedValue ​

number

The mean assumed by the null hypothesis.

Returns ​

number

The t-statistic; an infinity or NaN when the numbers of x are all equal (a single number included).

Throws ​

When x is empty.


tTestTwoSample() ​

static tTestTwoSample(sampleX, sampleY, difference?): number | null

Compute the two-sample t-statistic (Student's, equal variances assumed) of the hypothesis mean(sampleX) - mean(sampleY) = difference; usually difference is 0, to test whether both samples come from populations of the same mean. Look it up in a t table to get the p-value.

Parameters ​

sampleX ​

number[]

The first sample, at least two numbers.

sampleY ​

number[]

The second sample, at least two numbers.

difference? ​

number

The difference of the means assumed by the null hypothesis; 0 by default.

Returns ​

number | null

The t-statistic; null when a sample is empty.

Throws ​

When a sample has a single number.


variance() ​

static variance(x): number

Get the population variance of an array: the mean of the squared deviations from the mean (divided by n). For a sample of a larger population, use sampleVariance.

Parameters ​

x ​

number[]

The numbers; a single number gives 0.

Returns ​

number

The variance.

Throws ​

When x is empty.


zScore() ​

static zScore(x, mean, standardDeviation): number

Get the z-score of a value: how many standard deviations it is above (positive) or below (negative) the mean. It needs the population's mean and standard deviation; with a sample's ones, it is a t-statistic.

Parameters ​

x ​

number

The value.

mean ​

number

The population's mean.

standardDeviation ​

number

The population's standard deviation; 0 gives an infinity (or NaN for x at the mean).

Returns ​

number

The z-score.

Released under the MIT License.