然ranjs
然 rán

ranjs

rán · 然 “so; correct” — robust random variates, distribution testing & statistics for JavaScript.

140+ distributionsseedablezero depsMIT

What is this?

A small library for robust generation of various random variates, testing data against distributions or calculating different statistical properties.

Install in node

npm install --save ranjs

Use in browser

<script type="text/javascript" src="ran.min.js"></script>

Demo

Continuous distributions · Discrete distributions

API

ran.core.char([string[, n]])

Samples some characters with replacement from a string with uniform distribution.

Parameters

NameTypeDescription
stringstring

String to sample characters from.

nnumber

Number of characters to sample.

Returns

stringstring[]undefined

Random character if n is not given or less than 2, an array of random characters otherwise. If string is empty, undefined is returned.

Examples

ran.core.char('abcde')
// => 'd'

ran.core.char('abcde', 5)
// => [ 'd', 'c', 'a', 'a', 'd' ]
ran.core.choice(values[, n])

Samples some elements with replacement from an array with uniform distribution.

Parameters

NameTypeDescription
valuesT[]

Array to sample from.

nnumber

Number of elements to sample.

Returns

TT[]undefined

Single element or array of sampled elements. If the array is invalid (empty or not passed), undefined is returned.

Examples

ran.core.choice([1, 2, 3, 4, 5])
// => 2

ran.core.choice([1, 2, 3, 4, 5], 5)
// => [ 1, 5, 4, 4, 1 ]
ran.core.coin(head, tail[, p[, n]])

Flips a biased coin several times and returns the associated head/tail value or array of values.

Parameters

NameTypeDescription
headH

Head value.

tailT

Tail value.

pnumber

Bias (probability of head). Default is 0.5.

nnumber

Number of coins to flip. Default is 1.

Returns

HTundefined[]

Single head/tail value or an array of head/tail values.

Examples

ran.core.coin('a', {b: 2})
// => { b: 2 }

ran.core.coin('a', {b: 2}, 0.9)
// => 'a'

ran.core.coin('a', {b: 2}, 0.9, 9)
// => [ { b: 2 }, 'a', 'a', 'a', 'a', 'a', 'a', { b: 2 }, 'a' ]
ran.core.float([min[, max[, n]]])

Generates some uniformly distributed random floats in (min, max). If min > max, a random float in (max, min) is generated. If no parameters are passed, generates a single random float between 0 and 1. If only min is specified, generates a single random float between 0 and min.

Parameters

NameTypeDescription
minnumber

Lower boundary, or upper if max is not given.

maxnumber

Upper boundary.

nnumber

Number of floats to generate.

Returns

numbernumber[]

Single float or array of random floats.

Examples

ran.core.float()
// => 0.278014086611011

ran.core.float(2)
// => 1.7201255276155272

ran.core.float(2, 3)
// => 2.3693449236256185

ran.core.float(2, 3, 5)
// => [ 2.4310443387740093,
//      2.934333354639414,
//      2.7689523358767127,
//      2.291137165632517,
//      2.5040591952427906 ]
ran.core.int(min[, max[, n]])

Generates some uniformly distributed random integers in (min, max). If min > max, a random integer in (max, min) is generated. If only min is specified, generates a single random integer between 0 and min.

Parameters

NameTypeDescription
minnumber

Lower boundary, or upper if max is not specified.

maxnumber

Upper boundary.

nnumber

Number of integers to generate.

Returns

numbernumber[]

Single integer or array of random integers.

Examples

ran.core.int(10)
// => 2

ran.core.int(10, 20)
//=> 12

ran.core.int(10, 20, 5)
// => [ 12, 13, 10, 14, 14 ]
ran.core.seed(value)

Sets the seed for the underlying pseudo random number generator used by the core generators. Under the hood, ranjs implements the xoshiro128+ algorithm as described in Blackman and Vigna: Scrambled Linear Pseudorandom Number Generators (2019).

Parameters

NameTypeDescription
valuenumberstring

The value of the seed, either a number or a string (for the ease of tracking seeds).

Returns

void
ran.core.shuffle(values)

Shuffles an array in-place using the Fisher‒Yates algorithm.

Parameters

NameTypeDescription
valuesT[]

Array to shuffle.

Returns

T[]

The shuffled array.

Examples

ran.core.shuffle([1, 2, 3])
// => [ 2, 3, 1 ]
ran.dependence.covariance(x, y)

Calculates the sample covariance for paired arrays of values.

Parameters

NameTypeDescription
xnumber[]

First array of values.

ynumber[]

Second array of values.

Returns

number

The sample covariance, or NaN if either array has fewer than 2 elements.

Throws

Error
If the arrays have different lengths.

Examples

ran.dependence.covariance([], [])
// => NaN

ran.dependence.covariance([1], [2])
// => NaN

ran.dependence.covariance([1, 2, 3], [4, 5, 6])
// => 1

ran.dependence.covariance([1, 9, 10], [1, 2, 10])
// => 16.166666666666668
ran.dependence.dCor(x, y)

Calculates the distance correlation for paired arrays of values.

Parameters

NameTypeDescription
xnumber[]

First array of values.

ynumber[]

Second array of values.

Returns

number

The distance correlation, or NaN for empty or constant arrays.

Throws

Error
If the arrays have different lengths.

Examples

ran.dependence.dCor([], [])
// => NaN

ran.dependence.dCor([1, 2, 3], [2, 1, 2])
// => 0.5623413251903491
ran.dependence.dCov(x, y)

Calculates the distance covariance for paired arrays of values.

Parameters

NameTypeDescription
xnumber[]

First array of values.

ynumber[]

Second array of values.

Returns

number

The distance covariance, or NaN for empty arrays.

Throws

Error
If the arrays have different lengths.

Examples

ran.dependence.dCov([], [])
// => NaN

ran.dependence.dCov([1, 2, 3], [2, 1, 2])
// => 0.31426968052735443
ran.dependence.kendall(x, y)

Calculates Kendall's rank correlation coefficient for paired arrays of values.

Parameters

NameTypeDescription
xnumber[]

First array of values.

ynumber[]

Second array of values.

Returns

number

Kendall's correlation coefficient, or NaN for empty arrays.

Throws

Error
If the arrays have different lengths.

Examples

ran.dependence.kendall([], [])
// => NaN

ran.dependence.kendall([1, 2, 3], [4, 5, 6])
// => 1

ran.dependence.kendall([1, 2, 3], [1, 4, 2])
// => 0.3333333333333333
ran.dependence.kullbackLeibler(p, q)

Calculates the (discrete) Kullback-Leibler divergence for two probability distributions:

D_\mathrm{KL}(P \parallel Q) = \sum_{x \in \mathcal{X}} P(x) \log\bigg(\frac{P(x)}{Q(x)}\bigg).

Parameters

NameTypeDescription
pnumber[]

Array representing the probabilities for the i-th value in the base distribution (P).

qnumber[]

Array representing the probabilities for the i-th value in compared distribution (Q).

Returns

number

The Kullback-Leibler divergence, NaN for empty input, Infinity if Q(x) = 0 and P(x) > 0 for some x.

Throws

Error
If the arrays have different lengths.

Examples

ran.dependence.kullbackLeibler([], [])
// => NaN

ran.dependence.kullbackLeibler([0.1, 0.2, 0.7], [0, 0.3, 0.7])
// => Infinity

ran.dependence.kullbackLeibler([0.1, 0.3, 0.6], [0.333, 0.333, 0.334])
// => 0.19986796234715937

ran.dependence.kullbackLeibler([0.333, 0.333, 0.334], [0.1, 0.3, 0.6])
// => 0.2396882491444514
ran.dependence.oddsRatio(p00, p01, p10, p11)

Calculates the odds ratio for the joint probabilities of two binary variables:

OR(p_{00}, p_{01}, p_{10}, p_{11}) = \frac{p_{00} p_{11}}{p_{01} p_{10}}.

Parameters

NameTypeDescription
p00number

The probability of X = 0 and Y = 0.

p01number

The probability of X = 0 and Y = 1.

p10number

The probability of X = 1 and Y = 0.

p11number

The probability of X = 1 and Y = 1.

Returns

number

The odds ratio. Returns Infinity when p01 or p10 is zero and the numerator is non-zero.

Examples

ran.dependence.oddsRatio(0.3, 0, 0.3, 0.4)
// => Infinity

ran.dependence.oddsRatio(0.3, 0.3, 0, 0.4)
// => Infinity

ran.dependence.oddsRatio(0.1, 0.2, 0.3, 0.4)
// => 0.6666666666666669
ran.dependence.pearson(x, y)

Calculates the Pearson correlation coefficient for paired arrays of values.

Parameters

NameTypeDescription
xnumber[]

First array of values.

ynumber[]

Second array of values.

Returns

number

The Pearson correlation coefficient, or NaN if arrays have fewer than two elements or zero variance.

Throws

Error
If the arrays have different lengths.

Examples

ran.dependence.pearson([], [])
// => NaN

ran.dependence.pearson([1, 2, 3], [1, 1, 1])
// => NaN

ran.dependence.pearson([1, 2, 3], [4, 5, 6])
// => 1

ran.dependence.pearson([1, 9, 10], [1, 2, 10])
// => 0.6643835616438358
ran.dependence.pointBiserial(x, y)

Calculates the point-biserial correlation coefficient for paired arrays of values.

Parameters

NameTypeDescription
xnumber[]

First array of values.

ynumber[]

Second array of values. Must contain 0s and 1s only.

Returns

number

The point-biserial correlation coefficient, or NaN if arrays have fewer than 2 elements or zero variance.

Throws

Error
If the arrays have different lengths.

Examples

ran.dependence.pointBiserial([], [])
// => NaN

ran.dependence.pointBiserial([2, 2, 2], [0, 0, 1])
// => NaN

ran.dependence.pointBiserial([1, 2, 3], [4, 5, 6])
// => 0.8660254037844386
ran.dependence.somersD(x, y)

Calculates Somers' D for paired arrays of values.

Parameters

NameTypeDescription
xnumber[]

First array of values.

ynumber[]

Second array of values.

Returns

number

Somers' D, or NaN for empty arrays.

Throws

Error
If the arrays have different lengths.

Examples

ran.dependence.somersD([], [])
// => NaN

ran.dependence.somersD([1, 2, 3], [4, 6, 6])
// => 0.6666666666666666

ran.dependence.somersD([1, 1, 0], [4, 5, 6])
// => -1
ran.dependence.spearman(x, y)

Calculates Spearman's rank correlation coefficient for two paired arrays of values.

Parameters

NameTypeDescription
xnumber[]

First array of values.

ynumber[]

Second array of values.

Returns

number

Spearman's rank correlation coefficient, or NaN for empty arrays.

Throws

Error
If the arrays have different lengths.

Examples

ran.dependence.spearman([], [])
// => NaN

ran.dependence.spearman([1, 2, 3], [1, 4, 2])
// => 0.5

ran.dependence.spearman([1, 9, 10], [1, 2, 10])
// => 1
ran.dependence.yuleQ(p00, p01, p10, p11)

Calculates Yule's Q for the joint probabilities of two binary variables:

Q(p_{00}, p_{01}, p_{10}, p_{11}) = \frac{p_{00} p_{11} - p_{01} p_{10}}{p_{00} p_{11} + p_{01} p_{10}}.

Parameters

NameTypeDescription
p00number

The probability of X = 0 and Y = 0.

p01number

The probability of X = 0 and Y = 1.

p10number

The probability of X = 1 and Y = 0.

p11number

The probability of X = 1 and Y = 1.

Returns

number

Yule's Q, or NaN when p01 or p10 is zero (the odds ratio diverges, making the formula indeterminate).

Examples

ran.dependence.yuleQ(0.3, 0, 0.3, 0.4)
// => NaN

ran.dependence.yuleQ(0.3, 0.3, 0, 0.4)
// => NaN

ran.dependence.yuleQ(0.1, 0.2, 0.3, 0.4)
// => -0.19999999999999984
ran.dependence.yuleY(p00, p01, p10, p11)

Calculates Yule's Y for the joint probabilities of two binary variables:

Y(p_{00}, p_{01}, p_{10}, p_{11}) = \frac{\sqrt{p_{00} p_{11}} - \sqrt{p_{01} p_{10}}}{\sqrt{p_{00} p_{11}} + \sqrt{p_{01} p_{10}}}.

Parameters

NameTypeDescription
p00number

The probability of X = 0 and Y = 0.

p01number

The probability of X = 0 and Y = 1.

p10number

The probability of X = 1 and Y = 0.

p11number

The probability of X = 1 and Y = 1.

Returns

number

Yule's Y, or NaN when p01 or p10 is zero (the odds ratio diverges, making the formula indeterminate).

Examples

ran.dependence.yuleY(0.3, 0, 0.3, 0.4)
// => NaN

ran.dependence.yuleY(0.3, 0.3, 0, 0.4)
// => NaN

ran.dependence.yuleY(0.1, 0.2, 0.3, 0.4)
// => -0.10102051443364372
ran.dispersion.cv(values)

Calculates the coefficient of variation of an array of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate coefficient of variation for.

Returns

number

Coefficient of variation, or NaN for fewer than 2 elements, zero mean, or zero variance.

Examples

ran.dispersion.cv([])
// => NaN

ran.dispersion.cv([1])
// => NaN

ran.dispersion.cv([-1, 0, 1])
// => NaN

ran.dispersion.cv([1, 2, 3, 4, 5])
// => 0.5270462766947299
ran.dispersion.dVar(x)

Calculates the distance variance for paired arrays of values.

Parameters

NameTypeDescription
xnumber[]

Array of values.

Returns

number

The distance variance, or NaN for an empty array.

Examples

ran.dispersion.dVar([])
// => NaN

ran.dispersion.dVar([1, 2, 3])
// => 0.7027283689263066
ran.dispersion.entropy(probabilities[, base])

Calculates the Shannon entropy for a probability distribution.

Parameters

NameTypeDescription
probabilitiesnumber[]

Array representing the probabilities for the i-th value.

basenumber

Base for the logarithm. If not specified, natural logarithm is used.

Returns

number

Entropy of the probabilities, or NaN for empty input.

Examples

ran.dispersion.entropy([])
// => NaN

ran.dispersion.entropy([0.1, 0.1, 0.8])
// => 0.639031859650177

ran.dispersion.entropy([0.3, 0.3, 0.4])
// => 1.0888999753452238
ran.dispersion.gini(values)

Calculates the Gini coefficient for a sample of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate the Gini coefficient for.

Returns

number

The Gini coefficient, or NaN for fewer than 2 elements or zero mean.

Examples

ran.dispersion.gini([])
// => NaN

ran.dispersion.gini([1])
// => NaN

ran.dispersion.gini([-1, 0, 1])
// => NaN

ran.dispersion.gini([1, 2, 3, 4])
// => 0.25

ran.dispersion.gini([1, 1, 1, 7])
// => 0.45
ran.dispersion.iqr(values)

Calculates the interquartile range for a sample of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate the interquartile range for.

Returns

number

The interquartile range, or NaN for an empty array.

Examples

ran.dispersion.iqr([])
// => NaN

ran.dispersion.iqr([1, 1, 2, 3, 3])
// => 2
ran.dispersion.md(values)

Calculates the mean absolute difference of an array of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate mean absolute difference for.

Returns

number

Mean absolute difference, or NaN for fewer than 2 elements.

Examples

ran.dispersion.md([])
// => NaN

ran.dispersion.md([1])
// => NaN

ran.dispersion.md([1, 2, 3, 4])
// => 1.25
ran.dispersion.midhinge(values)

Calculates the midhinge for a sample of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate midhinge for.

Returns

number

The midhinge, or NaN for an empty array.

Examples

ran.dispersion.midhinge([])
// => NaN

ran.dispersion.midhinge([1, 1, 1, 2, 3])
// => 1.5
ran.dispersion.qcd(values)

Calculates the quartile coefficient of dispersion for a sample of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate quartile coefficient of dispersion for.

Returns

number

The quartile coefficient of dispersion, or NaN for an empty array.

Examples

ran.dispersion.qcd([])
// => NaN

ran.dispersion.qcd([1, 2, 3])
// => 0.25
ran.dispersion.range(values)

Calculates the range for a sample of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate range for.

Returns

number

The range of the values, or NaN for an empty array.

Examples

ran.dispersion.range([])
// => NaN

ran.dispersion.range([0, 1, 2, 2])
// => 2
ran.dispersion.rmd(values)

Calculates the relative mean absolute difference of an array of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate relative mean absolute difference for.

Returns

number

Relative mean absolute difference, or NaN for fewer than 2 elements or zero mean.

Examples

ran.dispersion.rmd([])
// => NaN

ran.dispersion.rmd([1])
// => NaN

ran.dispersion.rmd([-1, 0, 1])
// => NaN

ran.dispersion.rmd([1, 2, 3, 4])
// => 0.5
ran.dispersion.stdev(values)

Calculates the unbiased standard deviation of an array of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate standard deviation for.

Returns

number

Standard deviation of the values, NaN for fewer than 2 elements.

Examples

ran.dispersion.stdev([])
// => NaN

ran.dispersion.stdev([1])
// => NaN

ran.dispersion.stdev([1, 2, 3, 4, 5])
// => 1.5811388300841898
ran.dispersion.variance(values)

Calculates the unbiased sample variance of an array of values using Welford's algorithm.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate variance for.

Returns

number

Variance of the values, NaN for fewer than 2 elements.

Examples

ran.dispersion.variance([])
// => NaN

ran.dispersion.variance([1])
// => NaN

ran.dispersion.variance([1, 2, 3, 4, 5])
// => 2.5
ran.dispersion.vmr(values)

Calculates the variance-to-mean ratio of an array of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate variance-to-mean ratio for.

Returns

number

Variance-to-mean ratio, or NaN for fewer than 2 elements or zero mean.

Examples

ran.dispersion.vmr([])
// => NaN

ran.dispersion.vmr([1])
// => NaN

ran.dispersion.vmr([-1, 0, 1])
// => NaN

ran.dispersion.vmr([1, 2, 3, 4, 5])
// => 0.8333333333333334
ran.dist.guess(data[, options])

Fits a set of candidate distributions to a dataset and ranks them by BIC weight — the probability that each candidate is the best-fitting model in the candidate set, given the data. "Guess" is intentional: this is a heuristic exploratory tool, not a verdict.

