Bayesian updating
Bayes' rule turns a prior belief and data into a posterior belief. For the conjugate pairs the posterior stays in the prior's family and its parameters are sums of the data, so updating is exact arithmetic. Means, variances and predictive probabilities are fractions; credible intervals are certified quantiles.
A probability: beta and binomial
import { betaPrior } from "@ratmath/stats";
const prior = betaPrior(1, 1); // uniform on [0, 1]
const post = prior.update({ successes: 7, trials: 10 });
String(post); // "Beta(8, 4): mean 0.666667"
post.mean; // 2/3
post.mode; // 7/10, the maximum-likelihood estimate
post.interval("0.95"); // certified enclosures of the 2.5% and 97.5% quantiles
post.predictive(3).table; // [5/91, 20/91, 36/91, 30/91]: successes in the next 3 trials
With prior density proportional to and successes in trials, the posterior is proportional to
which is . Updating twice is updating once with the pooled data, and the order does not matter: the test suite checks both. The predictive law of the next trials is beta-binomial, , with rising factorials, exact.
A rate: gamma with Poisson or exponential data
import { gammaPrior } from "@ratmath/stats";
const calls = gammaPrior(2, 1).update([3, 4, 2, 5]); // calls per hour in four hours
String(calls); // "Gamma(shape 16, rate 5): mean 3.200000"
calls.predictive().pmf(3); // the chance of exactly 3 calls next hour, exact
const life = gammaPrior(1, 1, { likelihood: "exponential" }).update([0.5, 1.5]);
life.params; // { shape: 3, rate: 3 }
For Poisson counts the posterior of a prior is ; for exponential waiting times it is . The predictive law of the next Poisson count is negative binomial.
A mean: normal with known variance
import { normalPrior } from "@ratmath/stats";
const m = normalPrior(0, { variance: 4, dataVariance: 1 }).update([1.2, 0.8, 1.0, 1.4]);
m.variance; // 4/17: precisions add, 1/4 + 4/1 = 17/4
m.mean; // 88/85: the precision-weighted average of 0 and the sample mean 11/10
The more data, the more the posterior mean follows the sample and the less the prior.
Several categories: Dirichlet and multinomial
import { dirichletPrior } from "@ratmath/stats";
const d = dirichletPrior({ red: 1, green: 1, blue: 1 }).update({ red: 5, green: 2 });
d.mean; // { red: 3/5, green: 3/10, blue: 1/10 }
d.marginal("red"); // Beta(6, 4): the belief about red alone
Each category's weight grows by its count; the marginal belief about one category's probability is a beta distribution, so its credible interval comes from marginal(category).interval().
@ratmath/stats and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.