Exact

Finite probability

A finite distribution is a list of outcomes with a fraction for each. Events are functions of the outcome, and probabilities, conditional probabilities and expectations are sums of fractions, with nothing rounded.

Sample spaces

import { finite, die, dice, coin, deck, draw, bayes } from "@ratmath/stats";

const two = dice(2);                           // 36 outcomes, each a pair [a, b]
two.prob(([a, b]) => a + b === 7);             // 1/6
two.prob(([a, b]) => a + b >= 10, ([a]) => a === 6);   // 1/2: given that the first die shows 6

String(coin("2/3"));                           // "{ H: 2/3, T: 1/3 }"
String(finite(["a", "b", "b"]));               // "{ a: 1/3, b: 2/3 }": repeats count each time
String(finite({ red: "1/2", green: "1/3", blue: "1/6" }));

finite takes a list of equally likely outcomes, a list with weights, an object or a Map of probabilities, or a family from the discrete library (every permutation, every subset, and so on). Probabilities that do not add up to 1 are refused unless you pass { normalize: true }.

An outcome can be a number, text, or a list of these. An event is a function from the outcome to true or false, a single outcome, or a Set of outcomes.

New distributions from old

const sum = two.map(([a, b]) => a + b);        // the distribution of the total
String(sum);    // "{ 2: 1/36, 3: 1/18, 4: 1/12, 5: 1/9, 6: 5/36, 7: 1/6, 8: 5/36, … }"

die().sumOf(3).prob((s) => s >= 16);           // 5/108, without listing the 216 triples
two.given(([a, b]) => a !== b);                // the distribution after conditioning
die().product(coin());                         // pairs [face, side], independent
draw(deck(), 2).size;                          // 1326 two-card hands, each equally likely

map sends each outcome through a function and adds up the probabilities that land together: that is the distribution of a random variable. given keeps the outcomes of an event and divides by its probability,

P(A∣B)=P(A∩B)P(B), P(A \mid B) = \frac{P(A \cap B)}{P(B)},

and refuses when P(B)=0P(B) = 0. draw(items, k) lists hands of kk distinct items; with { ordered: true } the order drawn matters, and with { replace: true, ordered: true } items are put back. A listed distribution is limited to two million outcomes; for five-card hands, count with hypergeometric instead of listing. Products such as dice(9) are not listed at all: they keep their independent parts and stream when needed (see Many dice).

Expectation and spread

two.mean(([a, b]) => a + b);                   // 7
two.variance(([a, b]) => a + b);               // 35/6
show(two.sd(([a, b]) => a + b), 10);           // "2.4152294577": a square root, so certified
two.independent(([a]) => a % 2 === 0, ([a, b]) => a + b === 7);   // true
sum.quantile("9/10");                          // 10

The mean of ff is ∑ωf(ω) P(ω)\sum_\omega f(\omega)\,P(\omega) and the variance is E[f2]−E[f]2E[f^2] - E[f]^2, both exact. A standard deviation is exact when the variance is a perfect square and an enclosure otherwise. Two events are independent when P(A∩B)=P(A) P(B)P(A \cap B) = P(A)\,P(B) holds as an equation between fractions, which floating point cannot check.

Bayes' rule

// 1 person in 100 has the condition; the test is right 95 times in 100 either way
const b = bayes({ sick: "1/100", well: "99/100" }, { sick: "95/100", well: "5/100" });
String(b.posterior);      // "{ sick: 19/118, well: 99/118 }"
b.evidence;               // 59/1000: the chance of a positive result

For hypotheses HiH_i with priors P(Hi)P(H_i) and an observation DD,

P(Hi∣D)=P(D∣Hi) P(Hi)∑jP(D∣Hj) P(Hj). P(H_i \mid D) = \frac{P(D \mid H_i)\,P(H_i)}{\sum_j P(D \mid H_j)\,P(H_j)}.

The denominator is evidence, and table has one row per hypothesis with its prior, likelihood, joint probability and posterior. The posterior is a finite distribution, so it can be the prior of the next update.

Try itEdit the code and run it with @ratmath/stats and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs