Fitting distributions
Given data and a family of distributions, which member fits? Maximum likelihood picks the parameters that make the data most probable; the method of moments matches the mean and variance. Where the answer has a closed form it is an exact fraction.
Closed forms
import { fit, show } from "@ratmath/stats";
const d = [3, 1, 4, 1, 5, 9, 2, 6];
fit(d, "normal").params; // { mu: 31/8, variance: 423/64, sigma: 2.570870… }
fit(d, "exponential").params; // { rate: 8/31 }
fit(d, "poisson").params; // { lambda: 31/8 }
fit(d, "uniform").params; // { a: 1, b: 9 }: the smallest and largest values
fit(d, "uniform", { method: "moments" }).params; // { a: −0.577878…, b: 8.327878… }
fit([2, 3, 1], "binomial", { trials: 4 }).params; // { trials: 4, p: 1/2 }
For most textbook families the likelihood equations solve in closed form: the normal mean is and its variance (dividing by , not ), the exponential rate is , the Poisson mean is . With rational data these are exact. The method of moments sets the population mean and variance equal to the sample's; for the uniform distribution that gives , which need not even contain the data, while maximum likelihood gives the range of the data.
Gamma: an equation to solve
The gamma family's moment estimates are exact, and rate . Its maximum-likelihood shape solves
with the digamma function. The left side decreases from to 0, so there is exactly one root, and it is enclosed by bisection on certified values of and (both from @ratmath/analytic). The answer is an interval of width about .
fit(d, "gamma").params; // { shape: 2.093251…, rate: 0.540194… }, certified
fit(d, "gamma", { method: "moments" }).params; // { shape: 961/423, rate: 248/423 }, exact
fit([1, 2, 4], "lognormal").params.mu; // log 2, certified: the mean of the logs
When the parameters are enclosures the result has no distribution, since the distributions take exact parameters; when they are exact, distribution is the fitted member, ready for its density, quantiles or samples.
@ratmath/stats and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.