A JavaScript implementation of descriptive, regression, and inference statistics
—
Functions for working with various probability distributions and normal distribution calculations.
import {
// Discrete distributions
bernoulliDistribution,
binomialDistribution,
poissonDistribution,
// Normal distribution
zScore,
cumulativeStdNormalProbability,
errorFunction,
inverseErrorFunction,
probit,
// Constants and tables
standardNormalTable,
chiSquaredDistributionTable
} from "simple-statistics";function bernoulliDistribution(p: number): number[];Generates probabilities for a Bernoulli distribution - a discrete distribution with two possible outcomes.
Parameters:
p: number - Probability of success (between 0 and 1)Returns: number[] - Array with [P(X=0), P(X=1)]
import { bernoulliDistribution } from "simple-statistics";
// Coin flip with 60% chance of heads
const coinFlip = bernoulliDistribution(0.6);
// [0.4, 0.6] - 40% chance tails, 60% chance headsfunction binomialDistribution(trials: number, probability: number): number[];Generates probabilities for a binomial distribution - number of successes in a fixed number of trials.
Parameters:
trials: number - Number of independent trialsprobability: number - Probability of success in each trial (0-1)Returns: number[] - Array where index i contains P(X=i)
import { binomialDistribution } from "simple-statistics";
// 10 coin flips with 50% success probability
const distribution = binomialDistribution(10, 0.5);
// distribution[0] = P(0 heads)
// distribution[5] = P(5 heads) ≈ 0.246 (most likely)
// distribution[10] = P(10 heads) ≈ 0.001
console.log(`P(exactly 5 heads): ${distribution[5]}`);function poissonDistribution(lambda: number): number[];Generates probabilities for a Poisson distribution - models number of events in a fixed interval.
Parameters:
lambda: number - Average number of events per interval (rate parameter)Returns: number[] - Array where index i contains P(X=i)
import { poissonDistribution } from "simple-statistics";
// Average 3 customers per hour
const customerArrival = poissonDistribution(3);
// customerArrival[0] = P(0 customers) ≈ 0.0498
// customerArrival[3] = P(3 customers) ≈ 0.224 (most likely)
// customerArrival[6] = P(6 customers) ≈ 0.0504
console.log(`P(exactly 2 customers): ${customerArrival[2]}`);function zScore(x: number, mean: number, standardDeviation: number): number;Calculates the z-score (standard score) - how many standard deviations a value is from the mean.
Parameters:
x: number - The value to standardizemean: number - Population meanstandardDeviation: number - Population standard deviationReturns: number - Z-score (standardized value)
import { zScore } from "simple-statistics";
// Test score analysis
const score = 85;
const classAverage = 75;
const classStdDev = 10;
const z = zScore(score, classAverage, classStdDev); // 1.0
// Score is 1 standard deviation above the meanfunction cumulativeStdNormalProbability(z: number): number;Calculates the cumulative probability for the standard normal distribution (mean=0, std=1).
Parameters:
z: number - Z-score valueReturns: number - Probability that a standard normal variable is ≤ z
import { cumulativeStdNormalProbability, zScore } from "simple-statistics";
// What percentage scored below 85?
const z = zScore(85, 75, 10); // 1.0
const percentile = cumulativeStdNormalProbability(z); // 0.841
// 84.1% of students scored below 85function errorFunction(x: number): number;Calculates the error function, fundamental to many statistical calculations.
Parameters:
x: number - Input valueReturns: number - Error function value
import { errorFunction } from "simple-statistics";
const erfValue = errorFunction(1); // 0.843...function inverseErrorFunction(x: number): number;Calculates the inverse error function.
Parameters:
x: number - Input value (between -1 and 1)Returns: number - Inverse error function value
function probit(p: number): number;Calculates the probit function (inverse of cumulative standard normal distribution).
Parameters:
p: number - Probability value (between 0 and 1)Returns: number - Z-score corresponding to the probability
import { probit } from "simple-statistics";
// What z-score corresponds to 95th percentile?
const z95 = probit(0.95); // 1.645
// 95% of values fall below z = 1.645 in standard normal distributionconst standardNormalTable: number[];Pre-calculated standard normal distribution values for quick lookup.
import { standardNormalTable } from "simple-statistics";
// Access pre-calculated values
const tableValue = standardNormalTable[0]; // Value at index 0const chiSquaredDistributionTable: Record<number, Record<number, number>>;Critical values for chi-squared distribution at various degrees of freedom and significance levels.
Usage: Access critical values by degrees of freedom and significance level.
import { chiSquaredDistributionTable } from "simple-statistics";
// Get critical value for df=5, α=0.05
const criticalValue = chiSquaredDistributionTable[5][0.05];
// Statistical testing
function chiSquaredTest(observed: number[], expected: number[], df: number, alpha = 0.05): boolean {
let chiSquared = 0;
for (let i = 0; i < observed.length; i++) {
chiSquared += Math.pow(observed[i] - expected[i], 2) / expected[i];
}
const criticalValue = chiSquaredDistributionTable[df][alpha];
return chiSquared > criticalValue; // Reject null hypothesis if true
}import {
zScore,
cumulativeStdNormalProbability,
probit
} from "simple-statistics";
// SAT scores: mean=1000, std=200
const satMean = 1000;
const satStd = 200;
// What percentile is a score of 1200?
const z1200 = zScore(1200, satMean, satStd); // 1.0
const percentile = cumulativeStdNormalProbability(z1200); // 0.841
console.log(`1200 is the ${Math.round(percentile * 100)}th percentile`);
// What score is needed for 90th percentile?
const z90th = probit(0.90); // 1.282
const score90th = satMean + (z90th * satStd); // 1256.4
console.log(`90th percentile score: ${Math.round(score90th)}`);import { zScore, cumulativeStdNormalProbability } from "simple-statistics";
// Manufacturing: parts should be 100mm ± 2mm (99.7% within spec)
const targetLength = 100;
const tolerance = 2;
const processStd = tolerance / 3; // 3-sigma process
function qualityCheck(measurement: number): string {
const z = zScore(measurement, targetLength, processStd);
const probability = cumulativeStdNormalProbability(Math.abs(z));
if (Math.abs(z) > 3) {
return `REJECT: ${measurement}mm is ${Math.abs(z).toFixed(2)} standard deviations from target`;
} else {
return `ACCEPT: Within ${(probability * 100).toFixed(1)}% confidence interval`;
}
}
console.log(qualityCheck(102.1)); // Within tolerance
console.log(qualityCheck(106.5)); // Outside toleranceimport { poissonDistribution } from "simple-statistics";
// Customer service: average 4 calls per hour
const avgCallsPerHour = 4;
const callDistribution = poissonDistribution(avgCallsPerHour);
// Staffing decisions based on probability
let cumulative = 0;
for (let calls = 0; calls < callDistribution.length; calls++) {
cumulative += callDistribution[calls];
console.log(`P(≤${calls} calls): ${(cumulative * 100).toFixed(1)}%`);
if (cumulative >= 0.95) {
console.log(`Need capacity for ${calls} calls (95% confidence)`);
break;
}
}Install with Tessl CLI
npx tessl i tessl/npm-simple-statistics