Seeded sampling
Every random number in this library comes from a generator you seed. The same seed gives the same numbers on every machine, so a simulated result can be quoted with its seed and checked by anyone.
The generator
import { rng, normal, binomial, die } from "@ratmath/stats";
const r = rng(7); // a seed: a number or text
normal().samples(3, r); // [-0.2867212522343773, 0.890397962977404, -0.6748667246228445]
normal().samples(3, rng(7)); // the same three numbers
binomial(10, "1/3").samples(8, rng(1)); // [4, 3, 2, 4, 4, 4, 5, 4]
die().samples(8, rng(1)); // [5, 3, 1, 3, 1, 3, 3, 6]
rng is the generator of the discrete library, exported again here. Its integer draws are exact (no modulo bias), and it has int, bool(p) with an exact probability, pick, shuffle and sample. Every distribution in this library has sample(rng) for one draw and samples(n, rng) for a list.
Streams with names
const base = rng("my study");
const a = base.fork("noise"); // an independent stream
const b = base.fork("x values"); // another; neither disturbs the other or base
fork(label) derives a new generator from the seed and the label without advancing the parent. This is how simulations stay comparable. If one generator fed everything in turn, drawing one extra number early on would change every number after it. With a stream for each purpose, changing the noise leaves the values alone. Models use a stream for each part, and experiments use a stream for each run, so run 17 is the same data whether you ask for 20 runs or 2,000.
How the draws are made
A continuous draw starts from a uniform number on with 53 random bits. The normal distribution uses a pair of uniforms (the polar method), the gamma family uses Marsaglia and Tsang's method, and the rest push through the quantile function: if is the distribution function then has distribution . Discrete draws walk the cumulative sums, or add up exact Bernoulli trials.
These draws are floating-point numbers. That is the right tool for a simulation of a thousand runs, and it is why simulated results are labelled as such.
Exact draws
normal().samplesExact(2, rng(7)).map(String);
// ["-39406668679/137438953472", "-24665190495/68719476736"]
sampleExact(rng, { bits }) returns a fraction: a uniform fraction with bits random bits is pushed through the certified quantile, and the result is rounded to a fraction within of it, relative to its size. It is much slower, and it gives data whose exact statistics (a mean as a fraction, an exact permutation test) are the same on every machine and in every language that implements the same rule.
@ratmath/stats and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.