Reference
Reference
Every export, grouped by subject. Wherever a number is expected you may pass a Rational, a BigInt, text such as "1/3" or "0.05", or a JS number, which is read by its decimal form (0.1 is one tenth).
Kinds of answer
| Kind | What you get |
|---|---|
| exact | A Rational. Finite probability, discrete distributions with rational parameters, statistics of exact data, exact tests. |
| certified | A RationalInterval that contains the true value; { bits } sets its width. Continuous distributions, Poisson, square roots. |
| simulated | An object with kind: "simulated", its seed, and its sampling error. |
Arguments the library cannot work with are refused with a StatsError carrying a code, such as bad-argument, domain, needs-exact, too-large, too-close or impossible-event.
Numbers
| Export | What it does |
|---|---|
| toQ(v) | Any accepted number as a Rational. |
| toValue(v) | A datum: a Rational, or a RationalInterval from [low, high], "1.2:1.4" or "1.5[+-0.1]". |
| show(v, digits = 6) | Decimal text. For an enclosure, the digits both ends share, then …. |
| compare(value, level) | "below", "above", "equal" or "too close to call". |
| sqrt(v, bits = 96) | Exact for perfect squares, a certified enclosure otherwise. |
| toNumber(v) | A JS number; the midpoint of an enclosure. |
| StatsError | The error class, with code. |
Finite probability
| Export | What it does |
|---|---|
| finite(spec, weights?, { normalize }) | A Finite from equally likely outcomes, outcomes with weights, an object or Map, or a family from the discrete library. |
| die(sides = 6), dice(n, sides = 6), coin(p = 1/2) | A die; dice as tuples; a coin showing "H" with probability . |
| deck() | The 52 cards as text such as "Q♥", for draw. |
| draw(items, k, { replace, ordered }) | Every way of drawing of the items, equally likely. |
| bayes(prior, likelihood) | { posterior, evidence, table }. |
| Finite: p, prob, given | p(outcome); prob(event, given?); given(event), the conditional distribution. |
| Finite: map, filter, product, power, plus, sumOf | The distribution of a function of the outcome; conditioning; independent pairs and tuples; the sum of two independent numbers, or of copies. |
| Finite: marginal, joint, independent | Coordinates of tuple outcomes; several functions at once; whether two events are independent, exactly. |
| Finite: mean, expect, variance, sd, moment, covariance, correlation | Of the outcome or of functions of it. |
| Finite: cdf, quantile, median, modes, support | For numeric outcomes. |
| Finite: sample, samples, table, entries, outcomes, size | Seeded draws; rows { outcome, probability }. |
| Finite: count, factors, each, sum | The exact number of outcomes (a bigint); the independent parts of a product (null for a table); each [outcome, probability] in turn without listing; the distribution of the sum of tuple coordinates, by convolution for a product. See Many dice. |
Discrete distributions
| Export | What it does |
|---|---|
| bernoulli(p), binomial(n, p) | One trial; successes in trials. |
| geometric(p, { failures }), negativeBinomial(r, p) | Trials to the first success (or failures before it); failures before the th success. |
| hypergeometric(N, K, n), discreteUniform(a, b) | Marked items in a draw without replacement; a whole number from to . |
| poisson(lambda) | Certified; methods take { bits }. |
| Discrete | pmf(k), cdf(k), sf(k), prob(a, b) for , quantile(p), median(), mean, variance, sd(), mode, min, max, kind, sample(rng), samples(n, rng), toFinite(). |
Descriptive statistics
| Export | What it does |
|---|---|
| count, sum, mean, weightedMean(data, weights) | Exact; enclosures for interval data. |
| variance(data, { population }), sd, moment(data, k, { central }) | Sample variance unless population. |
| skewness, kurtosis(data, { excess }) | and . |
| min, max, range, median, quartiles, iqr, fiveNumber | Order statistics; quartiles is [q1, median, q3]. |
| quantile(data, p, { method }) | linear, weibull, hazen, median-unbiased, inverse, lower, higher, nearest, midpoint; for quartiles also halves (textbook) and tukey. |
| mad, trimmedMean(data, fraction) | Median absolute deviation; the mean after dropping a fraction from each end. |
| frequencies, modes, histogram(data, { edges | width, start | bins }) | Counts by value and by class. |
| covariance(x, y), correlation(x, y) | Sample covariance; Pearson's . |
| leastSquares(x, y) | { slope, intercept, r2, residuals, fitted, sse, sst, n, predict }. |
| summary(data) | The usual summaries in one object, with outliers and modes. |
| fast | Floating-point sum, mean, variance, sd, quantile, median, min, max, trimmedMean, covariance, correlation, leastSquares. |
Exact tests
| Export | What it does |
|---|---|
| binomialTest(k, n, p0 = 1/2, { alternative }) | A TestResult with interval(options). |
| fisherTest([[a, b], [c, d]], { alternative }) | With oddsRatio. |
| permutationTest(x, y, { statistic, alternative, paired, limit, resamples, seed }) | Exact when the deals can be counted, otherwise simulated with pValueInterval. |
| proportionInterval(k, n, { level, method, bits }) | { low, high, level, method, estimate }; method exact, wilson or wald. |
| TestResult | test, statistic, pValue, alternative, kind, decision(alpha), reject(alpha). Alternatives are "two-sided", "greater", "less". |
Continuous distributions
| Export | What it does |
|---|---|
| normal(mu = 0, sigma = 1), lognormal(mu, sigma) | |
| gamma(shape, rate = 1), chiSquare(k), exponential(rate = 1), weibull(shape, scale = 1) | |
| beta(a, b), studentT(df), fDist(d1, d2) | |
| uniform(a = 0, b = 1), cauchy(location = 0, scale = 1) | |
| fromDensity(f, support, { normalize, variable }) | A Continuous distribution from a density formula, or a list [[formula, [a, b]], ...] of pieces. Proves f ≥ 0 and mass 1 (exactly for polynomial pieces) or refuses; { normalize: true } divides by the mass and reports it as constant. checks says how each fact was established. |
| transform(dist, g), dist.transform(g) | The distribution of g(X) for g proven monotone on the support. Exact moments when X has polynomial pieces and g is a polynomial. |
| orderStatistic(dist, k, n), dist.orderStatistic(k, n) | The k-th smallest of n draws. Exact piecewise polynomial for uniform or polynomial densities (the maximum of n uniforms is Beta(n, 1)). |
| Continuous | pdf(x), cdf(x), sf(x), prob(a, b), quantile(p), median(), each with { bits }; mean, variance, sd() (null where undefined); low, high (the support; null for infinite); fast.pdf, fast.cdf, fast.quantile; sample(rng), samples(n, rng), sampleExact(rng, { bits }), samplesExact(n, rng). |
Tests and estimation
| Export | What it does |
|---|---|
| zTest(data, { sigma, mu, alternative, bits }) | z test for a mean with known . |
| tTest(x, [y], { mu, paired, equalVariance, alternative, bits }) | One-sample, paired, Welch (default) or pooled t test. |
| meanInterval(data, { level, sigma, alternative, bits }) | t (or z) interval for a mean. data may be a summary { n, mean, sd } or { n, mean, variance }. |
| varianceInterval(data, { level, bits }) | Chi-square interval for ; .sd holds the interval for . data may be { n, variance } or { n, sd }. |
| power({ test: "z" | "proportion", mu0, mu, sigma | p0, p, n, alpha, alternative }) | Closed-form power as an enclosure (the proportion test by the normal approximation). |
| sampleSize({ margin, p | sigma, level }) or ({ power, … as power }) | { n }: the smallest whole n proven to meet the margin or the power. |
| varianceTest(data, v0), fTest(x, y, { ratio }) | Chi-square test of one variance; F test of a ratio of two. |
| proportionTest(k, n, p0, { correct }), proportionTest([k1, k2], [n1, n2]) | z test for one or two proportions, with Wilson or Wald intervals. |
| chiSquareTest(observed | table, { p, expected, estimated, correct }) | Goodness of fit, or independence in a contingency table (Yates' correction on 2×2 when asked). |
| correlationTest(x, y) | t test of zero correlation; Fisher's z interval. |
| fit(data, family, { method, trials }) | Maximum likelihood (default) or moments for normal, exponential, poisson, bernoulli, binomial, geometric, uniform, gamma, beta (moments), lognormal (likelihood). Returns params, method, kind and distribution. |
| TestResult | statistic, statisticSquared (exact where possible), df, pValue (certified), alternative, estimate, null, standardError, interval({ level }), reject(alpha), decision(alpha). |
| Interval | { low, high, level, estimate, method }; an open end is null. Ends are rounded outward from enclosures. |
Regression and analysis of variance
| Export | What it does |
|---|---|
| linearModel(x, y, { intercept = true, names }) | Least squares with exact coefficients. x is one column, an array of rows, or an object of named columns. Refuses with "collinear", naming the column. |
| LinearModel | coefficients, fitted, residuals, sse, ssr, sst, rSquared, adjustedRSquared, variance, sigma, covariance, leverage, cooksDistance; coefficient(name), test(name, { value, alternative }), interval(name, { level }), table(), fTest(), predict(x), predictionInterval(x, { kind: "mean" | "new" }), standardizedResiduals(). |
| polyFit(x, y, degree) | Regression on . |
| dummies(labels, { reference, name }) | Indicator columns, one per level but the reference. |
| compareModels(small, big) | F test of nested models; checks the nesting exactly. |
| anova(groups) | One-way analysis of variance: table, means, grandMean, etaSquared and the F test. |
Rank tests, Kolmogorov–Smirnov and the bootstrap
| Export | What it does |
|---|---|
| ranks(data) | Midranks and tie group sizes. |
| signTest(x, y?, { mu, alternative }) | Exact, by the binomial law of the signs; zeros dropped. |
| wilcoxonTest(x, y?, { mu, alternative, method, correct }) | Signed-rank test; method "auto" (exact up to n = 60), "exact" or "normal". Adds estimate (Hodges–Lehmann). |
| mannWhitneyTest(x, y, { alternative, method, correct }) | U, the rank sum, exact counting with ties, and the Hodges–Lehmann shift. |
| kruskalWallisTest(groups) | H exact with the tie correction; p from chi-square, certified. |
| spearmanTest(x, y, …), kendallTest(x, y, …) | Rank correlations; exact p by enumeration (Spearman, n ≤ 9) or inversion counts (Kendall, no ties). |
| ksTest(x, dist | cdf | y, { alternative, exactUpTo, resamples, seed }) | One sample against a Continuous or an exact cdf; two samples by counting lattice paths. |
| kolmogorovCdf(n, d), kolmogorovTail(n, d), smirnovTail(n, d) | P(Dₙ < d) exactly; the two-sided tail; the one-sided tail. |
| bootstrap(data, statistic, { resamples, seed, level, method, exactUpTo }) | A Bootstrap: estimate, mean, bias, se, interval; exact distribution for small samples, replicates otherwise. |
Markov chains and Bayesian updating
| Export | What it does |
|---|---|
| markovChain(matrix | rows object, { states }) | A MarkovChain; every row must add up to 1 exactly. |
| MarkovChain | p(a, b), power(n), distribution(start, n), classes() (closed, recurrent, period), isIrreducible(), isErgodic(), stationary(), absorption() (probabilities, steps, fundamental matrix), hitting(targets), meanReturnTime(state), simulate(start, steps, { seed }). |
| betaPrior(a, b) | Beta belief for a probability; update({ successes, trials | failures }) or a list of 0/1; predictive(m) beta-binomial. |
| gammaPrior(shape, rate, { likelihood }) | Gamma belief for a rate, with Poisson counts or exponential times; predictive() negative binomial. |
| normalPrior(mean, { variance | sd, dataVariance | dataSd }) | Normal belief for a mean with known data variance. |
| dirichletPrior(alpha) | Dirichlet belief for category probabilities; marginal(category). |
| Every belief | params, mean, variance, mode (exact), distribution, interval(level) (certified), cdf(x), history. |
Sampling, models and experiments
| Export | What it does |
|---|---|
| rng(seed), Random | The seeded generator of the discrete library: fork(label), int, bool, pick, shuffle, sample. |
| model(spec), Model | Parts truth, x, noise, spread, contamination, xNoise, round, censor, missing, name. Methods with(changes), truthAt(x), sample(n, seed, { exact, bits }). |
| Dataset | x, y, trueX, trueY, contaminated, censored, missing, seed, model, kind, n, complete(). |
| howOften({ model, n | draw, event, runs, seed, level }) | A SimulatedRate. |
| coverage({ interval, truth, … }) | How often interval(data) contains the truth; adds meanWidth. |
| rejectionRate({ test, alpha, … }) | How often test(data) rejects: size under the null, power otherwise. |
| powerCurve({ effects, model | draw, test, … }) | A rejection rate for each effect; model or draw is a function of the effect. |
| estimatorStudy({ estimator, truth, … }) | A SimulatedEstimates: estimates, mean, sd, standardError, bias, rmse. |
| SimulatedRate | rate, hits, runs, seed, interval { low, high, level }, compare(value). |
| plan | The phases still to be built. |
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.