Candidates are pre-filtered before the expensive fit() call: hard filters (matching type and support against the data) are followed by soft, statistically-principled filters (skewness, coefficient of variation, dispersion index) that can, by design, silently exclude a candidate that would in fact have fit reasonably well. The soft filters' false-exclusion risk is not uniform, and has been empirically measured by Monte Carlo simulation (scripts/guess-filter-validation.js, 10 000 seeded draws per configuration, n = 50..1000; see issues #1054 and #1064). The skewness threshold used for a SYMMETRIC candidate is 2·√(c/n), where c is that family's own asymptotic skewness-estimator variance factor (Var(g1)·n ≈ μ6/μ2³ − 6·μ4/μ2² + 9, using population central moments — see _guess-meta.js's SYMMETRIC doc for the per-family derivation), not a single normal-only constant: the naive 6/n (roughly 2 standard errors of the sample-skewness estimator under normality) only holds for Normal(0, 1) (measured 4.2%-4.7% false exclusion across the tested n range, unaffected by this fix) and understates the true variance for heavier-tailed symmetric families — Laplace(0, 1)'s heavier tails (excess kurtosis 3 vs. Normal's 0) inflate it roughly tenfold (c ≈ 63 vs. Normal's c = 6), which the per-family threshold now accounts for directly instead of sharing Normal's bound: measured false exclusion dropped from 34.7%-51.1% under the old shared threshold to 1.4%-4.2% across the same n range. Uniform(-1, 1)'s c = 72/35 ≈ 2.06 is already lower than Normal's, so its measured 4.4%-5.6% rate was safe both before and after this fix. The positive-skew-only rule is deliberately asymmetric — it only excludes on strongly negative sample skewness, so ordinary sampling noise around zero or positive skew never triggers it; measured false-exclusion was ~0% for both Exponential(1) and Gamma(20, 1) (the latter's skewness, 2/√20 ≈ 0.45, is the family's lowest at that shape, making it the closest a POSITIVE_SKEW_ONLY member gets to the symmetric boundary). The coefficient-of-variation ([0.1, 10]) and dispersion-index (>3, <0.5) bounds were also measured at ~0% false exclusion for their respective representative distributions (Exponential(1), Poisson(5), NegativeBinomial(5, 0.5)) across the same n range — comfortably safe heuristics for those families, not merely unvalidated ones. A distribution excluded by a soft filter is never reported, with no diagnostic indicating it was screened out; callers with a specific hypothesis about their data should bypass all filtering via the candidates option rather than rely on the default pool. A candidate whose fit() throws is skipped rather than propagating the error. Throws if the data is too small for the surviving candidate set's largest parameter count (BIC's asymptotic approximation requires roughly 20 observations per parameter).

Parameters

NameTypeDescription
datanumber[]

Array of numbers to fit candidate distributions to.

optionsObject

Options for the fitting procedure.

candidatesFunction[]

Distribution constructors to try, overriding the default candidate pool (all distributions).

Returns

Object[]

Array of {name, params, bicWeight, pValue}, sorted by descending bicWeight (bicWeight values across the array sum to 1). For continuous candidates, pValue uses the Marsaglia & Marsaglia (2004) Anderson-Darling asymptotic approximation, which can occasionally report a value slightly above 1 for a very small, near-perfectly-fit sample — an artifact of the published approximation itself. Carries a warning string property when every surviving candidate fails goodness-of-fit at α=0.05.

Throws

Error
If no candidate survives pre-filtering, if the data is too small for the surviving candidate set's largest parameter count, or if no candidate can be fitted.
ran.dist.Distribution()

The distribution generator base class, all distribution generators extend this class. The methods listed here are available for all distribution generators. Integer parameters of a distribution are rounded. The examples provided for this class are using a Pareto distribution.

ran.dist.Distribution.aic(data)

Returns the value of the Akaike information criterion for a specific data set. Note that this method does not optimize the likelihood, merely computes the AIC with the current parameter values.

Parameters

NameTypeDescription
datanumber[]

Array of values containing the data.

Returns

number

The AIC for the current parameters.

Examples

let pareto1 = new dist.Pareto(1, 2)
let pareto2 = new dist.Pareto(1, 5)
let sample = pareto1.sample(1000)

pareto1.aic(sample)
// => 1584.6619128383577

pareto2.aic(sample)
// => 2719.0367230482957
ran.dist.Distribution.bic(data)

Returns the value of the Bayesian information criterion for a specific data set. Note that this method does not optimize the likelihood, merely computes the BIC with the current parameter values.

Parameters

NameTypeDescription
datanumber[]

Array of values containing the data.

Returns

number

The BIC for the current parameters.

Examples

let pareto1 = new dist.Pareto(1, 2)
let pareto2 = new dist.Pareto(1, 5)
let sample = pareto1.sample(1000)

pareto1.bic(sample)
// => 1825.3432698372499

pareto2.bic(sample)
// => 3190.5839264881165
ran.dist.Distribution.bounded()

Returns the boundedness category of the distribution's support:

Returns

The boundedness category of the support.

ran.dist.Distribution.cdf(x)

The cumulative distribution function:

F(x) = \int_{-\infty}^x f(t) ,\mathrm{d}t,

if the distribution is continuous and

F(x) = \sum_{x_i \le x} f(x_i),

if it is discrete. The functions f(t) and f(x_i) denote the probability density and mass functions.

Parameters

NameTypeDescription
xnumber

Value to evaluate CDF at.

Returns

number

The cumulative distribution value.

Examples

let pareto = new ran.dist.Pareto(1, 2)
pareto.cdf(3)
// => 0.8888888888888888
ran.dist.Distribution.cHazard(x)

The cumulative hazard function:

\Lambda(x) = \int_0^x \lambda(t) ,\mathrm{d}t,

where \lambda(x) is the hazard function.

Parameters

NameTypeDescription
xnumber

Value to evaluate cumulative hazard at.

Returns

number

The cumulative hazard.

Examples

let pareto = new ran.dist.Pareto(1, 2)
pareto.cHazard(3)
// => 2.197224577336219
ran.dist.Distribution.fit(data)

Estimates the distribution parameters from data using maximum likelihood estimation (MLE). Distributions with a closed-form MLE return it directly; all others maximise the log-likelihood lnL(data) with Powell's derivative-free conjugate-direction optimizer.

Parameters

NameTypeDescription
datanumber[]

Array of observations to fit.

Returns

Distribution

A new instance of the same distribution with MLE parameters.

ran.dist.Distribution.hazard(x)

The hazard function:

\lambda(x) = \frac{f(x)}{S(x)},

where f(x) and S(x) are the probability density (or mass) function and the survival function, respectively.

Parameters

NameTypeDescription
xnumber

Value to evaluate the hazard at.

Returns

number

The hazard value.

Examples

let pareto = new ran.dist.Pareto(1, 2)
pareto.hazard(3)
// => 0.6666666666666663
ran.dist.Distribution.kurtosis()

The theoretical excess kurtosis of the distribution:

\gamma_2 = \frac{\mathrm{E}[(X-\mu)^4]}{\sigma^4} - 3 = \frac{\mathrm{E}[X^4] - 4\mu,\mathrm{E}[X^3] + 6\mu^2,\mathrm{E}[X^2] - 3\mu^4}{\sigma^4} - 3.

Returns NaN when undefined (zero variance, or moment does not exist). Distributions with non-finite moments must override this method.

Returns

number

The theoretical excess kurtosis.

ran.dist.Distribution.lnL(data)

The log-likelihood of the current distribution based on some data. More precisely:

\ln L(\theta | X) = \sum_{x \in X} \ln f(x; \theta),

where X is the set of observations (sample) and \theta is the parameter vector of the distribution. The function f(x) denotes the probability density/mass function.

Parameters

NameTypeDescription
datanumber[]

Array of numbers to calculate log-likelihood for.

Returns

number

The log-likelihood of the data for the distribution.

Examples

let pareto = new ran.dist.Pareto(1, 2)
let uniform = new ran.dist.UniformContinuous(1, 10);

let sample1 = pareto.sample(100)
pareto.L(sample1)
// => -104.55926409382

let sample2 = uniform.sample(100)
pareto.L(sample2)
// => -393.1174868780569
ran.dist.Distribution.load(state)

Reconstructs a distribution instance from a snapshot created by save(). The returned instance is still built without a constructor call; a throwaway probe instance is constructed only to validate that the restored state's shape matches what the current class definition expects.

Parameters

NameTypeDescription
stateObject

The state to load, as returned by save().

Returns

Distribution

New distribution instance with the restored state.

Throws

Error
If the restored params/constants keys do not match the shape the current class definition would produce (e.g. a snapshot saved by an older, incompatible version of the class).

Examples

let pareto1 = new ran.dist.Pareto(1, 2).seed('test')
let sample1 = pareto1.sample(2)
let state = pareto1.save()

let pareto2 = ran.dist.Pareto.load(state)
let sample2 = pareto2.sample(3)
// => [ 1.1315154468682591,
//      5.44269493220745,
//      1.2587482868229616 ]
ran.dist.Distribution.logPdf(x)

The logarithmic probability density function. For discrete distributions, this is the logarithm of the probability mass function.

Parameters

NameTypeDescription
xnumber

Value to evaluate the log pdf at.

Returns

number

The logarithmic probability density (or mass).

Examples

let pareto = new ran.dist.Pareto(1, 2)
pareto.lnPdf(3)
// => -2.6026896854443837
ran.dist.Distribution.mean()

The theoretical mean of the distribution:

\mu = \mathrm{E}[X].

Returns a finite number for well-behaved distributions, NaN when the moment is mathematically undefined, or Infinity / -Infinity when it diverges. Distributions with non-finite moments must override this method; the numerical fallback cannot detect divergence through truncated integration.

Returns

number

The theoretical mean.

ran.dist.Distribution.params()

Returns the natural (user-facing) parameters of the distribution. Internal lookup state is not included.

Returns

Object

The natural parameters of the distribution.

ran.dist.Distribution.pdf(x)

Probability density function. In case of discrete distributions, it is the probability mass function.

Parameters

NameTypeDescription
xnumber

Value to evaluate distribution at.

Returns

number

The probability density or probability mass.

Examples

let pareto = new ran.dist.Pareto(1, 2)
pareto.pdf(3)
// => 0.07407407407407407
ran.dist.Distribution.q(p)

The quantile function of the distribution. For continuous distributions, it is defined as the inverse of the distribution function:

Q(p) = F^{-1}(p),

whereas for discrete distributions it is the lower boundary of the interval that satisfies F(k) = p :

Q(p) = \mathrm{inf}\{k \in \mathrm{supp}(f): p \le F(k)\},

with \mathrm{supp}(f) denoting the support of the distribution. For distributions with an analytically invertible cumulative distribution function, the quantile is explicitly implemented. In other cases, two fallback estimations are used: for continuous distributions the equation F(x) = p is solved using Brent's method. For discrete distributions a look-up table is used with linear search.

Parameters

NameTypeDescription
pnumber

The probability at which the quantile should be evaluated.

Returns

number

The value of the quantile function at the specified probability.

Throws

Error
If p is outside [0, 1].
ran.dist.Distribution.sample([n])

Generates some random variate.

Parameters

NameTypeDescription
nnumber

Number of variates to generate. If not specified, a single value is returned.

Returns

numbernumber[]

Single sample or an array of samples.

Examples

let pareto = new ran.dist.Pareto(1, 2)
pareto.sample(5)
// => [ 5.619011325146519,
//      1.3142187491180493,
//      1.0513159445581859,
//      1.8124951360943067,
//      1.1694087449301402 ]
ran.dist.Distribution.save()

Returns the current state of the generator. The object returned by this method contains all information necessary to set up another generator of the same distribution (parameters, state of the pseudo random generator, etc).

Returns

Object representing the inner state of the current generator.

Examples

let pareto1 = new ran.dist.Pareto(1, 2).seed('test')
let sample1 = pareto1.sample(2)
let state = pareto1.save()

let pareto2 = ran.dist.Pareto.load(state)
let sample2 = pareto2.sample(3)
// => [ 1.1315154468682591,
//      5.44269493220745,
//      1.2587482868229616 ]
ran.dist.Distribution.seed(value)

Sets the seed for the distribution generator. Distributions implement the same PRNG ( xoshiro128+) that is used in the core functions.

Parameters

NameTypeDescription
valuenumberstring

The value of the seed, either a number or a string (for the ease of tracking seeds).

Returns

this

Reference to the current distribution.

Examples

let pareto = new ran.dist.Pareto(1, 2).seed('test')
pareto.sample(5)
// => [ 1.571395735462202,
//      2.317583041477979,
//      1.1315154468682591,
//      5.44269493220745,
//      1.2587482868229616 ]
ran.dist.Distribution.skewness()

The theoretical skewness of the distribution:

\gamma_1 = \frac{\mathrm{E}[(X-\mu)^3]}{\sigma^3} = \frac{\mathrm{E}[X^3] - 3\mu,\mathrm{E}[X^2] + 2\mu^3}{\sigma^3}.

Returns NaN when undefined (zero variance, or moment does not exist). Distributions with non-finite moments must override this method.

Returns

number

The theoretical skewness.

ran.dist.Distribution.support()

Returns the support of the probability distribution (based on the current parameters). Note that the support for the probability distribution is not necessarily the same as the support of the cumulative distribution.

Returns

undefined[]

An array of objects describing the lower and upper boundary of the support. Each object contains a value: number and a closed: boolean property with the value of the boundary and whether it is closed, respectively. When value is (+/-)Infinity, closed is always false.

ran.dist.Distribution.survival(x)

The survival function:

S(x) = 1 - F(x),

where F(x) denotes the cumulative distribution function.

Parameters

NameTypeDescription
xnumber

Value to evaluate survival function at.

Returns

number

The survival value.

Examples

let pareto = new ran.dist.Pareto(1, 2)
pareto.survival(3)
// => 0.11111111111111116
ran.dist.Distribution.test(values)

Tests if an array of values is sampled from the specified distribution. For discrete distributions this method uses \chi^2 test, whereas for continuous distributions it uses the Anderson-Darling test. In both cases, the probability of Type I error (rejecting a correct null hypotheses) is 1%.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to test.

Returns

Object representing the result of the test:

Examples

let pareto = new ran.dist.Pareto(1, 2)
let uniform = new ran.dist.UniformContinuous(1, 10);

let sample1 = pareto.sample(100)
pareto.test(sample1)
// => { statistics: 0.312, passed: true }

let sample2 = uniform.sample(100)
pareto.test(sample2)
// => { statistics: 9.47, passed: false }
ran.dist.Distribution.type()

Returns the type of the distribution (either discrete or continuous).

Returns

Distribution type.

ran.dist.Distribution.variance()

The theoretical variance of the distribution:

\sigma^2 = \mathrm{E}[X^2] - \mathrm{E}[X]^2.

Returns a non-negative finite number for well-behaved distributions, NaN when the moment is mathematically undefined, or Infinity when it diverges. Distributions with non-finite moments must override this method.

Returns

number

The theoretical variance.

ran.dist.Alpha(alpha, beta)

Probability density function for the alpha distribution:

f(x; \alpha, \beta) = \frac{\phi\Big(\alpha - \frac{\beta}{x}\Big)}{x^2 \Phi(\alpha)},

where \alpha, \beta > 0 and \phi(x), \Phi(x) denote the probability density and cumulative probability functions of the normal distribution. Support: x > 0 .

Parameters

NameTypeDescription
alphanumber

Shape parameter.

betanumber

Scale parameter.

ran.dist.Anglit(mu, beta)

Probability density function for the anglit distribution:

f(x; \mu, \beta) = \frac{1}{\beta} \cos\bigg(2 \frac{x - \mu}{\beta}\bigg),

where \mu \in \mathbb{R} and \beta > 0 . Support: x \in \Big[\mu-\frac{\beta \pi}{4}, \mu + \frac{\beta \pi}{4}\Big] .

Parameters

NameTypeDescription
munumber

Location parameter.

betanumber

Scale parameter.

ran.dist.Arcsine(a, b)

Probability density function for the arbitrarily bounded arcsine distribution:

f(x; a, b) = \frac{1}{\pi \sqrt{(x -a) (b - x)}},

where a, b \in \mathbb{R} and a < b . Support: x \in [a, b] .

Parameters

NameTypeDescription
anumber

Lower boundary.

bnumber

Upper boundary.

ran.dist.AsymmetricLaplace(mu, sigma, kappa)

Probability density function for the asymmetric Laplace distribution:

f(x; \mu, \sigma, \kappa) = \frac{\sqrt{2}\kappa}{\sigma(1+\kappa^2)} \begin{cases} e^{-\frac{\sqrt{2}\kappa}{\sigma}(\mu - x)} &\quad\text{if $x < \mu$}, \\ e^{-\frac{\sqrt{2}}{\kappa\sigma}(x - \mu)} &\quad\text{if $x \geq \mu$}, \end{cases}

where \mu \in \mathbb{R} , \sigma > 0 , and \kappa > 0 . At \kappa = 1 it reduces to \text{Laplace}(\mu, \sigma/\sqrt{2}) . Support: x \in \mathbb{R} .

Parameters

NameTypeDescription
munumber

Location parameter.

sigmanumber

Scale parameter.

kappanumber

Asymmetry parameter.

ran.dist.BaldingNichols(F, p)

Probability density function for the Balding-Nichols distribution:

f(x; \alpha, \beta) = \frac{x^{\alpha - 1} (1 - x)^{\beta - 1}}{\mathrm{B}(\alpha, \beta)},

where \alpha = \frac{1 - F}{F} p , \beta = \frac{1 - F}{F} (1 - p) and F, p \in (0, 1) . Support: x \in (0, 1) . It is simply a re-parametrization of the beta distribution.

Parameters

NameTypeDescription
Fnumber

Fixation index.

pnumber

Allele frequency.

ran.dist.Bates(n, a, b)

Probability density function for the Bates distribution:

f(x; n, a, b) = \frac{n}{(b - a)(n - 1)!} \sum_{k = 0}^{\lfloor nz \rfloor} (-1)^k \begin{pmatrix}n \\ k \\ \end{pmatrix} (nz - k)^{n - 1},

with z = \frac{x - a}{b - a} , n \in \mathbb{N}^+ and a, b \in \mathbb{R}, a < b . Support: x \in [a, b] .

Parameters

NameTypeDescription
nnumber

Number of uniform variates to sum. If not an integer, it is rounded to the nearest one.

anumber

Lower boundary of the uniform variate.

bnumber

Upper boundary of the uniform variate.

ran.dist.Benini(alpha, beta, sigma)

Probability density function for the Benini distribution:

f(x; \alpha, \beta, \sigma) = \bigg(\frac{\alpha}{x} + \frac{2 \beta \ln \frac{x}{\sigma}}{x}\bigg) e^{-\alpha \ln \frac{x}{\sigma} - \beta \ln^2 \frac{x}{\sigma}},

with \alpha, \beta, \sigma > 0 . Support: x \in (\sigma, \infty) .

Parameters

NameTypeDescription
alphanumber

First shape parameter.

betanumber

Second shape parameter.

sigmanumber

Scale parameter.

ran.dist.BenktanderII(a, b)

Probability density function for the Benktander type II distribution:

f(x; a, b) = e^{\frac{a}{b}(1 - x^b)} x^{b-2} (ax^b - b + 1),

with a > 0 and b \in (0, 1] . Support: x \in [1, \infty) .

Parameters

NameTypeDescription
anumber

Scale parameter.

bnumber

Shape parameter.

ran.dist.Bernoulli(p)

Probability mass function for the Bernoulli distribution:

f(k; p) = \begin{cases}p &\quad\text{if $k = 1$},\\1 - p &\quad\text{if $k = 0$},\\\end{cases},

where p \in [0, 1] . Support: k \in \{0, 1\} .

Parameters

NameTypeDescription
pnumber

Probability of the outcome 1.

ran.dist.Beta(alpha, beta)

Probability density function for the beta distribution:

f(x; \alpha, \beta) = \frac{x^{\alpha - 1}(1 - x)^{\beta - 1}}{\mathrm{B}(\alpha, \beta)},

with \alpha, \beta > 0 and \mathrm{B}(\alpha, \beta) is the beta function. Support: x \in (0, 1) .

Parameters

NameTypeDescription
alphanumber

First shape parameter.

betanumber

Second shape parameter.

ran.dist.BetaBinomial(n, alpha, beta)

Probability mass function for the beta-binomial distribution:

f(k; n, \alpha, \beta) = \begin{pmatrix}n \\ k \\ \end{pmatrix} \frac{\mathrm{B}(\alpha + k, \beta + n - k)}{\mathrm{B}(\alpha, \beta)},

with n \in \mathbb{N}_0 and \alpha, \beta > 0 . Support: k \in {0, ..., n} .

Parameters

NameTypeDescription
nnumber

Number of trials.

alphanumber

First shape parameter.

betanumber

Second shape parameter.

ran.dist.BetaGeometric(alpha, beta)

Probability mass function for the beta-geometric distribution:

f(k; \alpha, \beta) = \frac{\mathrm{B}(\alpha + 1, \beta + k - 1)}{\mathrm{B}(\alpha, \beta)},

with \alpha, \beta > 0 . Support: k \in {1, 2, 3, \ldots} .

Parameters

NameTypeDescription
alphanumber

First shape parameter.

betanumber

Second shape parameter.

ran.dist.BetaNegativeBinomial(r, alpha, beta)

Probability mass function for the beta-negative-binomial distribution:

f(k; r, \alpha, \beta) = \frac{\Gamma(r + k)}{\Gamma(k + 1) \Gamma(r)} \frac{\mathrm{B}(\alpha + r, \beta + k)}{\mathrm{B}(\alpha, \beta)},

with r \in \mathbb{N}^+ and \alpha, \beta > 0 . Support: k \in \mathbb{N}_0 .

Parameters

NameTypeDescription
rnumber

Number of successes (rounded to nearest integer).

alphanumber

First shape parameter.

betanumber

Second shape parameter.

ran.dist.BetaPrime(alpha, beta)

Probability density function for the beta prime distribution (also known as inverted beta):

f(x; \alpha, \beta) = \frac{x^{\alpha - 1}(1 + x)^{-\alpha - \beta}}{\mathrm{B}(\alpha, \beta)},

with \alpha, \beta > 0 and \mathrm{B}(x, y) is the beta function. Support: x > 0 .

Parameters

NameTypeDescription
alphanumber

First shape parameter.

betanumber

Second shape parameter.

ran.dist.BetaRectangular(alpha, beta, theta, a, b)

Probability density function for the beta-rectangular distribution:

f(x; \alpha, \beta, \theta, a, b) = \theta \frac{(x - a)^{\alpha - 1} (b - x)^{\beta - 1}}{\mathrm{B}(\alpha, \beta) (b - a)^{\alpha + \beta - 1}} + \frac{1 - \theta}{b - a},

with \alpha, \beta > 0 , \theta \in [0, 1] , a, b \in \mathbb{R} , a < b and \mathrm{B}(x, y) is the beta function. Support: x \in [a, b] .

Parameters

NameTypeDescription
alphanumber

First shape parameter.

betanumber

Second shape parameter.

thetanumber

Mixture parameter.

anumber

Lower boundary of the support.

bnumber

Upper boundary of the support.

ran.dist.Binomial(n, p)

Probability mass function for the binomial distribution:

f(k; n, p) = \begin{pmatrix}n \\ k \\ \end{pmatrix} p^k (1 - p)^{n - k},

with n \in \mathbb{N}_0 and p \in [0, 1] . Support: k \in {0, ..., n} .

Parameters

NameTypeDescription
nnumber

Number of trials.

pnumber

Probability of success.

ran.dist.BirnbaumSaunders(mu, beta, gamma)

Probability density function for the Birnbaum-Saunders distribution (also known as fatigue life distribution):

f(x; \mu, \beta, \gamma) = \frac{z + 1 / z}{2 \gamma (x - \mu)} \phi\Big(\frac{z - 1 / z}{\gamma}\Big),

with \mu \in \mathbb{R} , \beta, \gamma > 0 , z = \sqrt{\frac{x - \mu}{\beta}} and \phi(x) is the probability density function of the standard normal distribution. Support: x \in (\mu, \infty) .

Parameters

NameTypeDescription
munumber

Location parameter.

betanumber

Scale parameter.

gammanumber

Shape parameter.

ran.dist.Borel(mu)

Probability mass function for the Borel distribution:

f(k; \mu) = \frac{e^{-\mu k} (\mu k)^{k - 1}}{k!},

where \mu \in [0, 1] . Support: k \in \mathbb{N}^+ .

Parameters

NameTypeDescription
munumber

Distribution parameter.

ran.dist.BorelTanner(mu, n)

Probability mass function for the Borel-Tanner distribution:

f(k; \mu, n) = \frac{n}{k}\frac{e^{-\mu k} (\mu k)^{k - n}}{(k - n)!},

where \mu \in [0, 1] and n \in \mathbb{N}^+ . Support: k \ge n .

Parameters

NameTypeDescription
munumber

Distribution parameter.

nnumber

Number of Borel distributed variates to add. If not an integer, it is rounded to the nearest one.

ran.dist.BoundedPareto(L, H, alpha)

Probability density function for the bounded Pareto distribution:

f(x; L, H, \alpha) = \frac{\alpha L^\alpha x^{-\alpha - 1}}{1 - \big(\frac{L}{H}\big)^\alpha},

with L, H > 0 , H > L and \alpha > 0 . Support: x \in [L, H] .

Parameters

NameTypeDescription
Lnumber

Lower boundary.

Hnumber

Upper boundary.

alphanumber

Shape parameter.

ran.dist.Bradford(c)

Probability density function for the Bradford distribution:

f(x; c) = \frac{c}{\ln(1 + c) (1 + c x)},

with c > 0 . Support: x \in [0, 1] .

Parameters

NameTypeDescription
cnumber

Shape parameter.

ran.dist.Burr(c, k)

Probability density function for the Burr (XII) distribution (also known as Singh-Maddala distribution):

f(x; c, k) = c k \frac{x^{c - 1}}{(1 + x^c)^{k + 1}},

with c, k > 0 . Support: x > 0 .

Parameters

NameTypeDescription
cnumber

First shape parameter.

knumber

Second shape parameter.

ran.dist.Categorical(weights, min)

Generator for a categorical distribution:

f(k; {w}) = \frac{w_k}{\sum_j w_j},

where w_k > 0 . Support: k \in \mathbb{N}_0 .

Parameters

NameTypeDescription
weightsnumber[]

Weights for the distribution (doesn't need to be normalized).

minnumber

Lowest value to sample (support starts at this value).

ran.dist.Cauchy(x0, gamma)

Probability density function for the Cauchy distribution:

f(x; x_0, \gamma) = \frac{1}{\pi\gamma\bigg[1 + \Big(\frac{x - x_0}{\gamma}\Big)^2\bigg]}

where x_0 \in \mathbb{R} and \gamma > 0 . Support: x \in \mathbb{R} .

Parameters

NameTypeDescription
x0number

Location parameter.

gammanumber

Scale parameter.

ran.dist.Champernowne(alpha, lambda, x0)

Probability density function for the Champernowne distribution:

f(x; \alpha, \lambda, x_0) = \frac{C}{\cosh(\alpha(x - x_0)) + \lambda},

with normalization constant C = \frac{\alpha\sqrt{1 - \lambda^2}}{2\arccos(\lambda)} , where \alpha > 0 , 0 \le \lambda < 1 , and x_0 \in \mathbb{R} . Support: x \in \mathbb{R} .

Parameters

NameTypeDescription
alphanumber

Shape parameter. Must be positive.

lambdanumber

Asymmetry parameter. Must satisfy 0 <= lambda < 1.

x0number

Location parameter.

ran.dist.Chi(k)

Probability density function for the \chi distribution:

f(x; k) = \frac{1}{2^{k/2 - 1} \Gamma(k/2)} x^{k - 1} e^{-x^2/2},

where k \in \mathbb{N}^+ . Support: x > 0 .

Parameters

NameTypeDescription
knumber

Degrees of freedom. If not an integer, is rounded to the nearest integer.

ran.dist.Chi2(k)

Probability density function for the \chi^2 distribution:

f(x; k) = \frac{1}{2^{k/2} \Gamma(k/2)} x^{k/2 - 1} e^{-x/2},

where k \in \mathbb{N}^+ . Support: x > 0 .

Parameters

NameTypeDescription
knumber

Degrees of freedom. If not an integer, is rounded to the nearest one.

ran.dist.ConwayMaxwellPoisson(lambda, nu)

Probability mass function for the Conway-Maxwell-Poisson distribution:

f(k; \lambda, \nu) = \frac{\lambda^k}{(k!)^\nu Z(\lambda, \nu)},

where \lambda > 0 , \nu > 0 , and Z(\lambda, \nu) = \sum_{j=0}^\infty \frac{\lambda^j}{(j!)^\nu} . Support: k \in \mathbb{N}_0 .

Parameters

NameTypeDescription
lambdanumber

Rate parameter (lambda > 0).

nunumber

Dispersion parameter (nu > 0). nu = 1 gives Poisson, nu > 1 gives underdispersion.

ran.dist.Dagum(p, a, b)

Probability density function for the Dagum distribution:

f(x; p, a, b) = \frac{ap}{x} \frac{\big(\frac{x}{b}\big)^{ap}}{\Big[\big(\frac{x}{b}\big)^a + 1\Big]^{p + 1}},

with p, a, b > 0 . Support: x > 0 .

Parameters

NameTypeDescription
pnumber

First shape parameter.

anumber

Second shape parameter.

bnumber

Scale parameter.

ran.dist.Davis(mu, b, n)

Probability density function for the Davis distribution:

f(x; \mu, b, n) = \frac{b^n (x - \mu)^{-1-n}}{\Gamma(n) \zeta(n) (e^{b/(x-\mu)} - 1)},

with \mu > 0 , b > 0 , and n > 1 . Support: x \in (\mu, \infty) .

Parameters

NameTypeDescription
munumber

Location parameter.

bnumber

Scale parameter.

nnumber

Shape parameter. Must be greater than 1.

ran.dist.Degenerate(x0)

Probability density function for the degenerate distribution:

f(x; x_0) = \begin{cases}1 &\quad\text{if $x = x_0$}\\0 &\quad\text{otherwise}\\\end{cases},

where x_0 \in \mathbb{R} . Support: x \in \mathbb{R} .

Parameters

NameTypeDescription
x0number

Location of the distribution.

ran.dist.Delaporte(alpha, beta, lambda)

Probability mass function for the Delaporte distribution:

f(k; \alpha, \beta, \lambda) = \frac{e^{-\lambda}}{\Gamma(\alpha)}\sum_{j = 0}^k \frac{\Gamma(\alpha + j) \beta^j \lambda^{k - j}}{j! (1 + \beta)^{\alpha + j} (k - j)!},

with \alpha, \beta, \lambda > 0 . Support: k \in \mathbb{N}_0 .

Parameters

NameTypeDescription
alphanumber

Shape parameter of the gamma component. Default component is 1.

betanumber

Scale parameter of the gamma component.

lambdanumber

Mean of the Poisson component.

ran.dist.DiscreteLaplace(p, mu)

Probability mass function for the discrete Laplace distribution (also called the bilateral geometric distribution):

f(k; p, \mu) = \frac{1-p}{1+p} p^{|k - \mu|},

with p \in (0, 1) and \mu \in \mathbb{Z} . Support: k \in \mathbb{Z} .

Parameters

NameTypeDescription
pnumber

Geometric decay parameter.

munumber

Integer location parameter. If not an integer, it is rounded to the nearest one.

ran.dist.DiscreteUniform(xmin, xmax)

Probability mass function for the discrete uniform distribution:

f(k; x_\mathrm{min}, x_\mathrm{max}) = \frac{1}{x_\mathrm{max} - x_\mathrm{min} + 1},

with x_\mathrm{min}, x_\mathrm{max} \in \mathbb{Z} and x_\mathrm{min} < x_\mathrm{max} . Support: k \in {x_\mathrm{min}, ..., x_\mathrm{max}} .

Parameters

NameTypeDescription
xminnumber

Lower boundary. If not an integer, it is rounded to the nearest one.

xmaxnumber

Upper boundary. If not an integer, it is rounded to the nearest one.

ran.dist.DiscreteWeibull(q, beta)

Probability mass function for the discrete Weibull distribution (using the original parametrization):

f(k; q, \beta) = q^{k^\beta} - q^{(k + 1)^\beta},

with q \in (0, 1) and \beta > 0 . Support: k \in \mathbb{N}_0 .

Parameters

NameTypeDescription
qnumber

First shape parameter.

betanumber

Second shape parameter.

ran.dist.DoubleGamma(alpha, beta)

Probability density function for the double gamma distribution (same shape/rate parametrization as used by the gamma distribution):

f(x; \alpha, \beta) = \frac{\beta^\alpha}{2 \Gamma(\alpha)} |x|^{\alpha - 1} e^{-\beta |x|},

where \alpha, \beta > 0 . Support: x \in \mathbb{R} .

Parameters

NameTypeDescription
alphanumber

Shape parameter.

betanumber

Rate parameter.

ran.dist.DoubleWeibull(lambda, k)

Probability density function for the double Weibull distribution:

f(x; \lambda, k) = \frac{k}{\lambda}\bigg(\frac{|x|}{\lambda}\bigg)^{k - 1} e^{-(|x| / \lambda)^k},

with \lambda, k > 0 . Support: x \in \mathbb{R} .

Parameters

NameTypeDescription
lambdanumber

Scale parameter.

knumber

Shape parameter.

ran.dist.DoublyNoncentralBeta(alpha, beta, lambda1, lambda2)

Probability density function for the doubly non-central beta distribution:

f(x; \alpha, \beta, \lambda_1, \lambda_2) = e^{-\frac{\lambda_1 + \lambda_2}{2}} \sum_{k = 0}^\infty \sum_{l = 0}^\infty \frac{\big(\frac{\lambda_1}{2}\big)^k}{k!} \frac{\big(\frac{\lambda_2}{2}\big)^l}{l!} \frac{x^{\alpha + k - 1} (1 - x)^{\beta + l - 1}}{\mathrm{B}\big(\alpha + k, \beta + l\big)},

where \alpha, \beta > 0 and \lambda_1, \lambda_2 \ge 0 . Support: x \in (0, 1) .

Parameters

NameTypeDescription
alphanumber

First shape parameter.

betanumber

Second shape parameter.

lambda1number

First non-centrality parameter.

lambda2number

Second non-centrality parameter.

ran.dist.DoublyNoncentralBeta._powellOptions()

Bounds fit()'s Powell search budget. On data that genuinely mismatches this family (also inherited by DoublyNoncentralF, which delegates its _pdf/_cdf here), the nested double-Poisson-mixing log-likelihood carries a long, near-flat ridge between the shape and non-centrality parameters: a full-precision Powell search (the base class's default tol=1e-8, maxIter=200) chases negligible log-likelihood gains along this ridge almost indefinitely, at ever-increasing per-point cost since larger non-centrality parameters require more series terms to evaluate (#1063). Empirically, tol=1e-2/maxIter=15 recovers parameters within this class's existing fit tolerances on well-matched data (matching the default optimizer's result within ordinary finite-sample noise) while bounding worst-case cost to roughly 1-2s instead of 13-30s+ on mismatched data. See solutions/performance/2026-07-22-0702-doubly-noncentral-fit-powell-ridge-cost.md

maxIter also bounds each inner Brent line search powell() runs per outer sweep, not just the outer sweep count itself (#1078). Investigated across 35 well-matched fits (7 parameter sets x 5 seeds): a decoupled, much larger inner-Brent budget produced bit-identical results, confirming maxIter=15 is not starving convergence there. On the same family-mismatched ridge data this fix targets, a larger inner budget did recover a meaningfully better log-likelihood (~16-32%) — but at the cost of reintroducing multi-second-plus fit() runs on that same data, i.e. exactly the cost blowup this fix exists to bound. The coupled maxIter=15 is kept as-is: on mismatched data, looser convergence is the deliberate, already-documented tradeoff above, not an unrelated defect to fix separately. See solutions/performance/2026-07-22-1600-doubly-noncentral-fit-inner-line-search-budget.md

Returns

Object

The bounded Powell search options.

ran.dist.DoublyNoncentralChi2(k1, k2, lambda1, lambda2)

Probability density function for the doubly non-central \chi^2 distribution:

f(x; k_1, k_2, \lambda_1, \lambda_2) = e^{-\frac{\lambda_1 + \lambda_2}{2}} \sum_{j = 0}^\infty \sum_{l = 0}^\infty \frac{\big(\frac{\lambda_1}{2}\big)^j}{j!} \frac{\big(\frac{\lambda_2}{2}\big)^l}{l!} f_{\chi^2}\big(x; k_1 + k_2 + 2j + 2l\big),

where f_{\chi^2}(x; \nu) is the central \chi^2 density with \nu degrees of freedom, k_1, k_2 \in \mathbb{N}^+ and \lambda_1, \lambda_2 \ge 0 . Support: x \in [0, \infty) .

Parameters

NameTypeDescription
k1number

First degrees of freedom. If not an integer, it is rounded to the nearest one.

k2number

Second degrees of freedom. If not an integer, it is rounded to the nearest one.

lambda1number

First non-centrality parameter.

lambda2number

Second non-centrality parameter.

ran.dist.DoublyNoncentralF(d1, d2, lambda1, lambda2)

Probability density function for the doubly non-central F distribution:

f(x; d_1, d_2, \lambda_1, \lambda_2) = \frac{d_1}{d_2} e^{-\frac{\lambda_1 + \lambda_2}{2}} \sum_{k = 0}^\infty \sum_{l = 0}^\infty \frac{\big(\frac{\lambda_1}{2}\big)^k}{k!} \frac{\big(\frac{\lambda_2}{2}\big)^l}{l!} \frac{\big(\frac{d_1 x}{d_2}\big)^{\frac{d_1}{2} + k - 1}}{\big(1 + \frac{d_1 x}{d_2}\big)^{\frac{d_1 + d_2}{2} + k + l}} \frac{1}{\mathrm{B}\big(\frac{d_1}{2} + k, \frac{d_2}{2} + l\big)},

where d_1, d_2 \in \mathbb{N}^+ and \lambda_1, \lambda_2 \ge 0 . Support: x > 0 .

Parameters

NameTypeDescription
d1number

First degrees of freedom. If not an integer, it is rounded to the nearest one.

d2number

Second degrees of freedom. If not an integer, it is rounded to the nearest one.

lambda1number

First non-centrality parameter.

lambda2number

Second non-centrality parameter.

ran.dist.DoublyNoncentralT(nu, mu, theta)

Probability density function for the doubly non-central t distribution:

f(x; \nu, \mu, \theta) = \frac{e^{-\frac{\theta + \mu^2}{2}}}{\sqrt{\pi \nu}} \sum_{j = 0}^\infty \frac{1}{j!} \frac{(x \mu \sqrt{2 / \nu})^j}{(1 + x^2 / \nu)^{\frac{\nu + j + 1}{2}}} \frac{\Gamma\big(\frac{\nu + j + 1}{2}\big)}{\Gamma\big(\frac{\nu}{2}\big)} {}_1F_1\bigg(\frac{\nu + j + 1}{2}, \frac{\nu}{2}; \frac{\theta}{2 (1 + x^2 / \nu)}\bigg),

where \nu \in \mathbb{N}^+ , \mu \in \mathbb{R} and \theta > 0 . Support: x \in \mathbb{R} .

Parameters

NameTypeDescription
nunumber

Degrees of freedom. If not an integer, it is rounded to the nearest one.

munumber

Location parameter.

thetanumber

Shape parameter.

ran.dist.Erlang(k, lambda)

Probability density function for the Erlang distribution:

f(x; k, \lambda) = \frac{\lambda^k x^{k - 1} e^{-\lambda x}}{(k - 1)!},

where k \in \mathbb{N}^+ and \lambda > 0 . Support: x \ge 0 .

Parameters

NameTypeDescription
knumber

Shape parameter. It is rounded to the nearest integer.

lambdanumber

Rate parameter.

ran.dist.Exponential(lambda)

Probability density function for the exponential distribution:

f(x; \lambda) = \lambda e^{-\lambda x},

with \lambda > 0 . Support: x \ge 0 .

Parameters

NameTypeDescription
lambdanumber

Rate parameter.

ran.dist.ExponentialLogarithmic(p, beta)

Probability density function for the exponential-logarithmic distribution:

f(x; p, \beta) = -\frac{1}{\ln p} \frac{\beta (1 - p) e^{-\beta x}}{1 - (1 - p) e^{-\beta x}},

with p \in (0, 1) and \beta > 0 . Support: x \ge 0 .

Parameters

NameTypeDescription
pnumber

Shape parameter.

betanumber

Scale parameter.

ran.dist.ExponentiallyModifiedGaussian(mu, sigma, lambda)

Probability density function for the exponentially modified Gaussian distribution:

f(x; \mu, \sigma, \lambda) = \frac{\lambda}{2} e^{\frac{\lambda}{2} (2 \mu + \lambda \sigma^2 - 2 x)} \mathrm{erfc}\Big(\frac{\mu + \lambda \sigma^2 - x}{\sqrt{2} \sigma}\Big),

with \mu \in \mathbb{R} , \sigma > 0 and \lambda > 0 . Support: x \in \mathbb{R} .

The distribution is the convolution of a \mathrm{Normal}(\mu, \sigma^2) and an \mathrm{Exponential}(\lambda) random variable.

Parameters

NameTypeDescription
munumber

Location parameter of the Gaussian component.

sigmanumber

Scale parameter of the Gaussian component.

lambdanumber

Rate parameter of the exponential component.

ran.dist.ExponentiatedWeibull(lambda, k, alpha)

Probability density function for the exponentiated Weibull distribution:

f(x; \lambda, k) = \alpha \frac{k}{\lambda}\bigg(\frac{x}{\lambda}\bigg)^{k - 1} \bigg[1 - e^{-(x / \lambda)^k}\bigg]^{\alpha - 1} e^{-(x / \lambda)^k},

with \lambda, k, \alpha > 0 . Support: x \ge 0 .

Parameters

NameTypeDescription
lambdanumber

Scale parameter.

knumber

First shape parameter.

alphanumber

Second shape parameter.

ran.dist.F(d1, d2)

Probability density function for the F distribution (or Fisher-Snedecor's F distribution):

f(x; d_1, d_2) = \frac{\sqrt{\frac{(d_1 x)^{d_1} d_2^{d_2}}{(d_1x + d_2)^{d_1 + d_2}}}}{x \mathrm{B}\big(\frac{d_1}{2}, \frac{d_2}{2}\big)},

with d_1, d_2 > 0 . Support: x > 0 .

Parameters

NameTypeDescription
d1number

First degree of freedom. If not an integer, it is rounded to the nearest one.

d2number

Second degree of freedom. If not an integer, it is rounded to the nearest one.

ran.dist.FisherZ(d1, d2)

Generator for Fisher's z distribution:

f(x; d_1, d_2) = \sqrt{\frac{d_1^{d_1} d_2^{d_2}}{(d_1 e^{2 x} + d_2)^{d_1 + d_2}}} \frac{2 e^{d_1 x}}{\mathrm{B}\big(\frac{d_1}{2}, \frac{d_2}{2}\big)},

with d_1, d_2 > 0 . Support: x \in \mathbb{R} .

Parameters

NameTypeDescription
d1number

First degree of freedom.

d2number

Second degree of freedom.

ran.dist.FlorySchulz(a)

Probability mass function for the Flory-Schulz distribution:

f(k; a) = a^2 k (1 - a)^{k - 1},

with a \in (0, 1) . Support: k \in \mathbb{N}^+ .

Parameters

NameTypeDescription
anumber

Shape parameter.

ran.dist.Frechet(alpha, s, m)

Probability density function for the Frechet distribution:

f(x; \alpha, s, m) = \frac{\alpha z^{-1 -\alpha} e^{-z^{-\alpha}}}{s},

with z = \frac{x - m}{s} . and \alpha, s > 0 , m \in \mathbb{R} . Support: x \in \mathbb{R}, x > m .

Parameters

NameTypeDescription
alphanumber

Shape parameter.

snumber

Scale parameter.

mnumber

Location parameter.

ran.dist.Gamma(alpha, beta)

Probability density function for the gamma distribution using the shape/rate parametrization:

f(x; \alpha, \beta) = \frac{\beta^\alpha}{\Gamma(\alpha)} x^{\alpha - 1} e^{-\beta x},

where \alpha, \beta > 0 . Support: x > 0 .

Parameters

NameTypeDescription
alphanumber

Shape parameter.

betanumber

Rate parameter.

ran.dist.GammaGompertz(b, s, beta)

Probability density function for the Gamma/Gompertz distribution:

f(x; b, s, \beta) = \frac{b s e^{b x} \beta^s}{(\beta - 1 + e^{b x})^{s + 1}},

with b, s, \beta > 0 . Support: x \ge 0 .

Parameters

NameTypeDescription
bnumber

Scale parameter.

snumber

First shape parameter.

betanumber

Second shape parameter.

ran.dist.GeneralizedExponential(a, b, c)

Probability density function for the generalized exponential distribution:

f(x; a, b, c) = \big(a + b (1 - e^{-c x})\big) e^{-(a + b)x + \frac{b}{c} (1 - e^{-c x})},

where a, b, c > 0 . Support> x \ge 0 .

Parameters

NameTypeDescription
anumber

First shape parameter.

bnumber

Second shape parameter.

cnumber

Third shape parameter.

ran.dist.GeneralizedExtremeValue(c)

Probability density function for the generalized extreme value distribution:

f(x; c) = (1 - cx)^{1 / c - 1} e^{-(1 - cx)^{1 / c}},

with c \ne 0 . Support: x \in (-\infty, 1 / c] if c > 0 , x \in [1 / c, \infty) otherwise.

Parameters

NameTypeDescription
cnumber

Shape parameter.

ran.dist.GeneralizedGamma(a, d, p)

Probability density function for the generalized gamma distribution:

f(x; a, d, p) = \frac{p/a^d}{\Gamma(d/p)} x^{d - 1} e^{-(x/a)^p},

where a, d, p > 0 . Support: x > 0 .

Parameters

NameTypeDescription
anumber

Scale parameter.

dnumber

Shape parameter.

pnumber

Shape parameter.

ran.dist.GeneralizedHermite(a1, a2, m)

Probability mass function for the generalized Hermite distribution:

f(k; a_1, a_m, m) = p_0 \frac{\mu^k (m - d)^k}{(m - 1)^k} \sum_{j = 0}^{\lfloor k / m \rfloor} \frac{(d - 1)^j (m - 1)^{(m - 1)j}}{m^j \mu^{(m - 1)j} (m - d)^{mj} (k - mj)! j!},

where p_0 = e^{\mu \big[\frac{d - 1}{m} - 1\big]} , \mu = a_1 + m a_m , d = \frac{a_1 + m^2 a_m}{a_1 + m a_m} , a_1, a_m > 0 and m \in \mathbb{N}^+ \setminus { 1 } . Support: k \in \mathbb{N} .

Parameters

NameTypeDescription
a1number

Mean of the first Poisson component.

a2number

Mean of the second Poisson component.

mnumber

Multiplier of the second Poisson. If not an integer, it is rounded to the nearest one.

ran.dist.GeneralizedLogistic(mu, s, c)

Probability density function for the generalized logistic distribution:

f(x; \mu, s, c) = \frac{c e^{-z}}{s (1 + e^{-z})^{c + 1}},

with z = \frac{x - \mu}{s} , \mu \in \mathbb{R} and s, c > 0 . Support: x \in \mathbb{R} .

Parameters

NameTypeDescription
munumber

Location parameter.

snumber

Scale parameter.

cnumber

Shape parameter.

ran.dist.GeneralizedNormal(mu, alpha, beta)

Probability density function for the generalized normal distribution:

f(x; \mu, \alpha, \beta) = \frac{\beta}{2 \alpha \Gamma\big(\frac{1}{\beta}\big)} e^{-\big(\frac{|x - \mu|}{\alpha}\big)^\beta},

where \mu \in \mathbb{R} and \alpha, \beta > 0 . Support: x \in \mathbb{R} .

Parameters

NameTypeDescription
munumber

Location paramameter.

alphanumber

Scale parameter.

betanumber

Shape parameter.

ran.dist.GeneralizedPareto(mu, sigma, xi)

Probability density function for the generalized Pareto distribution:

f(x; \mu, \sigma, \xi) = \begin{cases}\frac{1}{\sigma} (1 + \xi z)^{-(1/\xi + 1)} &\quad\text{if $\xi \ne 0$},\\\frac{1}{\sigma} e^{-z} &\quad\text{if $\xi = 0$}\\\end{cases},

with \mu, \xi \in \mathbb{R} , \sigma > 0 and z = \frac{x - \mu}{\sigma} . Support: x \in [\mu, \infty) if \xi \ge 0 , x \in [\mu, \mu - \sigma / \xi] otherwise.

Parameters

NameTypeDescription
munumber

Location parameter.

sigmanumber

Scale parameter.

xinumber

Shape parameter.

ran.dist.Geometric(p)

Probability mass function for the geometric distribution (the number of failures before the first success definition):

f(k; p) = p (1 - p)^k,

with p \in (0, 1] . Support: k \in {0, 1, 2, ...} .

Parameters

NameTypeDescription
pnumber

Probability of success.

ran.dist.Gilbrat()

Probability density function for the Gilbrat's distribution:

f(x) = \frac{1}{x \sqrt{2 \pi}}e^{-\frac{\ln x^2}{2}}.

Support: x > 0 .

ran.dist.Gompertz(eta, b)

Probability density function for the Gompertz distribution:

f(x; \eta, b) = b \eta e^{\eta + bx - \eta e^{bx}} ,

with \eta, b > 0 . Support: x \ge 0 .

Parameters

NameTypeDescription
etanumber

Shape parameter.

bnumber

Scale parameter.

ran.dist.Gumbel(mu, beta)

Probability density function for the Gumbel distribution:

f(x; \mu, \beta) = \frac{1}{\beta} e^{-(z + e^{-z})},

with z = \frac{x - \mu}{\beta} and \mu \in \mathbb{R} , \beta > 0 . Support: x \in \mathbb{R} .

Parameters

NameTypeDescription
munumber

Location parameter.

betanumber

Scale parameter.

ran.dist.HalfGeneralizedNormal(alpha, beta)

Probability density function for the half generalized normal distribution:

f(x; \alpha, \beta) = \frac{\beta}{\alpha \Gamma\big(\frac{1}{\beta}\big)} e^{-\big(\frac{x}{\alpha}\big)^\beta},

with \alpha, \beta > 0 . Support: x > 0 .

Parameters

NameTypeDescription
alphanumber

Scale parameter.

betanumber

Shape parameter.

ran.dist.HalfLogistic()

Probability density function for the half-logistic distribution:

f(x) = \frac{2 e^{-x}}{(1 + e^{-x})^2}.

Support: x \in [0, \infty) .

ran.dist.HalfNormal(sigma)

Probability density function for the half-normal distribution:

f(x; \sigma) = \frac{\sqrt{2}}{\sigma\sqrt{\pi}} e^{-\frac{x^2}{2\sigma^2}},

with \sigma > 0 . Support: x \ge 0 .

Parameters

NameTypeDescription
sigmanumber

Scale parameter.

ran.dist.HeadsMinusTails(n)

Probability mass function for the absolute-value (folded) heads-minus-tails distribution:

f(k; n) = \begin{cases}\Big(\frac{1}{2}\Big)^{2n} \begin{pmatrix}2n \\ n \\ \end{pmatrix} &\quad\text{if $k = 0$},\\2 \Big(\frac{1}{2}\Big)^{2n} \begin{pmatrix}2n \\ m + n \\ \end{pmatrix} &\quad\text{if $k = 2m$},\\0 &\quad\text{else}\\ \end{cases}

where n \in \mathbb{N}^+ . Support: k \in [0, 2n] .

Parameters

NameTypeDescription
nnumber

Half number of trials (n > 0).

Deprecated

Use ran.dist.Nakagami instead. This class will be removed in a future major release.

ran.dist.Hoyt(q, omega)

Probability density function for the Nakagami distribution (previously mis-labelled as the Hoyt distribution):

f(x; m, \omega) = \frac{2m^m}{\Gamma(m) \omega^m} x^{2m - 1} e^{-\frac{m}{\omega} x^2},

where m \ge 0.5 and \omega > 0 . Support: x > 0 .

Parameters

NameTypeDescription
qnumber

Shape parameter (same as m in Nakagami).

omeganumber

Spread parameter.

References

ran.dist.HyperbolicSecant()

Probability density function for the hyperbolic secant distribution:

f(x) = \frac{1}{2}\mathrm{sech}\Big(\frac{\pi}{2} x\Big).

Support: x \in \mathbb{R} .

ran.dist.Hypergeometric(N, K, n)

Probability mass function for the hypergeometric distribution:

f(k; N, K, n) = \frac{\begin{pmatrix}K \\ k \\ \end{pmatrix} \begin{pmatrix}N - k \\ n - k \\ \end{pmatrix}}{\begin{pmatrix}N \\ n \\ \end{pmatrix}},

with N \in \mathbb{N}^+ , K \in {0, 1, ..., N} and n \in {0, 1, ..., N} . Support: k \in {\mathrm{max}(0, n+K-N), ..., \mathrm{min}(n, K)} .

Parameters

NameTypeDescription
Nnumber

Total number of elements to sample from. If not an integer, it is rounded to the nearest one.

Knumber

Total number of successes. If not an integer, it is rounded to the nearest one.

nnumber

Number of draws. If not an integer, it is rounded to the nearest one.

ran.dist.InverseChi2(nu)

Probability density function for the inverse \chi^2 distribution:

f(x; \nu) = \frac{2^{-\nu/2}}{\Gamma(\nu / 2)} x^{-\nu/2 - 1} e^{-1/(2x)},

with \nu \in \mathbb{N}^+ . Support: x > 0 .

Parameters

NameTypeDescription
nunumber

Degrees of freedom.

ran.dist.InverseGamma(alpha, beta)

Probability density function for the inverse gamma distribution:

f(x; \alpha, \beta) = \frac{\beta^\alpha}{\Gamma(\alpha)} x^{-\alpha - 1} e^{-\beta/x},

where \alpha, \beta > 0 . Support: x > 0 .

Parameters

NameTypeDescription
alphanumber

Shape parameter.

betanumber

Scale parameter.

ran.dist.InverseGaussian(mu, lambda)

Probability density function for the Wald or inverse Gaussian distribution:

f(x; \lambda, \mu) = \bigg[\frac{\lambda}{2 \pi x^3}\bigg]^{1/2} e^{\frac{-\lambda (x - \mu)^2}{2 x \mu^2}},

with \mu, \lambda > 0 . Support: x > 0 .

Parameters

NameTypeDescription
munumber

Mean of the distribution.

lambdanumber

Shape parameter.

ran.dist.InvertedWeibull(c)

Probability density function for the inverted Weibull distribution:

f(x; c) = c x^{-c - 1} e^{-x^{-c}},

with c > 0 . Support: x \ge 0 .

Parameters

NameTypeDescription
cnumber

Shape parameter.

ran.dist.JohnsonSB(gamma, delta, lambda, xi)

Generator for Johnson's S_B distribution:

f(x; \gamma, \delta, \lambda, \xi) = \frac{\delta \lambda}{\sqrt{2 \pi} z (\lambda - z)} e^{-\frac{1}{2}\big[\gamma + \delta \ln \frac{z}{\lambda - z}\big]^2},

with \gamma, \xi \in \mathbb{R} , \delta, \lambda > 0 and z = x - \xi . Support: x \in (\xi, \xi + \lambda) .

Parameters

NameTypeDescription
gammanumber

First location parameter.

deltanumber

First scale parameter.

lambdanumber

Second scale parameter.

xinumber

Second location parameter.

ran.dist.JohnsonSU(gamma, delta, lambda, xi)

Generator for Johnson's S_U distribution:

f(x; \gamma, \delta, \lambda, \xi) = \frac{\delta}{\lambda \sqrt{2 \pi}} \frac{e^{-\frac{1}{2}\big[\gamma + \delta \mathrm{sinh}^{-1} z \big]^2}}{\sqrt{1 + z^2}},

with \gamma, \xi \in \mathbb{R} , \delta, \lambda > 0 and z = \frac{x - \xi}{\lambda} . Support: x \in \mathbb{R} .

Parameters

NameTypeDescription
gammanumber

First location parameter.

deltanumber

First scale parameter.

lambdanumber

Second scale parameter.

xinumber

Second location parameter.

ran.dist.Kolmogorov()

Probability density function for the Kolmogorov distribution:

f(x) = 8 \sum_{k=1}^\infty (-1)^{k - 1} k^2 x e^{-2 k^2 x^2}.

Support: x > 0 .

ran.dist.Kumaraswamy(a, b)

Probability density function for the Kumaraswamy distribution (also known as Minimax distribution):

f(x; a, b) = a b x^{a-1} (1 - x^a)^{b - 1},

with a, b > 0 . Support: x \in (0, 1) .

Parameters

NameTypeDescription
anumber

First shape parameter.

bnumber

Second shape parameter.

ran.dist.Laplace(mu, b)

Probability density function for the Laplace distribution (also known as double exponential distribution):

f(x; \mu, b) = \frac{1}{2b}e^{-\frac{|x - \mu|}{b}},

where \mu \in \mathbb{R} and b > 0 . Support: x \in \mathbb{R} .

Parameters

NameTypeDescription
munumber

Location parameter.

bnumber

Scale parameter.

ran.dist.Levy(mu, c)

Probability density function for the Lévy distribution:

f(x; \mu, c) = \sqrt{\frac{c}{2 \pi}}\frac{e^{-\frac{c}{2(x - \mu)}}}{(x - \mu)^{3/2}},

with \mu \in \mathbb{R} and c > 0 . Support: x \in [\mu, \infty) .

Parameters

NameTypeDescription
munumber

Location parameter.

cnumber

Scale parameter.

ran.dist.Lindley(theta)

Probability density function for the Lindley distribution:

f(x; \theta) = \frac{\theta^2}{1 + \theta} (1 + x) e^{-\theta x},

with \theta > 0 . Support: x \ge 0 .

Parameters

NameTypeDescription
thetanumber

Shape parameter.

ran.dist.Logarithmic(a, b)

Probability density function for the (continuous) logarithmic distribution:

f(x; a, b) = \frac{\ln x}{a (1 - \ln a) - b (1 - \ln b)},

with a, b \in [1, \infty) and a < b . Support: x \in [a, b] .

Parameters

NameTypeDescription
anumber

Lower boundary of the distribution.

bnumber

Upper boundary of the distribution.

ran.dist.LogCauchy(mu, sigma)

Probability density function for the log-Cauchy distribution:

f(x; \mu, \sigma) = \frac{1}{\pi x}\bigg[\frac{\sigma}{(\ln x - \mu)^2 + \sigma^2}\bigg],

with \mu \in \mathbb{R} and \sigma > 0 . Support: x > 0 .

Parameters

NameTypeDescription
munumber

Location parameter.

sigmanumber

Scale parameter.

ran.dist.LogGamma(alpha, beta, mu)

Probability density function for the log-gamma distribution using the shape/rate parametrization:

f(x; \alpha, \beta, \mu) = \frac{\beta^\alpha}{\Gamma(\alpha)} \ln^{\alpha - 1}(x - \mu + 1) (x - \mu + 1)^{-(1 + \beta)},

where \alpha, \beta > 0 and \mu \ge 0 . Support: x \in [\mu, \infty) .

Parameters

NameTypeDescription
alphanumber

Shape parameter.

betanumber

Rate parameter.

munumber

Location parameter.

ran.dist.Logistic(mu, s)

Probability density function for the logistic distribution:

f(x; \mu, s) = \frac{e^{-z}}{s (1 + e^{-z})^2},

with z = \frac{x - \mu}{s} , \mu \in \mathbb{R} and s > 0 . Support: x \in \mathbb{R} .

Parameters

NameTypeDescription
munumber

Location parameter.

snumber

Scale parameter.

ran.dist.LogisticExponential(lambda, kappa)

Probability density function for the logistic-exponential distribution:

f(x; \lambda, \kappa) = \frac{\lambda \kappa (e^{\lambda x} - 1)^{\kappa - 1} e^{\lambda x}}{[1 + (e^{\lambda x} - 1)^\kappa]^2},

where \lambda, \kappa > 0 . Support: x > 0 .

Parameters

NameTypeDescription
lambdanumber

Scale parameter.

kappanumber

Shape parameter.

ran.dist.LogitNormal(mu, sigma)

Probability density function for the logit-normal distribution:

f(x; \mu, \sigma) = \frac{1}{\sigma \sqrt{2 \pi} x (1 - x)} e^{-\frac{[\mathrm{logit}(x) - \mu]^2}{2 \sigma^2}},

with \mu \in \mathbb{R} , \sigma > 0 and \mathrm{logit}(x) = \ln \frac{x}{1 - x} . Support: x \in (0, 1) .

Parameters

NameTypeDescription
munumber

Location parameter.

sigmanumber

Scale parameter.

ran.dist.LogLaplace(mu, b)

Probability density function for the log-Laplace distribution:

f(x; \mu, b) = \frac{1}{2bx}e^{-\frac{|\mathrm{ln} x - \mu|}{b}},

where \mu \in \mathbb{R} and b > 0 . Support: x > 0 .

Parameters

NameTypeDescription
munumber

Location parameter.

bnumber

Scale parameter.

ran.dist.LogLogistic(alpha, beta)

Probability density function for the log-logistic distribution (also known as Fisk distribution):

f(x; \alpha, \beta) = \frac{(\beta / \alpha) (x / \alpha)^{\beta - 1}}{[1 + (x / \alpha)^\beta]^2},

with \alpha, \beta > 0 . Support: x \in [0, \infty) .

Parameters

NameTypeDescription
alphanumber

Scale parameter.

betanumber

Shape parameter.

ran.dist.LogNormal(mu, sigma)

Probability density function for the log-normal distribution:

f(x; \mu, \sigma) = \frac{1}{x \sigma \sqrt{2 \pi}}e^{-\frac{(\ln x - \mu)^2}{2\sigma^2}},

where \mu \in \mathbb{R} and \sigma > 0 . Support: x > 0 .

Parameters

NameTypeDescription
munumber

Location parameter.

sigmanumber

Scale parameter.

ran.dist.LogSeries(p)

Probability mass function for the log-series distribution:

f(k; p) = \frac{-1}{\ln(1 - p)}\frac{p^k}{k},

with p \in (0, 1) . Support: k \in \mathbb{N}^+ .

Parameters

NameTypeDescription
pnumber

Distribution parameter.

ran.dist.Lomax(lambda, alpha)

Probability density function for the Lomax distribution:

f(x; \lambda, \alpha) = \frac{\alpha}{\lambda}\Big[1 + \frac{x}{\lambda}\Big]^{-(\alpha + 1)},

with \lambda, \alpha > 0 . Support: x \ge 0 .

Parameters

NameTypeDescription
lambdanumber

Scale parameter.

alphanumber

Shape parameter.

ran.dist.Makeham(alpha, beta, lambda)

Probability density function for the Makeham distribution (also known as Gompertz-Makeham distribution):

f(x; \alpha, \beta, \lambda) = (\alpha e^{\beta x} + \lambda) \exp\Big[{-\lambda x - \frac{\alpha}{\beta}(e^{\beta x} - 1)}\Big],

with \alpha, \beta, \lambda > 0 . Support: x > 0 .

Parameters

NameTypeDescription
alphanumber

Shape parameter.

betanumber

Rate parameter.

lambdanumber

Scale parameter.

ran.dist.MaxwellBoltzmann(a)

Probability density function for the Maxwell-Boltzmann distribution:

f(x; a) = \sqrt{\frac{2}{\pi}}\frac{x^2 e^{-x^2 / (2a^2)}}{a^3},

with a > 0 . Support: x > 0 .

Parameters

NameTypeDescription
anumber

Scale parameter.

ran.dist.Mielke(k, s)

Probability density function for the Mielke distribution:

f(x; k, s) = \frac{k x^{k - 1}}{(1 + x^s)^{1 + k/s}},

with k, s > 0 . Support: x > 0 . It can be viewed as a re-parametrization of the Dagum distribution.

Parameters

NameTypeDescription
knumber

First shape parameter.

snumber

Second shape parameter.

ran.dist.Moyal(mu, sigma)

Probability density function for the Moyal distribution:

f(x; \mu, \sigma) = \frac{1}{\sqrt{2 \pi}}e^{-\frac{1}{2}(z + e^{-z})},

where z = \frac{x - \mu}{\sigma} , \mu \in \mathbb{R} and \sigma > 0 . Support: x \in \mathbb{R} .

Parameters

NameTypeDescription
munumber

Location parameter.

sigmanumber

Scale parameter.

ran.dist.Muth(alpha)

Probability density function for the Muth distribution:

f(x; \alpha) = (e^{\alpha x} - \alpha) \exp\bigg(\alpha x - \frac{1}{\alpha} (e^{\alpha x} - 1)\bigg),

with \alpha \in (0, 1] . Support: x > 0 .

Parameters

NameTypeDescription
alphanumber

Shape parameter.

ran.dist.Nakagami(m, omega)

Probability density function for the Nakagami distribution:

f(x; m, \Omega) = \frac{2m^m}{\Gamma(m) \Omega^m} x^{2m - 1} e^{-\frac{m}{\Omega} x^2},

where m \in \mathbb{R} , m \ge 0.5 and \Omega > 0 . Support: x > 0 .

Parameters

NameTypeDescription
mnumber

Shape parameter.

omeganumber

Spread parameter.

ran.dist.NegativeHypergeometric(N, K, r)

Probability mass function for the negative hypergeometric distribution:

f(k; N, K, r) = \frac{\begin{pmatrix}k + r - 1 \\ k \\ \end{pmatrix} \begin{pmatrix}N - r - k \\ K - k \\ \end{pmatrix}}{\begin{pmatrix}N \\ K \\ \end{pmatrix}},

with N \in \mathbb{N}_0 , K \in {0, 1, ..., N} and r \in {0, 1, ..., N - K} . Support: k \in {0, ..., K} .

Parameters

NameTypeDescription
Nnumber

Total number of elements to sample from. If not an integer, it is rounded to the nearest one.

Knumber

Total number of successes. If not an integer, it is rounded to the nearest one.

rnumber

Total number of failures to stop at. If not an integer, it is rounded to the nearest one.

ran.dist.NeymanA(lambda, phi)

Probability mass function for the Neyman type A distribution:

f(k; \lambda, \phi) = \frac{e^{-\lambda + \lambda e^{-\phi}} \phi^k}{k!} \sum_{j=1}^k S(k, j) \lambda^k e^{-\phi k},

where \lambda, \theta > 0 and S(n, m) denotes the Stirling number of the second kind. Support: k \in \mathbb{N}_0 .

Parameters

NameTypeDescription
lambdanumber

Mean of the number of clusters.

phinumber

Mean of the cluster size.

ran.dist.NoncentralBeta(alpha, beta, lambda)

Probability density function for the non-central beta distribution:

f(x; \alpha, \beta, \lambda) = e^{-\frac{\lambda}{2}} \sum_{k = 0}^\infty \frac{1}{k!} \bigg(\frac{\lambda}{2}\bigg)^k \frac{x^{\alpha + k - 1} (1 - x)^{\beta - 1}}{\mathrm{B}(\alpha + k, \beta)},

where \alpha, \beta > 0 and \lambda \ge 0 . Support: x \in [0, 1] .

Parameters

NameTypeDescription
alphanumber

First shape parameter.

betanumber

Second shape parameter.

lambdanumber

Non-centrality parameter.

ran.dist.NoncentralChi(k, lambda)

Probability density function for the non-central \chi distribution:

f(x; k; \lambda) = \frac{x^k \lambda}{(\lambda x)^{k/2}} e^{-\frac{x^2 + \lambda^2}{2}} I_{k/2 - 1}(\lambda x),

with k \in \mathbb{N}^+ , \lambda > 0 and I_n(x) is the modified Bessel function of the first kind with order n . Support: x \in [0, \infty) .

Parameters

NameTypeDescription
knumber

Degrees of freedom. If not an integer, it is rounded to the nearest one.

lambdanumber

Non-centrality parameter.

ran.dist.NoncentralChi2(k, lambda)

Probability density function for the non-central \chi^2 distribution:

f(x; k; \lambda) = \frac{1}{2}e^{-\frac{x + \lambda}{2}} \bigg(\frac{x}{\lambda}\bigg)^{k/4 - 1/2} I_{k/2 - 1}\big(\sqrt{\lambda x}\big),

with k \in \mathbb{N}^+ , \lambda \ge 0 and I_n(x) is the modified Bessel function of the first kind with order n . Support: x \in [0, \infty) . When \lambda = 0 the distribution degenerates to a central \chi^2(k) .

Parameters

NameTypeDescription
knumber

Degrees of freedom. If not an integer, it is rounded to the nearest one.

lambdanumber

Non-centrality parameter.

ran.dist.NoncentralF(d1, d2, lambda)

Probability density function for the non-central F distribution:

f(x; d_1, d_2, \lambda) = e^{-\frac{\lambda}{2}} \sum_{k=0}^\infty \frac{1}{k!} \bigg(\frac{\lambda}{2}\bigg)^k \frac{\Big(\frac{d_1}{d_2}\Big)^{\frac{d_1}{2} + k} \Big(\frac{d_2}{d_2 + d_1 x}\Big)^{\frac{d_1 + d_2}{2} + k}}{\mathrm{B}\Big(\frac{d_2}{2}, \frac{d_1}{2} + k\Big)} x^{\frac{d_1}{2} -1 + k},

where d_1, d_2 \in \mathbb{N}^+ and \lambda > 0 . Support: x \ge 0 .

Parameters

NameTypeDescription
d1number

First degree of freedom. If not an integer, it is rounded to the nearest one.

d2number

Second degree of freedom. If not an integer, it is rounded to the nearest one.

lambdanumber

Non-centrality parameter.

ran.dist.NoncentralT(nu, mu)

Probability density function for the non-central t distribution:

f(x; \nu, \mu) = \frac{\nu^\frac{\nu}{2} \exp\Big(-\frac{\nu \mu^2}{2 (x^2 + \nu)}\Big)}{\sqrt{\pi} \Gamma\big(\frac{\nu}{2}\big) 2^\frac{\nu - 1}{2} (x^2 + \nu)^\frac{\nu + 1}{2}} \int_0^\infty y^\nu \exp\bigg(-\frac{1}{2}\bigg[y - \frac{\mu x}{\sqrt{x^2 + \nu}}\bigg]^2\bigg) \mathrm{d}y,

with \nu \in \mathbb{N}^+ and \mu \in \mathbb{R} . Support: x \in \mathbb{R} .

Parameters

NameTypeDescription
nunumber

Degrees of freedom. If not an integer, it is rounded to the nearest one.

munumber

Non-centrality parameter.

ran.dist.Normal(mu, sigma)

Probability density function for the normal distribution:

f(x; \mu, \sigma) = \frac{1}{\sqrt{2 \pi \sigma^2}} e^{-\frac{(x - \mu)^2}{2\sigma^2}},

with \mu \in \mathbb{R} and \sigma > 0 . Support: x \in \mathbb{R} .

Parameters

NameTypeDescription
munumber

Location parameter (mean).

sigmanumber

Scale parameter (standard deviation).

ran.dist.Pareto(xmin, alpha)

Probability density function for the Pareto distribution:

f(x; x_\mathrm{min}, \alpha) = \frac{\alpha x_\mathrm{min}^\alpha}{x^{\alpha + 1}},

with x_\mathrm{min}, \alpha > 0 . Support: x \in [x_\mathrm{min}, \infty) .

Parameters

NameTypeDescription
xminnumber

Scale parameter.

alphanumber

Shape parameter.

ran.dist.PERT(a, b, c)

Probability density function for the PERT distribution:

f(x; a, b, c) = \frac{(x - a)^{\alpha - 1} (c - x)^{\beta - 1}}{\mathrm{B}(\alpha, \beta) (c - a)^{\alpha + \beta + 1}},

where a, b, c \in \mathbb{R} , a < b < c , \alpha = \frac{4b + c - 5a}{c - a} , \beta = \frac{5c - a -4b}{c - a} and \mathrm{B}(x, y) is the beta function. Support: x \in [a, c] .

Parameters

NameTypeDescription
anumber

Lower boundary of the support.

bnumber

Mode of the distribution.

cnumber

Upper boundary of the support.

ran.dist.Poisson(lambda)

Probability mass function for the Poisson distribution:

f(k; \lambda) = \frac{\lambda^k e^{-\lambda}}{k!},

with \lambda > 0 . Support: k \in \mathbb{N}_0 .

Parameters

NameTypeDescription
lambdanumber

Mean of the distribution.

ran.dist.PolyaAeppli(lambda, theta)

Probability mass function for the Pólya-Aeppli distribution (also known as geometric Poisson distribution):

f(k; \lambda, \theta) = \begin{cases}e^{-\lambda} &\quad\text{if $k = 0$},\\ e^{-\lambda} \sum_{j = 1}^k \frac{\lambda^j}{j!} \begin{pmatrix}k - 1 \\ j - 1 \\ \end{pmatrix} \theta^{k - j} (1 - \theta)^j &\quad\text{otherwise}\\ \end{cases},

where \lambda > 0 and \theta \in (0, 1) . Support: k \in \mathbb{N}_0 .

Parameters

NameTypeDescription
lambdanumber

Mean of the Poisson component.

thetanumber

Parameter of the shifted geometric component.

ran.dist.PowerLaw(a)

Probability density function for the power-law distribution (also called power-law distribution):

f(x; a) = a x^{a - 1},

with a > 0 . Support: x \in (0, 1) .

Parameters

NameTypeDescription
anumber

One plus the exponent of the distribution.

ran.dist.QExponential(q, lambda)

Probability density function for the q-exponential distribution:

f(x; q, \lambda) = (2 - q) \lambda e^{-\lambda x}_q,

where q < 2 , \lambda > 0 and e^x_q denotes the q-exponential function. Support: x > 0 if q \ge 1 , otherwise x \in \big[0, \frac{1}{\lambda (1 - q)}\big) .

Parameters

NameTypeDescription
qnumber

Shape parameter.

lambdanumber

Rate parameter.

ran.dist.R(c)

Probability density function for the R distribution:

f(x; c) = \frac{(1 - x^2)^{\frac{c}{2} - 1}}{\mathrm{B}\big(\frac{1}{2}, \frac{c}{2}\big)},

where c > 0 . Support: x \in [-1, 1] .

Parameters

NameTypeDescription
cnumber

Shape parameter.

ran.dist.Rademacher()

Probability mass function for the Rademacher distribution:

f(k) = \begin{cases}1/2 &\quad\text{if $k = -1$},\\ 1/2 &\quad\text{if $k = 1$},\\ 0 &\quad\text{otherwise}.\\ \end{cases}

Support: k \in {-1, 1} .

ran.dist.RaisedCosine(mu, s)

Probability density function for the raised cosine distribution:

f(x; \mu, s) = \frac{1}{2s} \Big[1 + \cos\Big(\frac{x - \mu}{s} \pi\Big)\Big],

where \mu \in \mathbb{R} and s > 0 . Support: x \in [\mu - s, \mu + s] .

Parameters

NameTypeDescription
munumber

Location paramter.

snumber

Scale parameter.

ran.dist.Rayleigh(sigma)

Probability density function for the Rayleigh distribution:

f(x; \sigma) = \frac{x}{\sigma^2} e^{-\frac{x^2}{2\sigma^2}},

with \sigma > 0 . Support: x \ge 0 .

Parameters

NameTypeDescription
sigmanumber

Scale parameter.

ran.dist.Reciprocal(a, b)

Probability density function for the reciprocal distribution:

f(x; a, b) = \frac{1}{x [\ln b - \ln a]},

with a, b > 0 and a < b . Support: x \in [a, b] .

Parameters

NameTypeDescription
anumber

Lower boundary of the support.

bnumber

Upper boundary of the support.

ran.dist.ReciprocalInverseGaussian(mu, lambda)

Probability density function for the reciprocal inverse Gaussian distribution (RIG):

f(x; \lambda, \mu) = \bigg[\frac{\lambda}{2 \pi x}\bigg]^{1/2} e^{\frac{-\lambda (1 - \mu x)^2}{2 \mu^2 x}},

with \mu, \lambda > 0 . Support: x > 0 .

Parameters

NameTypeDescription
munumber

Mean of the inverse Gaussian distribution.

lambdanumber

Shape parameter.

ran.dist.Rice(nu, sigma)

Probability density function for the Rice distribution:

f(x; \nu, \sigma) = \frac{x}{\sigma^2} e^{-\frac{x^2 + \nu^2}{2 \sigma^2}} I_0\bigg(\frac{\nu x}{\sigma^2}\bigg),

with \nu, \sigma > 0 and I_0(x) is the modified Bessel function of the first kind with order zero. Support: x \in [0, \infty) .

Parameters

NameTypeDescription
nunumber

First shape parameter.

sigmanumber

Second shape parameter.

ran.dist.ShiftedLogLogistic(mu, sigma, xi)

Probability density function for the shifted log-logistic distribution:

f(x; \mu, \sigma, \xi) = \frac{(1 + \xi z)^{-(1/\xi + 1)}}{\sigma [1 + (1 + \xi z)^{-1/\xi}]^2},

with z = \frac{x - \mu}{\sigma} , \mu, \xi \in \mathbb{R} and \sigma > 0 . Support: x \ge \mu - \sigma/\xi if \xi > 0 , x \le \mu - \sigma/\xi if \xi < 0 , x \in \mathbb{R} otherwise.

Parameters

NameTypeDescription
munumber

Location parameter.

sigmanumber

Scale parameter.

xinumber

Shape parameter.

ran.dist.Skellam(mu1, mu2)

Probability mass function for the Skellam distribution:

f(k; \mu_1, \mu_2) = e^{-(\mu_1 + \mu_2)}\Big(\frac{\mu_1}{\mu_2}\Big)^{k/2} I_k(2 \sqrt{\mu_1 \mu_2}),

with \mu_1, \mu_2 \ge 0 and I_n(x) is the modified Bessel function of the first kind with order n . Support: k \in \mathbb{N} .

Parameters

NameTypeDescription
mu1number

Mean of the first Poisson distribution.

mu2number

Mean of the second Poisson distribution.

ran.dist.SkewNormal(xi, omega, alpha)

Probability density function for the skew normal distribution:

f(x; \xi, \omega, \alpha) = \frac{2}{\omega} \phi\bigg(\frac{x - \xi}{\omega}\bigg) \Phi\bigg(\alpha \frac{x - \xi}{\omega}\bigg),

where \xi, \alpha \in \mathbb{R} , \omega > 0 and \phi(x) , \Phi(x) denote the probability density and cumulative distribution functions of the standard normal distribution. Support: x \in \mathbb{R} .

Parameters

NameTypeDescription
xinumber

Location parameter.

omeganumber

Scale parameter.

alphanumber

Shape parameter.

ran.dist.Slash()

Probability density function for the slash distribution:

f(x) = \begin{cases}\frac{\phi(0) - \phi(x)}{x^2} &\quad\text{if $x \ne 0$},\\ \frac{1}{2 \sqrt{2 \pi}} &\quad\text{if $x = 0$}\\ \end{cases},

where \phi(x) is the probability density function of the standard normal distribution. Support: x \in \mathbb{R} .

ran.dist.Soliton(N)

Probability mass function for the (ideal) soliton distribution:

f(k; N) = \begin{cases}\frac{1}{N} &\quad\text{if $k = 1$},\\ \frac{1}{k (k - 1)} &\quad\text{otherwise}\\ \end{cases},

with N \in \mathbb{N}^+ . Support: k \in {1, 2, ..., N} .

Parameters

NameTypeDescription
Nnumber

Number of blocks in the messaging model. If not an integer, it is rounded to the nearest one.

ran.dist.StudentT(nu)

Generator for Student's t-distribution:

f(x; \nu) = \frac{1}{\sqrt{\nu}\mathrm{B}\big(\frac{1}{2}, \frac{\nu}{2}\big)} \Big(1 + \frac{x^2}{\nu}\Big)^{-\frac{\nu + 1}{2}},

with \nu > 0 and \mathrm{B}(x, y) is the beta function. Support: x \in \mathbb{R} .

Parameters

NameTypeDescription
nunumber

Degrees of freedom.

ran.dist.StudentZ(n)

Generator for Student's Z distribution:

f(x; n) = \frac{\Gamma\Big(\frac{n}{2}\Big)}{\sqrt{\pi} \Gamma\Big(\frac{n - 1}{2}\Big)} (1 + x^2)^{-\frac{n}{2}},

with n > 1 . Support: x \in \mathbb{R} .

Parameters

NameTypeDescription
nnumber

Degrees of freedom.

ran.dist.Trapezoidal(a, b, c, d)

Probability density function for the trapezoidal distribution:

f(x; a, b, c, d) = \begin{cases}0 &\quad\text{for $x < a$},\\ \frac{2 (x - a)}{(b - a) (d + c - a - b)} &\quad\text{for $a \le x < b$}\\ \frac{2}{d + c - a - b} &\quad\text{for $b \le x < c$}\\ \frac{2 (d - x)}{(d - c) (d + c - a - b)} &\quad\text{for $c \le x \le d$}\\ 0 &\quad\text{for $d < x$} \\ \end{cases},

where a, b, c, d \in \mathbb{R} , a < d , a \le b < c and c \le d . Support: x \in [a, d] .

Parameters

NameTypeDescription
anumber

Lower bound of the support.

bnumber

Start of the level part.

cnumber

End of the level part.

dnumber

Upper bound of the support.

ran.dist.Triangular(a, b, c)

Probability density function for the asymmetric triangular distribution:

f(x; a, b, c) = \begin{cases}0 &\quad\text{for $x < a$},\\ \frac{2 (x - a)}{(b - a) (c - a)} &\quad\text{for $a \le x < c$} \\ \frac{2 (b - x)}{(b - a) (b - c)} &\quad\text{for $c \le x \le b$} \\ 0 &\quad\text{for $b < x$} \\ \end{cases},

with a, b, c \in \mathbb{R} , a < b and a \le c \le b . Support: x \in [a, b] .

Parameters

NameTypeDescription
anumber

Lower bound of the support.

bnumber

Upper bound of the support.

cnumber

Mode of the distribution.

ran.dist.TruncatedExponential(lambda, a, b)

Probability density function for the truncated exponential distribution:

f(x; \lambda, a, b) = \frac{\lambda e^{-\lambda x}}{e^{-\lambda a} - e^{-\lambda b}},

with \lambda > 0 , a \ge 0 , and b > a . Support: x \in [a, b] .

Parameters

NameTypeDescription
lambdanumber

Rate parameter.

anumber

Lower boundary of the support.

bnumber

Upper boundary of the support.

ran.dist.TruncatedNormal(mu, sigma, a, b)

Probability density function for the truncated normal distribution:

f(x; \mu, \sigma, a, b) = \frac{\phi(\xi)}{\Phi(\beta) - \Phi(\alpha)},

where \xi = \frac{x - \mu}{\sigma}, \alpha = \frac{a - \mu}{\sigma} and \beta = \frac{b - \mu}{\sigma} . The functions \phi and \Phi denote the probability density and cumulative distribution functions of the normal distribution. Finally, \mu \in \mathbb{R} , \sigma > 0 and b > a . Support: x \in [a, b] .

Parameters

NameTypeDescription
munumber

Mean of the underlying normal distribution.

sigmanumber

Variance of the underlying normal distribution.

anumber

Lower boundary of the support.

bnumber

Upper boundary of the support.

ran.dist.TukeyLambda(lambda)

Probability density function for the Tukey lambda distribution:

f(x; \lambda) = \frac{1}{Q^{-1}(F(x))},

where Q(p) = \frac{p^\lambda - (1 - p)^\lambda}{\lambda} and F(x) = Q^{-1}(x) . Support: x \in [-1/\lambda, 1/\lambda] if \lambda > 0 , otherwise x \in \mathbb{R} .

Parameters

NameTypeDescription
lambdanumber

Shape parameter.

ran.dist.Uniform(xmin, xmax)

Probability density function for the continuous uniform distribution:

f(x; x_\mathrm{min}, x_\mathrm{max}) = \frac{1}{x_\mathrm{max} - x_\mathrm{min}},

with x_\mathrm{min}, x_\mathrm{max} \in \mathbb{R} and x_\mathrm{min} < x_\mathrm{max} . Support: x \in [x_\mathrm{min}, x_\mathrm{max}] .

Parameters

NameTypeDescription
xminnumber

Lower boundary.

xmaxnumber

Upper boundary.

ran.dist.UniformProduct(n)

Probability density function for the product of uniform distribution:

f(x; n) = \frac{(-\ln x)^{n-1}}{(n-1)!},

with n \in \mathbb{N}, n > 1 . Support: x \in (0, 1] .

Parameters

NameTypeDescription
nnumber

Number of uniform factors. If not an integer, it is rounded to the nearest one.

ran.dist.UniformRatio()

Probability density function for the uniform ratio distribution:

f(x) = \begin{cases}\frac{1}{2} &\quad\text{if $x < 1$},\\ \frac{1}{2x^2} &\quad\text{if $x \ge 1$},\\ \end{cases}.

Support: x > 0 .

ran.dist.UQuadratic(a, b)

Probability density function for the u-quadratic distribution:

f(x; a, b) = \alpha (x - \beta)^2,

where \alpha = \frac{12}{(b - a)^3} , \beta = \frac{a + b}{2} , a, b \in \mathbb{R} and a < b . Support: x \in [a, b] .

Parameters

NameTypeDescription
anumber

Lower bound of the support.

bnumber

Upper bound of the support.

ran.dist.VonMises(kappa)

Probability density function for the von Mises distribution:

f(x; \kappa) = \frac{e^{\kappa \cos(x)}}{2 \pi I_0(\kappa)},

with \kappa > 0 . Support: x \in [-\pi, \pi] . Note that originally this distribution is periodic and therefore it is defined over \mathbb{R} , but (without the loss of general usage) this implementation still does limit the support on the bounded interval [-\pi, \pi] .

Parameters

NameTypeDescription
kappanumber

Shape parameter.

ran.dist.Weibull(lambda, k)

Probability density function for the Weibull distribution:

f(x; \lambda, k) = \frac{k}{\lambda}\bigg(\frac{x}{\lambda}\bigg)^{k - 1} e^{-(x / \lambda)^k},

with \lambda, k > 0 . Support: x \ge 0 .

Parameters

NameTypeDescription
lambdanumber

Scale parameter.

knumber

Shape parameter.

ran.dist.Wigner(R)

Generator for Wigner distribution (also known as semicircle distribution):

f(x; R) = \frac{2}{\pi R^2} \sqrt{R^2 - x^2},

with R > 0 . Support: x \in [-R, R] .

Parameters

NameTypeDescription
Rnumber

Radius of the distribution.

ran.dist.YuleSimon(rho)

Probability mass function for the Yule-Simon distribution:

f(k; \rho) = \rho \mathrm{B}(k, \rho + 1),

with \rho > 0 and \mathrm{B}(x, y) is the beta function. Support: k \in \mathbb{N}^+ .

Parameters

NameTypeDescription
rhonumber

Shape parameter.

ran.dist.Zeta(s)

Probability mass function for the zeta distribution:

f(k; s) = \frac{k^{-s}}{\zeta(s)},

with s \in (1, \infty) and \zeta(x) is the Riemann zeta function. Support: k \in \mathbb{N}^+ .

Parameters

NameTypeDescription
snumber

Exponent of the distribution.

ran.dist.Zipf(s, N)

Probability mass function for the Zipf distribution:

f(k; s, N) = \frac{k^{-s}}{H_{N, s}},

with s \ge 0 , N \in \mathbb{N}^+ and H_{N, s} denotes the generalized harmonic number. Support: k \in {1, 2, ..., N} .

Parameters

NameTypeDescription
snumber

Exponent of the distribution.

Nnumber

Number of words. If not an integer, it is rounded to the nearest integer. Default is 100.

ran.dist.ZipfMandelbrot(N, s, q)

Probability mass function for the Zipf-Mandelbrot distribution:

f(k; N, s, q) = \frac{(k+q)^{-s}}{H_{N,s,q}},

with s > 1 , q \ge 0 , N \in \mathbb{N}^+ and H_{N,s,q} = \sum_{j=1}^{N}(j+q)^{-s} . Support: k \in {1, 2, \ldots, N} .

Parameters

NameTypeDescription
Nnumber

Number of elements (support size). If not an integer, it is rounded to the nearest integer.

snumber

Exponent of the distribution.

qnumber

Shift parameter.

ran.location.geometricMean(values)

Calculates the geometric mean of an array of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate geometric mean for.

Returns

number

Geometric mean of the values, NaN for empty input.

Examples

ran.location.geometricMean([])
// => NaN

ran.location.geometricMean([1, 2, 3])
// => 1.8171205928321394
ran.location.harmonicMean(values)

Calculates the harmonic mean of an array of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate harmonic mean for.

Returns

number

Harmonic mean of the values, NaN if any value is non-positive.

Examples

ran.location.harmonicMean([])
// => NaN

ran.location.harmonicMean([0, 1, 2])
// => NaN

ran.location.harmonicMean([-1, 2, 3])
// => NaN

ran.location.harmonicMean([1, 2, 3])
// => 1.6363636363636365
ran.location.mean(values)

Calculates the arithmetic mean of an array of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate mean for.

Returns

number

Mean of the values, NaN for empty input.

Examples

ran.location.mean([])
// => NaN

ran.location.mean([1, 2, 3])
// => 2
ran.location.median(values)

Calculates the median of a sample of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate median for.

Returns

number

Median of the values, NaN for empty input.

Examples

ran.location.median([])
// => NaN

ran.location.median([1, 2, 3, 4])
// => 2.5
ran.location.midrange(values)

Calculates the mid-range for a sample of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate mid-range for.

Returns

number

The mid-range of the values, NaN for empty input.

Examples

ran.location.midrange([])
// => NaN

ran.location.midrange([0, 0, 0, 1, 2])
// => 1
ran.location.mode(values)

Calculates the mode(s) of a sample. In case of discrete values (integers), it returns the values corresponding to the highest frequencies in ascending order. For continuous sample, the mode is estimated using the half-sample mode algorithm.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate mode for.

Returns

numbernumber[]

The estimated mode (continuous sample) or an array of modes (discrete sample). Returns an empty array for empty input.

Examples

ran.location.mode([])
// => []

ran.location.mode([1])
// => [1]

ran.location.mode([1, 1, 2, 2, 3])
// => [1, 2]

ran.location.mode([1, 2, 2, 2, 3])
// => [2]

ran.location.mode([1.2, 3.4, 5.6])
// => 4.5
ran.location.trimean(values)

Calculates the trimean for a sample of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate trimean for.

Returns

number

The trimean of the values, NaN for empty input.

Examples

ran.location.trimean([])
// => NaN

ran.location.trimean([1, 1, 1, 2, 3])
// => 1.25
ran.mc.gelmanRubin(samples[, maxLength])

Calculates the Gelman-Rubin convergence diagnostic for a set of independent chains. Returns the R-hat statistic as a function of iteration count for each state dimension, starting from the minimum of 2 samples.

Parameters

NameTypeDescription
samplesArray

Array of chains, where each chain is an array of states returned by RWM#sample. At least two chains are required.

maxLengthnumber

Maximum number of diagnostic values to return per dimension. Defaults to the full chain length.

Throws

Error
If fewer than two chains are provided.
ran.mc.runChains(Sampler[, samplerOptions[, runOptions]])

Runs multiple independently-seeded MCMC chains from the same target and computes the Gelman-Rubin convergence diagnostic across them — the recommended workflow for gating MCMC convergence (decisions/0024-mcmc-warmup-convergence-strategy.md), since no signal computable from a single chain can distinguish "converged" from "stuck". samplerOptions is forwarded to new Sampler(samplerOptions) without inspecting its keys, so any MCMC subclass — including Gibbs, whose options object has no logDensity at all — can drive the diagnostic the same way (decisions/0033-generalized-runchains-sampler-driver.md).

Do not pass an explicit initialState.x. The same samplerOptions object is forwarded to every chain, and MCMC.seed() only redraws the starting position when x was not supplied. If you provide initialState.x, all chains start from the identical point, which defeats the over-dispersed-initialization that makes the Gelman-Rubin diagnostic meaningful — a chain family stuck in one mode then reports R-hat ≈ 1 ("converged") because every chain is stuck in the same place. Omit initialState.x so each seed draws its own random start.

Parameters

NameTypeDescription
SamplerFunction

An MCMC subclass (e.g. RWM, AdaptiveMetropolis, Slice, Gibbs, HMC, MALA, or NUTS) to drive each chain.

samplerOptionsObject

Options object forwarded verbatim to new Sampler(samplerOptions) for every chain — the same shape that sampler's own options-object constructor accepts (e.g. {logDensity, config, initialState} for RWM/AdaptiveMetropolis/Slice, {logDensity, gradLogDensity, config, initialState} for HMC/MALA/NUTS, {conditionals, config, initialState} for Gibbs).

runOptionsObject

Run configuration. Supported properties:

Returns

Object

Object with properties: samples (number[][][], one sample array per chain) and rhat (number[][], the gelmanRubin() diagnostic across the chains).

Throws

Error
If runOptions.chains is not an integer of at least two, or exceeds the maximum allowed chain count, or if runOptions.seeds is provided and its length does not equal runOptions.chains.
ran.mc.MCMC(logDensity[, config[, initialState]])

Base class implementing a general Markov chain Monte Carlo sampler. All MCMC samplers extend this class. MCMC samplers approximate integrals by efficiently sampling a density that cannot be normalized or sampled directly. Every public subclass (RWM, AdaptiveMetropolis, Slice, HMC, Gibbs, MALA, NUTS) exposes an options-object-only constructor; this base constructor's positional (logDensity, config, initialState) signature is an internal contract those subclasses forward to, not part of the public API.

Parameters

NameTypeDescription
logDensityFunction

The logarithm of the (unnormalized) target density.

configObject

Sampler configuration. Supported properties:

initialStateObject

Initial state of the sampler. Supported properties: {x} (starting position), {samplingRate} (thinning interval), and {internal} for subclass-specific state.

Throws

Error
If config.dim is provided but is not a positive integer, or exceeds the maximum allowed dimension.
Error
If config.maxLag is provided but is not a positive integer, or exceeds the maximum allowed lag.
Error
If config.arWindow is provided but is not a positive integer, or exceeds the maximum allowed window.
Error
If the combined dim*maxLag accumulator footprint exceeds the maximum allowed memory budget.
ran.mc.MCMC.ac()

Computes the autocorrelation function for each dimension at lags 0 to maxLag-1. Uses an online estimator: O(dim * maxLag) memory, O(dim * maxLag) per update, O(1) per query.

ran.mc.MCMC.ar()

Computes the acceptance rate over the most recent arWindow iterations (a sliding window, default 1000). During the partial-fill phase, before arWindow iterations have occurred since the last reset, this equals the exact cumulative rate.

Returns

number

Fraction of proposals accepted in the current window.

ran.mc.MCMC.ess()

Computes the effective sample size for each dimension using Geyer's initial positive monotone sequence estimator (IPSM; Geyer 1992, Vehtari et al. 2021 — the estimator used by Stan and ArviZ): \Gamma_m = \rho_{2m} + \rho_{2m+1} pairs consecutive lags starting at lag 0 (so the first pair always includes \rho_0 = 1 ), clamped to be no larger than \Gamma_{m-1} (the true autocovariance sequence is convex, so a non-increasing sequence of pair sums has strictly lower variance than summing raw lags). The sum stops at the first pair whose clamped value is not positive; \mathrm{ESS} = \frac{N}{-1 + 2 \sum_m \Gamma_m}, or \mathrm{ESS} = N ( \tau = 1 ) if even the first pair is non-positive (sum = 0) -- that -1 + 2 \cdot 0 = -1 would otherwise give a nonsensical negative \tau . Anchoring the pairing at lag 0 means \rho_1 alone can never prematurely truncate the sum: \Gamma_0 = 1 + \rho_1 is non-positive only when \rho_1 \le -1 , an extreme case, unlike the old single-lag rule which underestimated \tau (overestimated ESS) whenever an otherwise well-mixing chain had one merely-negative early lag. Built directly on the same accumulators as ac() and statistics() — no additional accumulator state. If the first pair itself is already non-positive ( \rho_1 \le -1 , an extreme case), \mathrm{ESS} = N exactly: a legitimate output of this truncation rule when the sampler genuinely produces that strong an anti-correlation, not necessarily a sign of a broken sampler. A milder resonance -- e.g. HMC's fixed pathLength resonating with the target's geometry, see hmc.js -- typically lands well short of that \rho_1 \le -1 boundary and instead inflates or deflates ESS relative to the raw sample count without saturating to N exactly. See #974: verified against a brute-force autocorrelation over the raw iterate() sequence, which confirmed the online accumulator is exact and the anti-correlation is genuine.

A fully stuck (zero-variance) chain is a distinct case from the above: ac()'s divisor is the population variance, so a chain that never moves produces 0/0 = \mathrm{NaN} at every lag including lag 0. That NaN is not a signal of non-positive autocorrelation to saturate on — it means the chain contributed zero effectively-independent samples, so ess() reports 1 rather than N (the n = 0 case, no observations at all yet, is unaffected and still reports 0).

solutions/testing/2026-07-18-1641-ess-geyer-ipsm-pairing-offset-self-consistent-wrong-tests.md — the pairing must start at lag 0 (anchored by rho[0] = 1), not lag 1; an off-by-one-lag version of this method passed every hand-derived test because the tests were derived by hand using the same wrong pairing.

Returns

number[]

Array of effective sample sizes, one per dimension.

ran.mc.MCMC.iterate([callback[, warmUp]])

Performs a single iteration, updates accumulators, and optionally calls a callback.

Advanced/low-level: most callers should use warmUp and sample instead, which drive iterate() internally. Calling it manually is for cases that need per-step control (e.g. live progress plotting, custom stopping rules). sample() resets the accumulators before it starts collecting, but interleaving manual iterate() calls with warmUp()/sample() otherwise does not — mixing manual draws in can blend adaptation-phase and equilibrium-phase observations into statistics(), ar(), and ac().

Parameters

NameTypeDescription
callbackFunction

Called with (x, accepted) after each iteration.

warmUpboolean

Whether the iteration is part of warm-up. Default is false.

ran.mc.MCMC.sample([progress[, size]])

Samples from the target density. Resets accumulators so that statistics() reflects the sampling phase only, and ar() reflects at most its last arWindow draws (see ADR-0021). Thins the chain by samplingRate (set during warm-up).

Parameters

NameTypeDescription
progressFunction

Called with the integer percentage complete (0–99), once per percent.

sizenumber

Number of samples to collect. Default is 1000.

ran.mc.MCMC.seed(value)

Sets the seed for the sampler's pseudo random number generator. If the initial position was not explicitly provided at construction, it is redrawn from the newly seeded generator so that sampling is fully reproducible.

Parameters

NameTypeDescription
valuenumberstring

The value of the seed, either a number or a string (for the ease of tracking seeds).

Returns

this

Reference to the current sampler.

ran.mc.MCMC.state()

Returns the current state of the sampler. The return value can be passed to a sampler of the same type to resume from this position.

Returns

Object

Object with properties: x (current position), samplingRate (thinning interval), internal (subclass state), and prng (the PRNG's exact stream position, restored on reconstruction so a resumed sampler's subsequent draws are bit-for-bit identical to an uninterrupted run — decisions/0035-mcmc-exact-stream-reproducible-resume.md).

ran.mc.MCMC.statistics()

Computes mean, standard deviation, and coefficient of variation for each dimension based on observations seen since the last reset (start of sampling or construction).

Returns

Object[]

Array of {mean, std, cv} objects, one per dimension.

ran.mc.MCMC.warmUp([progress[, maxBatches]])

Carries out the warm-up phase. Runs batches of 10K iterations, adapts internal parameters via _adjust(), and tunes the thinning interval using the online autocorrelation estimate.

decisions/0024-mcmc-warmup-convergence-strategy.md — deliberately fixed-length, no convergence-triggered early stop: no signal computable from a single chain can distinguish "converged" from "stuck". Gate convergence on gelmanRubin() across multiple independently-seeded chains instead.

Parameters

NameTypeDescription
progressFunction

Called with the percentage complete (0–100) after each batch.

maxBatchesnumber

Number of warm-up batches. Default is 100.

ran.mc.AdaptiveMetropolis(options)

Class implementing the full-covariance adaptive Metropolis algorithm (Haario, Saksman & Tamminen, 2001). Unlike RWM, which adapts only the per-component (diagonal) proposal scale, this sampler learns the full joint proposal covariance from the chain's own history during warm-up: Sigma_proposal = (2.38^2 / dim) * (Cov(x) + epsilon * I). The covariance is refactorized via Matrix.ldl() after every warm-up iteration and frozen once sample() is called, since _adjust is only ever invoked from warmUp().

Parameters

NameTypeDescription
optionsObject

Sampler options, as a single object.

logDensityFunction

The logarithm of the (unnormalized) target density.

configObject

AdaptiveMetropolis configuration (see MCMC base class for shared options).

initialStateObject

Initial state of the sampler (see MCMC base class).

Throws

Error
If options is not a plain object.
ran.mc.ARS(logDensity, support[, derivative])

Class implementing Adaptive Rejection Sampling (Gilks & Wild, 1992) for a univariate log-concave target density on a finite support bracket. A piecewise-linear upper hull, built from tangent lines to the log-density at a growing set of abscissae, gives a piecewise-exponential sampling envelope; a piecewise-linear lower hull built from the secant lines between the same abscissae gives a cheap "squeeze" test that avoids evaluating the true log-density whenever possible. Every time the true log-density does have to be evaluated, the tested point is added to the abscissa set, tightening both hulls so the acceptance probability increases monotonically as sampling proceeds. Unlike MCMC and its subclasses, ARS is not a Markov chain: every draw is an exact, independent sample from the target (up to the target being genuinely log-concave), with no warm-up or burn-in.

Parameters

NameTypeDescription
logDensityFunction

The logarithm of the (unnormalized) target density.

supportnumber[]

The two-element [lo, hi] support bracket. Must be finite with lo < hi.

derivativeFunction

The derivative of logDensity. Estimated via finite differences when omitted.

Throws

Error
If logDensity is not a function, or support is not a
ran.mc.Gibbs(options)

Class implementing a component-wise (systematic-scan) Gibbs sampler. Cycles through the dimensions in a fixed order and replaces each in turn with a draw from its full conditional distribution, given the current values of every other dimension. Because each draw comes directly from the exact conditional, there is no accept/reject step: every iteration is accepted and ar is always 1.

Parameters

NameTypeDescription
optionsObject

Sampler options, as a single object.

conditionalsFunction[]

Array of samplers, one per dimension. The d-th conditional function is called as conditionals[d](x, rng) with the current full state (an array where index d is about to be replaced) and the sampler's own PRNG (exposing rng.next(): number, a uniform variate in [0, 1)), and must return a single draw from the full conditional distribution of dimension d given the rest of the state. seed() only reproduces a conditional's draws if the conditional actually consumes rng for its own randomness (e.g. rng.next()); a conditional that ignores rng and constructs its own independent generator remains non-reproducible regardless of seed() — see decisions/0026-gibbs-seed-rng-threading.md.

configObject

Sampler configuration (see MCMC base class for shared options). dim defaults to conditionals.length; if provided explicitly it must match conditionals.length.

initialStateObject

Initial state of the sampler (see MCMC base class).

Throws

Error
If options is not a plain object, or conditionals is not a non-empty array, or config.dim is provided but does not match conditionals.length.
ran.mc.HMC(options)

Class implementing the Hamiltonian Monte Carlo (HMC) sampler. Uses gradient information and a leapfrog integrator to simulate Hamiltonian dynamics, proposing distant moves along the resulting trajectory and accepting/rejecting via the Metropolis criterion on the augmented (position, momentum) system. Momenta are resampled from a standard multivariate Normal at the start of every iteration. During warm-up, the step size is adapted via Robbins-Monro dual averaging (Hoffman & Gelman 2014, S3.2) toward a target acceptance probability, and jittered multiplicatively each iteration to avoid periodicity artifacts.

Known limitation: only stepSize is jittered — pathLength (the number of leapfrog steps) stays fixed for the sampler's entire lifetime. A fixed trajectory length (pathLength * stepSize) can still land near a half-period of the target's natural oscillation at certain target correlations, producing genuine negative low-lag autocorrelation that ess() and ac() faithfully report — this is a legitimate property of the chain, not a bug in those estimators. If you observe this (e.g. ac() reporting negative autocorrelation at low lags, or ess() reporting an effective sample size well above or below the raw sample count), try a different pathLength, or switch to NUTS, which adapts trajectory length automatically each iteration (Hoffman & Gelman 2014) and removes the need to hand-tune pathLength.

Parameters

NameTypeDescription
optionsObject

Sampler options, as a single object.

logDensityFunction

The logarithm of the (unnormalized) target density.

gradLogDensityFunction

The gradient of logDensity: maps a state (number[]) to its gradient (number[]) of the same dimension. The array passed in may be reused and mutated across subsequent leapfrog steps; read it synchronously and do not retain the reference.

configObject

HMC configuration (see MCMC base class for shared options), plus stepSize (ε, the leapfrog step size, default 0.1), pathLength (L, the number of leapfrog steps per iteration, default 10 — fixed for the sampler's lifetime and not jittered like stepSize; see the class JSDoc's "Known limitation" note for the resonance risk this can produce), and metric (the mass matrix structure adapted during warm-up: 'diag' (default) estimates a per-dimension variance; 'dense' estimates the full covariance matrix, refactored through Matrix's LDL decomposition).

initialStateObject

Initial state of the sampler (see MCMC base class).

Throws

Error
If options is not a plain object, or gradLogDensity is not a function, or a resumed initialState.internal.stepSize) is provided but is not a positive finite number, or a pathLength (config.pathLength or a resumed initialState.internal.pathLength) is provided but is not a positive integer or exceeds
ran.mc.MALA(options)

Class implementing the Metropolis-adjusted Langevin algorithm (MALA) sampler. Proposes a single gradient-informed Langevin step per iteration (x' = x + (stepSize^2 / 2) * gradLogDensity(x) + stepSize * z, z ~ N(0, I)), then applies a Metropolis-Hastings correction for the proposal's asymmetry (the transition density's mean is state-dependent, so q(x'|x) != q(x|x')) to make the chain exact. During warm-up, the step size is adapted via batch Robbins-Monro (Roberts & Rosenthal 2009), the same scheme RWM uses, toward the MALA-optimal acceptance rate of ~0.574 (Roberts & Rosenthal 1998).

Parameters

NameTypeDescription
optionsObject

MALA options, as a single object.

logDensityFunction

The logarithm of the (unnormalized) target density.

gradLogDensityFunction

The gradient of logDensity: maps a state (number[]) to its gradient (number[]) of the same dimension.

configObject

MALA configuration (see MCMC base class for shared options), plus stepSize (ε, default 0.1).

initialStateObject

Initial state of the sampler (see MCMC base class).

Throws

Error
If options is not a plain object, or gradLogDensity is not a function, or a stepSize (config.stepSize or a resumed initialState.internal.stepSize) is provided but is not a positive finite number.
ran.mc.NUTS(options)

Class implementing the No-U-Turn Sampler (NUTS). Extends Hamiltonian Monte Carlo by replacing a fixed-length leapfrog trajectory with a recursive doubling-tree procedure that extends forward or backward in a randomly chosen direction until the trajectory's outer endpoints start turning back toward each other (the "U-turn" stopping criterion) or a maximum tree depth is reached. The transition is selected via slice sampling over the tree's valid states, eliminating the need to hand-tune a trajectory length. Momenta are resampled from N(0, M) at the start of every iteration, where M is the Euclidean mass matrix adapted during warm-up (config.metric); the no-U-turn criterion is evaluated on the velocity M⁻¹r. During warm-up, the step size is adapted via Robbins-Monro dual averaging (Hoffman & Gelman 2014, S3.2) toward a target acceptance probability, driven by the tree-averaged acceptance statistic accumulated across every leapfrog evaluation in that iteration's tree.

Sampler-health diagnostics are exposed both per-transition and in aggregate: every iterate result carries divergent and maxDepthHit booleans, and divergenceCount / maxDepthCount report the per-sampling-phase totals (reset like ar). A well-behaved run reports both counts as 0; nonzero divergences flag a step size that is too large or a target too extreme, nonzero max-depth hits a step size that is too small. See decisions/0035-nuts-sampler-health-diagnostics.md.

Parameters

NameTypeDescription
optionsObject

Sampler options, as a single object.

logDensityFunction

The logarithm of the (unnormalized) target density.

gradLogDensityFunction

The gradient of logDensity: maps a state (number[]) to its gradient (number[]) of the same dimension.

configObject

NUTS configuration (see MCMC base class for shared options), plus stepSize (ε, the leapfrog step size, default 0.1) and metric (the mass matrix structure adapted during warm-up: 'diag' (default) estimates a per-dimension variance; 'dense' estimates the full covariance matrix, refactored through Matrix's LDL decomposition).

initialStateObject

Initial state of the sampler (see MCMC base class).

Throws

Error
If options is not a plain object, or gradLogDensity is not a function, or a stepSize (config.stepSize or a resumed initialState.internal.stepSize) is provided but is not a positive finite number, or metric is provided but is not
ran.mc.NUTS.divergenceCount()

Returns the number of divergent transitions recorded during the current sampling phase. A divergent transition is one whose leapfrog trajectory contained a leaf whose Hamiltonian drifted more than the energy-divergence threshold from the trajectory's start, indicating the step size is too large or the target geometry too extreme (biased exploration). Reset at construction and at the start of each sample call, so a read afterwards reflects the sampling phase only — the same lifecycle as ar. A well-behaved run reports 0.

Returns

number

Count of divergent transitions since the last reset.

ran.mc.NUTS.maxDepthCount()

Returns the number of transitions that reached the maximum tree depth during the current sampling phase. A max-depth hit is a doubling that exhausted the tree-depth cap without the trajectory U-turning, indicating the step size is too small (inefficient sampling). Reset at construction and at the start of each sample call, so a read afterwards reflects the sampling phase only — the same lifecycle as ar. A well-behaved run reports 0.

Returns

number

Count of max-tree-depth-saturated transitions since the last reset.

ran.mc.ParallelTempering(options[, legacyOptions])

Class implementing Parallel Tempering (Replica Exchange MCMC, Geyer 1991) to sample multimodal targets. Runs N independent MCMC replicas at inverse temperatures beta_1 = 1 > beta_2 > ... > beta_n, replica i targeting beta_i * logDensity(x). Hot replicas (small beta) have a flattened target and cross low-probability barriers between modes easily; the cold replica (beta = 1) samples the true target. After each thinned step, a swap between one alternating-parity set of adjacent replica pairs is proposed and accepted with probability min(1, exp((beta_i - beta_j) * (logDensity(x_j) - logDensity(x_i)))) (the direction that follows from detailed balance on the joint replica distribution; see the _proposeSwap implementation comment), letting the cold chain inherit the hot chains' mode-crossing moves.

Unlike every other class in ran.mc, this is not an MCMC subclass: it has no single position or target density of its own, only an array of independent replicas and the swap logic that couples them (see decisions/0028-parallel-tempering-standalone-coordinator.md). Each replica keeps its own proposal tuning pinned to its temperature slot; an accepted swap exchanges only the replicas' positions (and, where present, their cached scaled log-density), not their adaptation state.

Parameters

NameTypeDescription
optionsObject

Coordinator options, as a single object. Supported properties:

legacyOptionsObject

Deprecated positional-form options object, read only when the deprecated new ParallelTempering(logDensity, options) form is used. Do not use in new code.

Throws

Error
If logDensity is not a function.
Error
If neither temperatures nor nReplicas and tempMax are provided, or if they are invalid.
ran.mc.RWM(options)

Class implementing the (random walk) Metropolis algorithm as a diagonal adaptive Metropolis sampler. Proposals are joint (every component perturbed at once) in both warm-up and sampling; during warm-up a single global step scale is adapted via batch Robbins-Monro toward the optimal acceptance rate (0.44 in one dimension, 0.234 for higher dimensions) and the per-component scales track the running marginal standard deviations.

Parameters

NameTypeDescription
optionsObject

Sampler options, as a single object.

logDensityFunction

The logarithm of the (unnormalized) target density.

configObject

RWM configuration (see MCMC base class for shared options).

initialStateObject

Initial state of the sampler (see MCMC base class).

Throws

Error
If options is not a plain object.
ran.mc.Slice(options)

Class implementing coordinate-wise slice sampling (Neal, R.M. (2003) "Slice Sampling", Annals of Statistics 31(3):705-767) via the stepping-out and shrinkage procedure. Each sweep updates every dimension in turn: a vertical level is drawn below the current point's density, an interval bracketing the resulting horizontal slice is found by stepping outward in increments of w, and a point within that interval is accepted once shrinkage finds one whose density exceeds the vertical level. No proposal distribution or gradient is required, and every sweep produces an accepted draw, so ar is always 1.

A prior, non-functional slice.js (100% commented out, 1D only, never wired into the base class) was deleted as dead code in PR #615; this is a fresh implementation, not a restoration.

Parameters

NameTypeDescription
optionsObject

Sampler options, as a single object.

logDensityFunction

The logarithm of the (unnormalized) target density.

configObject

Sampler configuration (see MCMC base class for shared options).

initialStateObject

Initial state of the sampler (see MCMC base class). The interval width w (default 1.0) may be seeded via initialState.internal.w, either as a single number (broadcast to every dimension) or as a per-dimension array.

Throws

Error
If options is not a plain object, or if
ran.process.Process()

The stochastic process generator base class, all process generators extend this class. The methods listed here are available for all process generators.

ran.process.Process.covariogram(s, t)

Returns the analytical covariogram (covariance function) of the process evaluated at times s and t. Must be implemented by subclasses.

Parameters

NameTypeDescription
snumber

First time point.

tnumber

Second time point.

Returns

number

Covariance between the process values at times s and t.

ran.process.Process.ensemble(m, n)

Generates m independent paths of n steps each by calling path(n) m times.

Parameters

NameTypeDescription
mnumber

Number of paths.

nnumber

Number of steps per path.

Returns

Array

Array of m arrays, each of length n+1 (initial state followed by n states).

ran.process.Process.marginal(t)

Returns the marginal distribution of the process at time t as a fully-functional Distribution instance, unlocking the entire Distribution API (quantile, hazard, survival, likelihood, aic, bic, test) on the marginal without additional numerical machinery. Must be implemented by subclasses.

decisions/0040-process-marginal-distribution-instance.md — returns an existing Distribution instance built from already-derived mean()/variance()/pdf() parameters, instead of duplicating Distribution's numerical machinery on Process.

Parameters

NameTypeDescription
tnumber

Time.

Throws

Error
If not implemented by the subclass, or if t is outside the process's domain.
ran.process.Process.mean(t)

Returns the analytical mean of the process at time t. Must be implemented by subclasses.

Parameters

NameTypeDescription
tnumber

Time.

Returns

number

Expected value at time t, or NaN for t < 0.

ran.process.Process.next()

Advances the process by one step, updates the current state, and returns the new state.

Returns

number

The new state after the step.

ran.process.Process.path(n)

Generates a path of n steps starting from the initial state. Advances the PRNG stream by n steps (like sample()), so consecutive calls return independent realizations. The process state is restored to its pre-call value after generation.

Parameters

NameTypeDescription
nnumber

Number of steps.

Returns

Array

Array of n+1 states (initial state followed by n successive states).

ran.process.Process.pdf(x, t)

Returns the marginal probability density or mass at state x and time t. For continuous processes this is a probability density; for discrete processes (e.g. Poisson) this is a probability mass. Must be implemented by subclasses.

Parameters

NameTypeDescription
xnumber

State value.

tnumber

Time.

Returns

number

Marginal density or mass at (x, t), or NaN when t is out of domain.

ran.process.Process.reset()

Resets the process to its initial state.

ran.process.Process.seed(value)

Seeds the internal PRNG for reproducible paths.

Parameters

NameTypeDescription
valuenumberstring

Seed value passed to the underlying Xoshiro128p PRNG.

Returns

this

Reference to the current process.

ran.process.Process.state()

Returns the current state of the process.

Returns

number

Current state.

ran.process.Process.variance(t)

Returns the analytical variance of the process at time t. Must be implemented by subclasses.

Parameters

NameTypeDescription
tnumber

Time.

Returns

number

Variance at time t, or NaN for t < 0.

ran.process.AR1(phi, sigma)

First-order autoregressive (AR(1)) process, the discrete-time analogue of the Ornstein-Uhlenbeck process.

The update rule per step is

X_{n+1} = \phi X_n + \sigma Z,

where Z \sim \mathcal{N}(0, 1) . For |\phi| < 1 the process is stationary with marginal distribution \mathcal{N}(0, \sigma^2/(1-\phi^2)) . For |\phi| \geq 1 the process is non-stationary and grows without bound; a warning is emitted but no error is thrown.

Parameters

NameTypeDescription
phinumber

Autoregressive coefficient.

sigmanumber

Innovation standard deviation (must be > 0).

ran.process.BrownianBridge(sigma, T[, dt])

Brownian bridge process conditioned to return to 0 at time T, using an exact discrete-time sampler.

The underlying SDE is

\mathrm{d}X_t = -\frac{X_t}{T - t} \mathrm{d}t + \sigma \mathrm{d}W_t.

Because the SDE is linear, the conditional distribution X_{t+\mathrm{d}t} \mid X_t = x, X_T = 0 is Gaussian, derived from the covariance structure of the Wiener process. The sampler draws from that distribution directly

X_{t+\mathrm{d}t} = X_t \frac{T - t - \mathrm{d}t}{T - t} + \sigma\sqrt{\frac{\mathrm{d}t (T - t - \mathrm{d}t)}{T - t}},Z,

where Z \sim \mathcal{N}(0, 1) . There is no step-size discretization error. The process pins to 0 at step N = T/\mathrm{d}t .

Parameters

NameTypeDescription
sigmanumber

Volatility (must be > 0).

Tnumber

Terminal time (must be > 0).

dtnumber

Time step (must be > 0; T/dt must be a positive integer).

ran.process.BrownianMotion(mu, sigma[, dt])

Brownian motion (Wiener process) with drift, using an exact discrete-time sampler.

The underlying SDE is

\mathrm{d}X_t = \mu \mathrm{d}t + \sigma \mathrm{d}W_t.

Because the coefficients are constant (state-independent), the Euler–Maruyama step coincides with the exact transition: each increment is an independent draw from \mathcal{N}(\mu \mathrm{d}t ,\sigma^2 \mathrm{d}t) , giving the update rule

X_{t+\mathrm{d}t} = X_t + \mu,\mathrm{d}t + \sigma\sqrt{\mathrm{d}t},Z,

where Z \sim \mathcal{N}(0, 1) . There is no step-size discretization error.

Parameters

NameTypeDescription
munumber

Drift coefficient.

sigmanumber

Diffusion coefficient (must be > 0).

dtnumber

Time step (must be > 0).

ran.process.CompoundPoisson(jumpDist, lambda[, dt])

Compound Poisson process: cumulative random-magnitude jumps arriving at a Poisson rate.

At each time step of width \mathrm{d}t the state advances by the sum of K \sim \mathrm{Poisson}(\lambda,\mathrm{d}t) independent jumps drawn from the supplied distribution:

X_{t+\mathrm{d}t} = X_t + \sum_{i=1}^{K} J_i,

where K \sim \mathrm{Poisson}(\lambda,\mathrm{d}t) and J_i \sim \text{jumpDist} .

Parameters

NameTypeDescription
jumpDistObject

A ran.dist Distribution instance whose .sample() method supplies jump sizes.

lambdanumber

Arrival rate (must be > 0).

dtnumber

Time step (must be > 0).

Deprecated

Use ran.process.CompoundPoisson instead. This class will be removed in v1.33.0.

ran.process.CompoundPoissonProcess(jumpDist, lambda[, dt])

Deprecated alias for ran.process.CompoundPoisson. Process must not appear in Process subclass names (decisions/0041-process-subclass-naming-no-process-suffix.md).

Parameters

NameTypeDescription
jumpDistObject

A ran.dist Distribution instance whose .sample() method supplies jump sizes.

lambdanumber

Arrival rate (must be > 0).

dtnumber

Time step (must be > 0).

References

ran.process.CoxIngersollRoss(kappa, theta, sigma[, dt])

Cox-Ingersoll-Ross (CIR) mean-reverting process, using an Euler-Maruyama discretization with reflection to keep paths non-negative.

The underlying SDE is

\mathrm{d}X_t = \kappa(\theta - X_t) \mathrm{d}t + \sigma\sqrt{X_t} \mathrm{d}W_t.

The Euler-Maruyama step uses reflection to prevent the noise term from amplifying negative states:

X_{t+\mathrm{d}t} = X_t + \kappa(\theta - X_t),\mathrm{d}t + \sigma\sqrt{\max(X_t, 0)},\sqrt{\mathrm{d}t},Z,

where Z \sim \mathcal{N}(0, 1) . When the Feller condition 2\kappa\theta > \sigma^2 holds, the continuous-time process is strictly positive; below the Feller threshold, paths may occasionally become negative under Euler-Maruyama despite the reflection.

Parameters

NameTypeDescription
kappanumber

Mean-reversion speed (must be > 0).

thetanumber

Long-run mean (must be > 0).

sigmanumber

Volatility (must be > 0).

dtnumber

Time step (must be > 0).

ran.process.GeometricBrownianMotion(mu, sigma[, dt])

Geometric Brownian Motion with drift, using an exact discrete-time sampler.

The underlying SDE is

\mathrm{d}X_t = \mu X_t \mathrm{d}t + \sigma X_t \mathrm{d}W_t.

By Itô's formula, \log X_t follows Brownian motion with drift, yielding the closed-form solution X_t = X_0\exp((\mu - \sigma^2/2)t + \sigma W_t) . Each step is therefore an independent lognormal draw

X_{t+\mathrm{d}t} = X_t \exp!\left((\mu - \tfrac{\sigma^2}{2}),\mathrm{d}t + \sigma\sqrt{\mathrm{d}t},Z\right),

where Z \sim \mathcal{N}(0, 1) . There is no step-size discretization error.

Parameters

NameTypeDescription
munumber

Drift rate.

sigmanumber

Volatility (must be > 0).

dtnumber

Time step (must be > 0).

ran.process.OrnsteinUhlenbeck(theta, mu, sigma[, dt])

Ornstein-Uhlenbeck mean-reverting process, using an exact discrete-time sampler.

The underlying SDE is

\mathrm{d}X_t = \theta(\mu - X_t) \mathrm{d}t + \sigma \mathrm{d}W_t.

Because the SDE is linear, X_{t+\mathrm{d}t} \mid X_t is Gaussian with closed-form mean and variance. The sampler draws from that distribution directly

X_{t+\mathrm{d}t} = X_t,e^{-\theta,\mathrm{d}t} + \mu\left(1 - e^{-\theta,\mathrm{d}t}\right) + \sigma\sqrt{\frac{1 - e^{-2\theta,\mathrm{d}t}}{2\theta}},Z,

where Z \sim \mathcal{N}(0, 1) . There is no step-size discretization error regardless of \mathrm{d}t .

Parameters

NameTypeDescription
thetanumber

Mean-reversion speed (must be > 0).

munumber

Long-run mean.

sigmanumber

Diffusion coefficient (must be > 0).

dtnumber

Time step (must be > 0).

ran.process.Poisson(lambda[, dt])

Poisson process: a counting process of independent arrivals at rate \lambda , using an exact discrete-time sampler.

By the independent-increments property, the number of arrivals in any interval of length \mathrm{d}t is exactly \mathrm{Poisson}(\lambda \mathrm{d}t) , independent of all other intervals. The sampler draws that count directly

X_{t+\mathrm{d}t} = X_t + K, \quad K \sim \mathrm{Poisson}(\lambda,\mathrm{d}t),

with no step-size discretization error.

Parameters

NameTypeDescription
lambdanumber

Event rate (must be > 0).

dtnumber

Time step (must be > 0).

Deprecated

Use ran.process.Poisson instead. This class will be removed in v1.33.0.

ran.process.PoissonProcess(lambda[, dt])

Deprecated alias for ran.process.Poisson. Process must not appear in Process subclass names (decisions/0041-process-subclass-naming-no-process-suffix.md).

Parameters

NameTypeDescription
lambdanumber

Event rate (must be > 0).

dtnumber

Time step (must be > 0).

References

ran.process.RandomWalk(p)

Discrete-time random walk on the integers: at each step the state moves by +1 with probability p and by −1 with probability 1 − p. For p = 0.5 the walk is symmetric (unbiased); for p ≠ 0.5 it has drift 2p − 1 per step.

The update rule is

X_{n+1} = X_n + \begin{cases} +1 & \text{if } U < p, \ -1 & \text{if } U \geq p, \end{cases}

where U \sim \mathrm{Uniform}(0,1) .

Parameters

NameTypeDescription
pnumber

Probability of a +1 step (must satisfy 0 < p < 1).

ran.shape.kurtosis(values)

Calculates the sample excess kurtosis which is unbiased for the normal distribution.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate kurtosis for.

Returns

number

The sample excess kurtosis, or NaN for fewer than 3 elements or zero variance.

Examples

ran.shape.kurtosis([])
// => NaN

ran.shape.kurtosis([1, 2])
// => NaN

ran.shape.kurtosis([1, 1, 1])
// => NaN

ran.shape.kurtosis([1, 1, 3, 1, 1])
// => 5.000000000000003

ran.shape.kurtosis([1, 2, 2, 2, 1])
// => -3.3333333333333326
ran.shape.max(values)

Returns the maximum of an array of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to find the maximum for.

Returns

number

The maximum of the values, or NaN for an empty array.

Examples

ran.shape.max([])
// => NaN

ran.shape.max([3, 1, 4, 1, 5, 9])
// => 9
ran.shape.min(values)

Returns the minimum of an array of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to find the minimum for.

Returns

number

The minimum of the values, or NaN for an empty array.

Examples

ran.shape.min([])
// => NaN

ran.shape.min([3, 1, 4, 1, 5, 9])
// => 1
ran.shape.moment(values, k[, c])

Calculates the k-th raw moment for a sample of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate moment for.

knumber

Order of the moment.

cnumber

Value to shift the distribution by before calculating the moment.

Returns

number

The k-th moment, or NaN for an empty array.

Examples

ran.shape.moment([], 2)
// => NaN

ran.shape.moment([1, 2, 3], 0)
// => 1

ran.shape.moment([1, 2, 3], 2)
// => 4.666666666666667
ran.shape.quantile(values, p)

Calculates the quantile at 0 < p < 1 using the R-7 algorithm.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate quantile for.

pnumber

Value to calculate quantile at.

Returns

number

The quantile of the sample, or NaN for an empty array.

ran.shape.rank(values)

Calculates the fractional rank for an array of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate ranks for.

Returns

number[]

The ranks of the values, or an empty array for empty input.

Examples

ran.shape.rank([])
// => []

ran.shape.rank([1, 2, 2, 3])
// => [1, 2.5, 2.5, 4]
ran.shape.skewness(values)

Calculates the Fisher-Pearson standardized sample skewness for a sample of values.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate skewness for.

Returns

number

The sample skewness, or NaN for fewer than 3 elements or zero variance.

Examples

ran.shape.skewness([])
// => NaN

ran.shape.skewness([1, 2])
// => NaN

ran.shape.skewness([1, 1, 1])
// => NaN

ran.shape.skewness([1, 1, 1, 2])
// => 2

ran.shape.skewness([1, 2, 2, 2])
// => -2
ran.shape.yule(values)

Calculates Yule's coefficient which is a measure of skewness based on quantiles.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to calculate Yule's coefficient for.

Returns

number

Yule's coefficient, or NaN for an empty array or when the lower and upper quartiles are equal.

Examples

ran.shape.yule([])
// => NaN

ran.shape.yule([1, 1, 1])
// => NaN

ran.shape.yule([1, 1, 1, 2])
// => 1

ran.shape.yule([1, 2, 2, 2])
// => -1
ran.test.bartlett(dataSets[, alpha])

Calculates the Bartlett statistics for multiple data sets.

Parameters

NameTypeDescription
dataSetsArray[]

Array containing the data sets.

alphanumber

Confidence level.

Returns

Object containing the test statistics (chi2) and whether the data sets passed the null hypothesis that their variances are the same.

Throws

Error
If the number of data sets is less than 2.
Error
If the size of any data set is less than 2 elements.

Examples

let normal1 = new ran.dist.Normal(1, 2)
let normal2 = new ran.dist.Normal(1, 3)
let normal3 = new ran.dist.Normal(1, 5)

ran.test.bartlett([normal1.sample(100), normal1.sample(100), normal1.sample(100)], 0.1)
// => { stat: 0.09827551592930094, passed: true }

ran.test.bartlett([normal1.sample(100), normal2.sample(100), normal3.sample(100)], 0.1)
// => { stat: 104.31185521417476, passed: false }
ran.test.brownForsythe(dataSets[, alpha])

Calculates the Brown-Forsythe test statistic for multiple data sets.

Parameters

NameTypeDescription
dataSetsArray[]

Array containing the data sets.

alphanumber

Confidence level.

Returns

Object containing the test statistics (W) and whether the data sets passed the null hypothesis that their variances are the same.

Throws

Error
If the number of data sets is less than 2.
Error
If the size of any data set is less than 2 elements.

Examples

let normal1 = new ran.dist.Normal(1, 2)
let normal2 = new ran.dist.Normal(1, 3)
let normal3 = new ran.dist.Normal(1, 5)

ran.test.brownForsythe([normal1.sample(100), normal1.sample(100), normal1.sample(100)], 0.1)
// => { stat: 1.0664885130451343, passed: true }

ran.test.brownForsythe([normal1.sample(100), normal2.sample(100), normal3.sample(100)], 0.1)
// => { stat: 27.495614343570345, passed: false }
ran.test.cramerVonMises(values, cdf[, alpha])

Calculates the Cramér-von Mises statistic for an array of values against a cumulative distribution function, testing the null hypothesis that the sample is drawn from the distribution the CDF represents. The asymptotic p-value uses the Csörgő & Faraway (1996) convergent series for the limiting distribution's CDF.

Parameters

NameTypeDescription
valuesnumber[]

Array of values to perform the test for.

cdfFunction

Cumulative distribution function to test against.

alphanumber

Confidence level.

Returns

Object containing the test statistic (T = n omega^2), the asymptotic goodness-of-fit p-value, and whether the sample passed the null hypothesis that it is drawn from the tested distribution.

Throws

Error
If values is empty.

Examples

let normal = new ran.dist.Normal(0, 1)

ran.test.cramerVonMises(normal.sample(100), x => normal.cdf(x))
// => { stat: 0.043, pValue: 0.802, passed: true }
ran.test.hsic(dataSets[, alpha])

Calculates the Hilbert-Schmidt independence criterion (HSIC) for paired arrays of values. HSIC tests if two data sets are statistically independent. Source: A. Gretton et al. A Kernel Statistical Test of Independence in Advances in Neural Information Processing Systems (2008).

Parameters

NameTypeDescription
dataSetsArray[]

Array containing the two data sets.

alphanumber

Confidence level.

Returns

Object containing the test statistics and whether the data sets passed the null hypothesis that they are statistically independent.

Throws

Error
If the number of data sets is less than 2.
Error
If the data sets have different sample size.
Error
If the sample size is less than 6.

Examples

let sample1 = Array.from({length: 50}, (d, i) => i)
let sample2 = sample1.map(d => d + Math.random() - 0.5)
ran.test.hsic([sample1, sample2])
// => { stat: 6.197628059960943, passed: false }

sample1 = ran.core.float(0, 10, 50)
sample2 = ran.core.float(0, 10, 50)
ran.test.hsic([sample1, sample2])
// => { stat: 0.3876607680368274, passed: true }
ran.test.levene(dataSets, alpha)

Calculates the Levene's test statistic for multiple data sets.

Parameters

NameTypeDescription
dataSetsArray[]

Array containing the data sets.

alphanumber

Confidence level.

Returns

Object containing the test statistics (W) and whether the data sets passed the null hypothesis that their variances are the same.

Throws

Error
If the number of data sets is less than 2.
Error
If the size of any data set is less than 2 elements.

Examples

let normal1 = new ran.dist.Normal(1, 2)
let normal2 = new ran.dist.Normal(1, 3)
let normal3 = new ran.dist.Normal(1, 5)

ran.test.levene([normal1.sample(100), normal1.sample(100), normal1.sample(100)], 0.1)
// => { stat: 0.019917137672045088, passed: true }

ran.test.levene([normal1.sample(100), normal2.sample(100), normal3.sample(100)], 0.1)
// => { stat: 29.06345994086687, passed: false }
ran.test.mannWhitney(dataSets[, alpha])

Calculates the Mann-Whitney statistics for two data sets.

Parameters

NameTypeDescription
dataSetsArray[]

Array containing the two data sets.

alphanumber

Confidence level.

Returns

Object containing the (non-standardized) test statistics (U) and whether the data sets passed the null hypothesis that the samples come from the same distribution.

Throws

Error
If the number of data sets is different from 2.

Examples

let pareto = new ran.dist.Pareto(1, 2)
let uniform = new ran.dist.Uniform(1, 10)

ran.test.mannWhitney([pareto.sample(100), pareto.sample(100)], 0.1)
// => { stat: 4941, passed: true }

ran.test.mannWhitney([pareto.sample(100), uniform.sample(100)], 0.1)
// => { stat: 132, passed: false }
ran.test.welch(x, y[, alpha])

Calculates Welch's two-sample t-test for two data sets.

Parameters

NameTypeDescription
xnumber[]

First sample.

ynumber[]

Second sample.

alphanumber

Confidence level.

Returns

Object containing the test statistic (t) and whether the data sets passed the null hypothesis that their means are equal.

Throws

Error
If either sample has fewer than 2 elements.

Examples

let normal1 = new ran.dist.Normal(0, 1)
let normal2 = new ran.dist.Normal(5, 1)

ran.test.welch(normal1.sample(100), normal1.sample(100))
// => { stat: -0.43, passed: true }

ran.test.welch(normal1.sample(100), normal2.sample(100))
// => { stat: -49.3, passed: false }