stats::dist
On this page
Probability distributions as types. Each is built by a new that
checks its parameters (throwing InvalidParameter), never panics
afterwards, and implements Distribution (sampling) and either
Continuous or Discrete (density, CDF, quantile, moments). The
functions take one point; for an array use the broadcast call form
Normal::pdf.(d, xs).
Structs
BernoulliSource
pub struct BernoulliThe Bernoulli distribution: 1 with probability p, else 0.
use stats::{Bernoulli, Discrete};
let d = try Bernoulli::new(0.3);
assert(d.pmf(1) == 0.3 && d.cdf(0) == 0.7 && d.var() == 0.21);
Sourcepub fn new(§p: f64) throws (StatsError) -> Bernoulli Bernoulli(p),
0 <= p <= 1.The probability of 1.
Sourcepub fn fit<X: Sample>(§x: X) throws (StatsError) -> Bernoulli The maximum-likelihood fit: the share of ones. Values must be 0 or 1.
nabiassert((try stats::Bernoulli::fit([1, 0, 0, 1])).p() == 0.5);
Trait implementations 2
impl Distribution for Bernoulliimpl Discrete for Bernoulli
BetaSource
pub struct BetaThe beta distribution with shapes a, b > 0 on [0, 1]. The CDF is
the regularized incomplete beta function; draws from two gamma
deviates.
use stats::{Beta, Continuous};
let d = try Beta::new(2.0, 3.0);
assert(d.mean() == 0.4);
assert((d.cdf(0.4) - 0.5248).abs() < 1e-15);
Sourcepub fn new(§a: f64, b: f64) throws (StatsError) -> Beta Beta(a, b); both finite and positive.
The first shape.
The second shape.
Trait implementations 2
impl Distribution for Betaimpl Continuous for Beta
BinomialSource
pub struct BinomialThe binomial distribution: the number of successes in n >= 0
independent trials of probability p. The PMF and CDF go through
the incomplete beta function's factor and continued fraction, so
both tails keep their relative accuracy for large n.
use stats::{Binomial, Discrete};
let d = try Binomial::new(20, 0.3);
assert((d.cdf(4) - 0.2375077788776017).abs() < 1e-15);
assert(d.mean() == 6.0);
Sourcepub fn new(§n: i64, p: f64) throws (StatsError) -> Binomial Binomial(n, p),
n >= 0,0 <= p <= 1.The number of trials.
The success probability.
Sourcepub fn fit<X: Sample>(§x: X, n: i64) throws (StatsError) -> Binomial The maximum-likelihood
pfor counts out ofntrials each:sum(x) / (n * len(x)).nabiassert((try stats::Binomial::fit([3, 5, 4], 10)).p() == 0.4);
Trait implementations 2
impl Distribution for Binomialimpl Discrete for Binomial
CauchySource
pub struct CauchyThe Cauchy (Lorentz) distribution with location x0 and scale
gamma > 0: Student's t with one degree of freedom, shifted and
scaled. It has no mean or variance (both NaN).
use stats::{Cauchy, Continuous};
let d = try Cauchy::new(0.0, 1.0);
assert(d.cdf(1.0) == 0.75 && d.ppf(0.75) == 1.0000000000000002);
Sourcepub fn new(§x0: f64, gamma: f64) throws (StatsError) -> Cauchy Cauchy(x0, gamma);
x0finite,gammafinite and > 0.The location (the median).
The scale (half the interquartile range).
Trait implementations 2
impl Distribution for Cauchyimpl Continuous for Cauchy
ChiSquaredSource
pub struct ChiSquaredThe chi-squared distribution with k > 0 degrees of freedom
(Gamma(k / 2, 2)); k need not be an integer.
use stats::{ChiSquared, Continuous};
let d = try ChiSquared::new(3.0);
assert((d.sf(7.814727903251178) - 0.05).abs() < 1e-15);
Sourcepub fn new(§k: f64) throws (StatsError) -> ChiSquared Chi-squared with
kdegrees of freedom (finite, > 0).The degrees of freedom.
Trait implementations 2
impl Distribution for ChiSquaredimpl Continuous for ChiSquared
ExponentialSource
pub struct ExponentialThe exponential distribution with rate lambda > 0 (mean 1 / lambda; SciPy's expon(scale=1/lambda)).
use stats::{Continuous, Exponential};
let d = try Exponential::new(2.0);
assert(d.mean() == 0.5);
assert((d.cdf(1.0) - (1.0 - (-2.0).exp())).abs() < 1e-16);
Sourcepub fn new(§lambda: f64) throws (StatsError) -> Exponential The exponential distribution with rate
lambda(finite, > 0).The rate.
Sourcepub fn fit<X: Sample>(§x: X) throws (StatsError) -> Exponential The maximum-likelihood fit
lambda = 1 / mean(x); values must be>= 0and not all 0.nabiassert((try stats::Exponential::fit([1.0, 2.0, 3.0])).rate() == 0.5);
Trait implementations 2
impl Distribution for Exponentialimpl Continuous for Exponential
FisherFSource
pub struct FisherFThe F distribution with d1, d2 > 0 degrees of freedom: the ratio
of two scaled chi-squared variables. CDF I_x(d1 / 2, d2 / 2) with
x = d1 f / (d1 f + d2).
use stats::{Continuous, FisherF};
let d = try FisherF::new(3.0, 20.0);
assert((d.sf(3.0983912121407795) - 0.05).abs() < 1e-14);
Sourcepub fn new(§d1: f64, d2: f64) throws (StatsError) -> FisherF F(d1, d2); both finite and positive.
The numerator degrees of freedom.
The denominator degrees of freedom.
Trait implementations 2
impl Distribution for FisherFimpl Continuous for FisherF
GammaSource
pub struct GammaThe gamma distribution with shape k > 0 and scale theta > 0
(mean k theta). The CDF is the regularized incomplete gamma
function; draws by Marsaglia and Tsang (2000).
use stats::{Continuous, Gamma};
let d = try Gamma::new(2.0, 3.0);
assert(d.mean() == 6.0 && d.var() == 18.0);
assert((d.cdf(6.0) - 0.5939941502901619).abs() < 1e-15);
Sourcepub fn new(§k: f64, theta: f64) throws (StatsError) -> Gamma Gamma(k, theta); both finite and positive.
The shape.
The scale.
Sourcepub fn fit<X: Sample>(§x: X) throws (StatsError) -> Gamma The maximum-likelihood fit. The shape solves
ln k - psi(k) = ln mean(x) - mean(ln x)by Newton's method from Minka's (2002) start; thentheta = mean / k. Values must be positive and not all equal.nabilet d = try stats::Gamma::fit([1.0, 2.0, 3.0, 4.0, 5.0]); assert((d.shape() - 3.701643810008814).abs() < 1e-10); // SciPy: gamma.fit(x, floc=0)
Trait implementations 2
impl Distribution for Gammaimpl Continuous for Gamma
GeometricSource
pub struct GeometricThe geometric distribution on 1, 2, 3, ...: the number of trials of
probability p up to and including the first success (SciPy's
geom). P(X = k) = (1 - p)^(k - 1) p.
use stats::{Discrete, Geometric};
let d = try Geometric::new(0.25);
assert(d.pmf(2) == 0.1875 && d.mean() == 4.0);
assert(d.ppf(0.25) == 1 && d.ppf(0.4375) == 2);
Sourcepub fn new(§p: f64) throws (StatsError) -> Geometric Geometric(p),
0 < p <= 1.The success probability.
Sourcepub fn fit<X: Sample>(§x: X) throws (StatsError) -> Geometric The maximum-likelihood fit
p = 1 / mean(x); values are trial counts >= 1.nabiassert((try stats::Geometric::fit([1, 3, 4])).p() == 0.375);
Trait implementations 2
impl Distribution for Geometricimpl Discrete for Geometric
LaplaceSource
pub struct LaplaceThe Laplace distribution with location mu and scale b > 0:
density e^(-|x - mu| / b) / (2 b).
use stats::{Continuous, Laplace};
let d = try Laplace::new(0.0, 1.0);
assert(d.cdf(0.0) == 0.5 && d.var() == 2.0);
assert((d.ppf(0.25) + 2.0.ln()).abs() < 1e-16);
Sourcepub fn new(§mu: f64, b: f64) throws (StatsError) -> Laplace Laplace(mu, b);
mufinite,bfinite and > 0.The location.
The scale.
Sourcepub fn fit<X: Sample>(§x: X) throws (StatsError) -> Laplace The maximum-likelihood fit: the median, and the mean absolute deviation from it.
nabilet d = try stats::Laplace::fit([1.0, 2.0, 3.0, 10.0, 4.0]); assert(d.location() == 3.0 && d.scale() == 2.2);
Trait implementations 2
impl Distribution for Laplaceimpl Continuous for Laplace
LogNormalSource
pub struct LogNormalThe log-normal distribution: X = e^Y with Y ~ N(mu, sigma^2)
(SciPy's lognorm(s=sigma, scale=e^mu)).
use stats::{Continuous, LogNormal};
let d = try LogNormal::new(0.0, 1.0);
assert(d.median() == 1.0);
assert((d.mean() - 0.5.exp()).abs() < 1e-15);
Sourcepub fn new(§mu: f64, sigma: f64) throws (StatsError) -> LogNormal The log-normal of N(mu, sigma^2);
mufinite,sigma > 0.The mean of
ln X.The standard deviation of
ln X.
Sourcepub fn fit<X: Sample>(§x: X) throws (StatsError) -> LogNormal The maximum-likelihood fit: the mean and population standard deviation of
ln x. Every value must be positive.nabilet d = try stats::LogNormal::fit([1.0, 10.0, 100.0]); assert((d.mu() - 10.0.ln()).abs() < 1e-15);
Trait implementations 2
impl Distribution for LogNormalimpl Continuous for LogNormal
MultinomialSource
pub struct MultinomialThe multinomial distribution: the counts in each of k categories
after n independent draws with probabilities p. A draw is a
vector of k counts summing to n (conditional binomials).
use stats::Multinomial;
let d = try Multinomial::new(4, [0.5, 0.25, 0.25]);
assert((try d.pmf([2, 1, 1]) - 0.1875).abs() < 1e-16);
assert(d.mean()[0] == 2.0);
Sourcepub fn new<P: Sample>(§n: i64, p: P) throws (StatsError) -> Multinomial Multinomial(n, p):
n >= 0,pnon-negative and summing to 1 within 1e-9 (then rescaled to sum to 1 exactly up to rounding).The number of draws.
The category probabilities.
The number of categories.
Sourcepub fn logpmf<X: Sample>(§self, x: X) throws (StatsError) -> f64 ln P(X = x)for a vector of countsx;-infwhen the counts do not sum ton, are negative or not whole. ThrowsShapeMismatchwhenxhas the wrong length.nabilet d = try stats::Multinomial::new(2, [0.5, 0.5]); assert((try d.logpmf([1, 1]) - 0.5.ln()).abs() < 1e-15);
Sourcepub fn pmf<X: Sample>(§self, x: X) throws (StatsError) -> f64 P(X = x); 0 wherelogpmfis-inf. ThrowsShapeMismatchwhenxhas the wrong length.n p.The covariance
n (diag(p) - p p^T).nabilet d = try stats::Multinomial::new(10, [0.5, 0.5]); assert(d.cov()[0, 0] == 2.5 && d.cov()[0, 1] == -2.5);
Sourcepub fn fit(§x: Matrix<f64>) throws (StatsError) -> Multinomial The maximum-likelihood fit from rows of counts (one observation per row, each summing to the same
n):pis the column sums over the grand total.nabiuse core::array::Matrix; let x: Matrix<f64> = [[1, 2, 1], [3, 0, 1]]; let d = try stats::Multinomial::fit(x); assert(d.trials() == 4 && d.p()[0] == 0.5);
Trait implementations 1
impl Distribution for Multinomial
MultivariateNormalSource
pub struct MultivariateNormalThe multivariate normal distribution with mean mu and covariance
sigma (symmetric positive definite), through its Cholesky factor
sigma = L L^T (linalg): the density by one triangular solve and
ln det sigma = 2 sum ln L_ii, a draw as mu + L z.
use core::array::{Matrix, Vector};
use stats::MultivariateNormal;
let mu: Vector<f64> = [0, 0];
let s: Matrix<f64> = [[2, 1], [1, 2]];
let d = try MultivariateNormal::new(mu, s);
let x: Vector<f64> = [0, 0];
assert((try d.logpdf(x) - (-(2.0 * 3.141592653589793).ln() - 0.5 * 3.0.ln())).abs() < 1e-15);
Sourcepub fn new(§mu: Vector<f64>, sigma: Matrix<f64>) throws (StatsError) -> MultivariateNormal N(mu, sigma). Throws
ShapeMismatchunlesssigmais k x k fork = len(mu),NotFinitefor NaN or infinity,Singularwhensigmais not positive definite.The dimension.
The mean vector.
The covariance matrix.
The Cholesky factor
Lof the covariance.ln det sigma.
Sourcepub fn logpdf(§self, x: Vector<f64>) throws (StatsError) -> f64 The log density at
x:-(k ln 2 pi + ln det sigma + |L^-1 (x - mu)|^2) / 2. ThrowsShapeMismatchfor a wrong length.nabiuse core::array::{Matrix, Vector}; let mu: Vector<f64> = [0]; let s: Matrix<f64> = [[1]]; let d = try stats::MultivariateNormal::new(mu, s); let x: Vector<f64> = [0]; assert((try d.logpdf(x) + 0.9189385332046728).abs() < 1e-15);
Sourcepub fn pdf(§self, x: Vector<f64>) throws (StatsError) -> f64 The density at
x.
Sourcepub fn mahalanobis(§self, x: Vector<f64>) throws (StatsError) -> f64 The squared Mahalanobis distance
(x - mu)^T sigma^-1 (x - mu).nabiuse core::array::{Matrix, Vector}; let mu: Vector<f64> = [0, 0]; let s: Matrix<f64> = [[4, 0], [0, 1]]; let d = try stats::MultivariateNormal::new(mu, s); let x: Vector<f64> = [2, 1]; assert((try d.mahalanobis(x) - 2.0).abs() < 1e-14);ndraws as the rows of an n x k matrix.nabiuse core::array::{Matrix, Vector}; use std::random::Xoshiro256PlusPlus; let mu: Vector<f64> = [1, 2]; let s: Matrix<f64> = [[1, 0.5], [0.5, 1]]; let d = try stats::MultivariateNormal::new(mu, s); let g = Xoshiro256PlusPlus::seed(3); let x = d.sample_rows(ref g, 5000); assert(x.shape() == [5000, 2] && (stats::mean(x[:, 1]) - 2.0).abs() < 0.1);
Sourcepub fn fit(§x: Matrix<f64>) throws (StatsError) -> MultivariateNormal The maximum-likelihood fit from the rows of
x(one observation per row): the column means and the covariance withddof = 0.nabiuse core::array::Matrix; let x: Matrix<f64> = [[1, 2], [3, 3], [2, 7]]; let d = try stats::MultivariateNormal::fit(x); assert(d.mean()[0] == 2.0 && d.mean()[1] == 4.0);
Trait implementations 1
impl Distribution for MultivariateNormal
NegativeBinomialSource
pub struct NegativeBinomialThe negative binomial distribution: the number of failures before
the r-th success in trials of probability p (SciPy's nbinom;
r > 0 need not be an integer). `P(X = k) = C(k + r - 1, k) p^r (1
- p)^k
, CDFI_p(r, k + 1)`; draws as Poisson(Gamma(r, (1 - p) / p)).
use stats::{Discrete, NegativeBinomial};
let d = try NegativeBinomial::new(3.0, 0.5);
assert((d.pmf(2) - 0.1875).abs() < 1e-16 && d.mean() == 3.0);
Sourcepub fn new(§r: f64, p: f64) throws (StatsError) -> NegativeBinomial NegativeBinomial(r, p),
r > 0finite,0 < p <= 1.The number of successes.
The success probability.
Trait implementations 2
impl Distribution for NegativeBinomialimpl Discrete for NegativeBinomial
NormalSource
pub struct NormalThe normal (Gaussian) distribution with mean mu and standard
deviation sigma > 0. CDF and quantile through ndtr / ndtri,
so both tails keep full relative accuracy; draws by the ziggurat.
use stats::{Continuous, Normal};
let d = try Normal::new(100.0, 15.0);
assert((d.cdf(130.0) - 0.9772498680518208).abs() < 1e-15);
assert((d.ppf(0.5) - 100.0).abs() < 1e-12);
Sourcepub fn new(§mu: f64, sigma: f64) throws (StatsError) -> Normal N(mu, sigma^2); throws
InvalidParameterunlessmuis finite andsigmafinite and positive.N(0, 1).
The mean parameter.
The standard deviation parameter.
Sourcepub fn fit<X: Sample>(§x: X) throws (StatsError) -> Normal The maximum-likelihood fit: the mean and the population standard deviation (
ddof = 0). ThrowsTooFewbelow 2 values,NotFinitefor NaN or infinity,InvalidParameterfor constant data.nabilet d = try stats::Normal::fit([1.0, 2.0, 3.0, 4.0]); assert(d.mu() == 2.5 && (d.sigma() - 1.25.sqrt()).abs() < 1e-15);
Trait implementations 2
impl Distribution for Normalimpl Continuous for Normal
PoissonSource
pub struct PoissonThe Poisson distribution with mean lambda >= 0. PMF lambda^k e^-lambda / k! through the incomplete gamma function's factor, CDF
Q(k + 1, lambda); draws by search below 10 and PTRS above.
use stats::{Discrete, Poisson};
let d = try Poisson::new(4.0);
assert((d.pmf(2) - 8.0 * (-4.0).exp()).abs() < 1e-16);
assert(d.ppf(0.5) == 4);
Sourcepub fn new(§lambda: f64) throws (StatsError) -> Poisson Poisson(lambda),
lambdafinite and >= 0.The mean.
Sourcepub fn fit<X: Sample>(§x: X) throws (StatsError) -> Poisson The maximum-likelihood fit: the mean of the counts.
nabiassert((try stats::Poisson::fit([1, 2, 6])).lambda() == 3.0);
Trait implementations 2
impl Distribution for Poissonimpl Discrete for Poisson
StudentTSource
pub struct StudentTStudent's t distribution with nu > 0 degrees of freedom (not
necessarily an integer). The CDF is I_x(nu / 2, 1 / 2) with x = nu / (nu + t^2), both x and 1 - x formed directly so neither
tail cancels; the quantile inverts it, with the closed forms for
nu = 1 and 2.
use stats::{Continuous, StudentT};
let d = try StudentT::new(10.0);
// mpmath: 2.22813885198627475; SciPy 1.13 gives 2.2281388519649385.
// A few ulps either way: the platform's libm differs (Windows' UCRT).
assert((d.ppf(0.975) - 2.2281388519862747).abs() < 4e-15);
assert((d.cdf(-2.0) - 0.036694017385370196).abs() < 1e-16);
Sourcepub fn new(§nu: f64) throws (StatsError) -> StudentT Student's t with
nudegrees of freedom (> 0;infis not allowed: useNormal::standard()).The degrees of freedom.
Trait implementations 2
impl Distribution for StudentTimpl Continuous for StudentT
UniformSource
pub struct UniformThe uniform distribution on [a, b], a < b.
use stats::{Continuous, Uniform};
let d = try Uniform::new(2.0, 6.0);
assert(d.cdf(3.0) == 0.25 && d.ppf(0.75) == 5.0 && d.var() == 16.0 / 12.0);
Sourcepub fn new(§a: f64, b: f64) throws (StatsError) -> Uniform The uniform distribution on
[a, b]; both finite,a < b.The lower end.
The upper end.
Sourcepub fn fit<X: Sample>(§x: X) throws (StatsError) -> Uniform The maximum-likelihood fit
[min(x), max(x)].nabilet d = try stats::Uniform::fit([0.5, 0.2, 0.9]); assert(d.a() == 0.2 && d.b() == 0.9);
Trait implementations 2
impl Distribution for Uniformimpl Continuous for Uniform
WeibullSource
pub struct WeibullThe Weibull distribution with shape k > 0 and scale lambda > 0:
P(X > x) = e^(-(x / lambda)^k) (SciPy's weibull_min).
use stats::{Continuous, Weibull};
let d = try Weibull::new(2.0, 1.0);
assert((d.sf(1.0) - (-1.0).exp()).abs() < 1e-16);
assert((d.mean() - 0.8862269254527579).abs() < 1e-15);
Sourcepub fn new(§k: f64, lambda: f64) throws (StatsError) -> Weibull Weibull(k, lambda); both finite and positive.
The shape.
The scale.
Trait implementations 2
impl Distribution for Weibullimpl Continuous for Weibull
IidSource
pub struct Iid<D>n independent copies of d: a draw is d.samples(g, n).
use stats::{Distribution, Poisson};
use std::random::Xoshiro256PlusPlus;
let g = Xoshiro256PlusPlus::seed(1);
let ks = (try Poisson::new(3.0)).iid(5).sample(ref g);
assert(ks.len() == 5);
The distribution of each draw.
The number of draws.
Trait implementations 1
impl<D: Distribution> Distribution for Iid<D>
Traits
DistributionSource
pub trait DistributionSomething to draw random values from. Value is f64 for the
continuous distributions, i64 for the discrete ones and a vector
for the multivariate ones. Draws depend only on the generator's
state, so a seeded Xoshiro256PlusPlus repeats them on every
target.
use stats::{Distribution, Normal};
use std::random::Xoshiro256PlusPlus;
let g = Xoshiro256PlusPlus::seed(7);
let d = try Normal::new(10.0, 2.0);
let x = d.sample(ref g);
let xs = d.samples(ref g, 1000);
assert(xs.len() == 1000 && (stats::mean(xs) - 10.0).abs() < 0.3);
The type of one draw.
One draw, advancing
g.nindependent draws.nindependent copies as one distribution, whose draw is a vector ofn(forg ~ d.iid(n)).
ContinuousSource
pub trait Continuous: Distribution<Value = f64>A distribution on the real line with a density.
use stats::{Continuous, Normal};
let d = Normal::standard();
assert(d.cdf(0.0) == 0.5);
assert((d.ppf(d.cdf(1.3)) - 1.3).abs() < 1e-15);
let i = d.interval(95pct);
assert((i.hi - 1.959963984540054).abs() < 1e-15);
The density at
x.ln pdf(x), without underflow far in the tails.P(X <= x).The survival function
P(X > x), accurate where it is small.The quantile: the
xwithcdf(x) = p,0 <= p <= 1(NaN otherwise).The
xwithsf(x) = q, accurate for smallq.The mean (NaN when it does not exist, as for Cauchy).
The variance (NaN or infinity when it does not exist).
The standard deviation.
The median,
ppf(0.5).The central interval holding probability
level:[ppf((1 - level) / 2), isf((1 - level) / 2)].
DiscreteSource
pub trait Discrete: Distribution<Value = i64>A distribution on the integers.
use stats::{Discrete, Binomial};
let d = try Binomial::new(10, 0.5);
assert((d.pmf(5) - 0.24609375).abs() < 1e-15);
assert(d.ppf(0.5) == 5);
P(X = k).ln pmf(k).P(X <= k).P(X > k), accurate where it is small.The smallest
kwithcdf(k) >= p,0 <= p <= 1;i64::MINfor apoutside it.The mean.
The variance.
The standard deviation.