stats
On this page
Statistics on core's Array and List.
stats covers what a first statistics course does and a good part of
what comes after: summaries, probability distributions, random samples,
hypothesis tests, regression and the bootstrap. Each function takes any
sequence of numbers (a Vector<f64>, a List, a fixed array, a range),
and the results are plain structs whose fields you read by name.
#Tutorial
#Summaries
mean, median, var, std, quantile and the rest take the data
and return a number. Descriptive statistics never throw: an empty input
gives NaN, as in NumPy. stats::nan:: has the same functions skipping
NaN values.
let x = [5.1, 4.9, 5.6, 5.8, 6.0, 5.4, 5.2, 5.7];
println(f"mean {stats::mean(x):.4}, median {stats::median(x):.2}");
println(f"var {stats::var(x, ddof: 1):.4}, std {stats::std(x, ddof: 1):.4}");
println(f"90th percentile {(try stats::quantile(x, 0.9)):.3}");
println(f"skew {stats::skew(x):.3}");
let gaps = [1.0, f64::NAN, 3.0];
println(f"{stats::mean(gaps)} {stats::nan::mean(gaps)}");
mean 5.4625, median 5.50
var 0.1427, std 0.3777
90th percentile 5.860
skew -0.097
NaN 2
quantile interpolates as NumPy does by default; the method: argument
picks any of the Hyndman and Fan definitions when a field expects
another.
#Distributions
A distribution is a value: Normal::new(100.0, 15.0) is the normal with
mean 100 and standard deviation 15. Continuous distributions have pdf,
cdf, sf (one minus the cdf, accurate in the tail), ppf (the
inverse cdf) and interval; discrete ones have pmf instead of pdf.
use stats::{Binomial, Continuous, Discrete, Normal};
let iq = try Normal::new(100.0, 15.0);
println(f"P(IQ > 130) = {iq.sf:.4}");
println(f"middle 95%: {iq.interval}");
println(f"97.5th percentile {iq.ppf:.2}");
let coin = try Binomial::new(10, 0.5);
println(f"P(7 heads of 10) = {coin.pmf(7):.4}, P(at most 7) = {coin.cdf(7):.4}");
P(IQ > 130) = 0.0228
middle 95%: [70.6005402318992, 129.3994597681008]
97.5th percentile 129.40
P(7 heads of 10) = 0.1172, P(at most 7) = 0.9453
#Random samples
A Sampler is a seeded random number generator: the same seed gives the
same draws on every machine, which makes a simulation repeatable.
d.samples(ref g, n) draws n values from d.
use stats::{Continuous, Distribution, Normal, Sampler};
let g = Sampler::seed(7);
let d = try Normal::new(10.0, 2.0);
let xs = d.samples(ref g, 10000);
println(f"{xs.len()} draws: mean {stats::mean(xs):.2}, std {stats::std(xs, ddof: 1):.2}");
let fitted = try Normal::fit(xs);
println(f"fitted mean {fitted.mean():.2}");
10000 draws: mean 10.00, std 1.99
fitted mean 10.00
fit estimates a distribution's parameters by maximum likelihood; most
distributions in the package have one.
#Hypothesis tests
A test returns its statistic and p-value. The t-tests also return the
estimate and its standard error, so the confidence interval is one more
call (ci). Here a drug trial: did the treated group's blood pressure
fall more than the control group's?
let control = [-2.1, 0.5, -1.0, 1.3, -0.4, 0.8, -1.7, 0.2, -0.6, 1.1];
let treated = [-6.3, -4.1, -7.5, -2.9, -5.2, -3.8, -6.9, -4.4, -5.8, -3.1];
let t = try stats::ttest_ind(treated, control);
println(f"difference {t.estimate:.2} mmHg, 95% interval {t.ci}");
println(f"p = {t.pvalue:.2e}, significant at 1%: {t.result().rejects}");
// Are the treated values plausibly normal? Shapiro-Wilk.
let sw = try stats::shapiro(treated);
println(f"Shapiro-Wilk p = {sw.pvalue:.3}");
// The same question without assuming normality.
let u = try stats::mannwhitneyu(treated, control);
println(f"Mann-Whitney p = {u.pvalue:.2e}");
difference -4.81 mmHg, 95% interval [-6.131505142918329, -3.48849485708167]
p = 7.45e-7, significant at 1%: true
Shapiro-Wilk p = 0.696
Mann-Whitney p = 1.83e-4
The package also has paired and one-sample t-tests, chi-squared tests of
fit and of contingency tables, Fisher's exact test, Kolmogorov-Smirnov,
Wilcoxon, one-way ANOVA (f_oneway) and the correlation tests. Each
takes alternative: for a one-sided test.
#Regression
stats::ols fits y = b0 + b1 x1 + ... by least squares and reports
what a regression table does: coefficients, standard errors, t
statistics, p-values, R². Each row of x is one observation, each
column one predictor; the intercept is added for you.
use core::array::{Matrix, Vector};
// Fuel use (l/100 km) against mass (tonnes) and engine size (litres).
let x: Matrix<f64> = [[1.1, 1.2], [1.3, 1.4], [1.4, 1.6], [1.5, 2.0], [1.7, 2.0], [1.8, 2.5], [2.0, 3.0], [2.2, 3.0]];
let y: Vector<f64> = [5.2, 5.9, 6.3, 7.1, 7.4, 8.3, 9.2, 9.6];
let fit = try stats::ols(x, y);
for (k, name) in ["intercept", "mass", "engine"].enumerate() {
println(f"{name:>9}: {fit.coef[k]:>6.3} (se {fit.se[k]:.3}, p {fit.p[k]:.3})");
}
println(f"R^2 {fit.r2:.4}");
let next: Matrix<f64> = [[1.6, 1.8]];
println(f"predicted for a 1.6 t car with a 1.8 l engine: {(try fit.predict(next))[0]:.2}");
intercept: 1.684 (se 0.155, p 0.000)
mass: 1.807 (se 0.259, p 0.001)
engine: 1.319 (se 0.138, p 0.000)
R^2 0.9991
predicted for a 1.6 t car with a 1.8 l engine: 6.95
stats::logistic fits a logistic regression for a yes/no outcome, and
stats::polyfit a polynomial in one variable.
#The bootstrap
When no formula gives the uncertainty of a statistic, the bootstrap
estimates it by recomputing the statistic on many resamples of the data.
stats::bootstrap takes the data and the statistic as a function and
returns the estimate, its standard error and a confidence interval (BCa
by default).
use core::array::Vector;
let incomes = [21.0, 23.5, 25.0, 26.0, 28.5, 30.0, 31.0, 34.0, 38.0, 45.0, 60.0, 120.0];
let b = try stats::bootstrap(incomes, |v: Vector<f64>| -> f64 { stats::median(v) }, resamples: 2000, seed: 1);
println(f"median {b.estimate}, se {b.se:.2}, 95% interval {b.ci}");
median 30.5, se 4.09, 95% interval [25, 38]
#Notation
With the ops feature (on by default) some of this reads like a
statistics text: 95pct is the number 0.95, m ± h is an interval, and
g ~ d draws from d.
use stats::{Distribution, Normal, Sampler};
let g = Sampler::seed(42);
let xs = g ~ (try Normal::new(10.0, 2.0)).iid(1000);
let ci = stats::mean(xs) ± 1.96 * stats::sem(xs);
println(f"{ci} contains 10: {10.0 in ci}");
println(95pct);
[9.886659540274959, 10.129771738653204] contains 10: true
0.95
#What next
- Signals and spectra: FFT and filters.
- The modules below list every distribution, test and option.
Modules
axisStatistics along one axis of an array: each lane alongaxisis reduced to one value, giving an array of one rank less (NumPy'saxis=argument).descriptiveDescriptive statistics of one set of values: location, spread and shape.distProbability distributions as types.hypothesisHypothesis tests.nanNaN-aware statistics: the same as the plain ones on the values that are not NaN (NumPy'snanmean, ...).opsNotation for statistics (featureops, on by default): g ~ d a draw from distribution d with the Sampler g; with d.iid(n), n draws ("distributed as", level of==) y ~ x the least-squares fit of y on x with an intercept, as R'slm(y ~ x); a Result, since operators cannot throw m ± h the interval [m - h, m + h] (level of+) 95pct the number 0.95, for confidence levels~has a second spelling,∼(U+223C TILDE OPERATOR).regressRegression: ordinary and weighted least squares with inference, polynomial fits and logistic regression.specialThe special functions behind the distributions, from thespecialpackage.
Re-exports
descriptive::order::{QuantileMethod, iqr, max, median, min, mode, percentile, quantile, quantiles, range}Source
pub use descriptive::order::{QuantileMethod, iqr, max, median, min, mode, percentile, quantile, quantiles, range}QuantileMethodHow a quantile between two order statistics is chosen.iqrThe interquartile rangeq(0.75) - q(0.25)(type 7).maxThe largest value; NaN when empty or a value is NaN.medianThe median (the mean of the middle two for an even count); NaN when empty or a value is NaN.minThe smallest value; NaN when empty or a value is NaN.modeThe most frequent value and its count; the smallest of several equally frequent ones (SciPy'smode).percentileThep-th percentile,0 <= p <= 100:quantile(x, p / 100).quantileTheq-quantile,0 <= q <= 1, bymethod(defaultLinear).quantilesThe quantiles at each ofqs, by one sort (O(n log n)).rangemax - min(NumPy'sptp); NaN when empty or a value is NaN.
descriptive::{Summary, describe, kurtosis, mean, moment, sem, skew, std, sum, var, wmean, zscore}Source
pub use descriptive::{Summary, describe, kurtosis, mean, moment, sem, skew, std, sum, var, wmean, zscore}SummaryA summary of a set of values: count, mean, spread, quartiles and shape.describeTheSummaryof the values: one copy and a sort.kurtosisThe kurtosism4 / m2^2, minus 3 by default (fisher: true, the excess kurtosis, 0 for a normal sample in the limit); withbias: falsethe unbiased estimatorG2of the k-statistics (SciPy'skurtosis).meanThe arithmetic mean, by pairwise summation (O(n)); NaN when empty.momentThek-th central momentsum((x - mean)^k) / n(1 gives 0, 2 the population variance); NaN when empty.semThe standard error of the mean,std(x, ddof) / sqrt(n), withddof = 1by default (SciPy'ssem).skewThe skewnessm3 / m2^1.5of the central moments; withbias: falsethe adjusted Fisher-Pearson coefficientG1 = g1 sqrt(n (n - 1)) / (n - 2)(SciPy'sskew).stdThe standard deviation,sqrt(var(x, ddof)).sumThe sum of the values, by pairwise summation (O(n), error O(eps log n) of the sum of magnitudes); 0 when empty.varThe variancesum((x - mean)^2) / (n - ddof)(corrected two-pass, Chan, Golub and LeVeque 1983).wmeanThe weighted meansum(w x) / sum(w).zscoreThe z-scores(x - mean) / std(x, ddof)of every element, in the shape ofa.
dist::{Bernoulli, Beta, Binomial, Cauchy, ChiSquared, Continuous, Discrete, Distribution, Exponential, FisherF, Gamma, Geometric, Iid, Laplace, LogNormal, Multinomial, MultivariateNormal, NegativeBinomial, Normal, Poisson, StudentT, Uniform, Weibull}Source
pub use dist::{Bernoulli, Beta, Binomial, Cauchy, ChiSquared, Continuous, Discrete, Distribution, Exponential, FisherF, Gamma, Geometric, Iid, Laplace, LogNormal, Multinomial, MultivariateNormal, NegativeBinomial, Normal, Poisson, StudentT, Uniform, Weibull}BernoulliThe Bernoulli distribution: 1 with probabilityp, else 0.BetaThe beta distribution with shapesa, b > 0on [0, 1].BinomialThe binomial distribution: the number of successes inn >= 0independent trials of probabilityp.CauchyThe Cauchy (Lorentz) distribution with locationx0and scalegamma > 0: Student's t with one degree of freedom, shifted and scaled.ChiSquaredThe chi-squared distribution withk > 0degrees of freedom (Gamma(k / 2, 2));kneed not be an integer.ContinuousA distribution on the real line with a density.DiscreteA distribution on the integers.DistributionSomething to draw random values from.ExponentialThe exponential distribution with ratelambda > 0(mean1 / lambda; SciPy'sexpon(scale=1/lambda)).FisherFThe F distribution withd1, d2 > 0degrees of freedom: the ratio of two scaled chi-squared variables.GammaThe gamma distribution with shapek > 0and scaletheta > 0(meank theta).GeometricThe geometric distribution on 1, 2, 3, ...: the number of trials of probabilitypup to and including the first success (SciPy'sgeom).Iidnindependent copies ofd: a draw isd.samples(g, n).LaplaceThe Laplace distribution with locationmuand scaleb > 0: densitye^(-|x - mu| / b) / (2 b).LogNormalThe log-normal distribution:X = e^YwithY ~ N(mu, sigma^2)(SciPy'slognorm(s=sigma, scale=e^mu)).MultinomialThe multinomial distribution: the counts in each ofkcategories afternindependent draws with probabilitiesp.MultivariateNormalThe multivariate normal distribution with meanmuand covariancesigma(symmetric positive definite), through its Cholesky factorsigma = L L^T(linalg): the density by one triangular solve andln det sigma = 2 sum ln L_ii, a draw asmu + L z.NegativeBinomialThe negative binomial distribution: the number of failures before ther-th success in trials of probabilityp(SciPy'snbinom;r > 0need not be an integer).NormalThe normal (Gaussian) distribution with meanmuand standard deviationsigma > 0.PoissonThe Poisson distribution with meanlambda >= 0.StudentTStudent's t distribution withnu > 0degrees of freedom (not necessarily an integer).UniformThe uniform distribution on[a, b],a < b.WeibullThe Weibull distribution with shapek > 0and scalelambda > 0:P(X > x) = e^(-(x / lambda)^k)(SciPy'sweibull_min).
hypothesis::{Alternative, Anova, Contingency, TTest, TestResult, chi2_contingency, chisquare, f_oneway, fisher_exact, kendalltau, ks_2samp, kstest, mannwhitneyu, pearsonr, shapiro, spearmanr, ttest_1samp, ttest_ind, ttest_rel, wilcoxon}Source
pub use hypothesis::{Alternative, Anova, Contingency, TTest, TestResult, chi2_contingency, chisquare, f_oneway, fisher_exact, kendalltau, ks_2samp, kstest, mannwhitneyu, pearsonr, shapiro, spearmanr, ttest_1samp, ttest_ind, ttest_rel, wilcoxon}AlternativeWhich way the alternative hypothesis points.AnovaThe outcome of a one-way ANOVA:F, its p-value and the two degrees of freedom.ContingencyThe chi-squared test of independence in a contingency table: its statistic, p-value, degrees of freedom(r - 1)(c - 1)and the expected counts under independence.TTestThe outcome of a t-test: the t statistic, its p-value and degrees of freedom, the estimate (a mean or a difference of means) and its standard error, from whichcigives a confidence interval.TestResultThe outcome of a test: the statistic, its p-value and, for tests with a t, chi-squared or similar reference distribution, the degrees of freedom.chi2_contingencyPearson's chi-squared test of independence of the rows and columns of a table of counts.chisquarePearson's goodness-of-fit test of observed counts against expected ones:sum((o - e)^2 / e)onk - 1 - ddofdegrees of freedom.f_onewayThe one-way ANOVA F-test thatk >= 2groups share one mean (SciPy'sf_oneway).fisher_exactFisher's exact test of independence in a 2 x 2 table[[a, b], [c, d]]: with the margins fixed,ais hypergeometric.kendalltauKendall's tau-b and the p-value oftau = 0: exact (the distribution of inversions of a random permutation) for up to 33 pairs without ties, else the normal approximation with the tie-corrected variance of Kendall (1970) (SciPy'skendalltau).ks_2sampThe two-sample Kolmogorov-Smirnov test thatxandycome from one distribution.kstestThe one-sample Kolmogorov-Smirnov test ofxagainst the continuous distributiond.mannwhitneyuThe Mann-Whitney U test thatxandycome from one distribution against a shift (SciPy'smannwhitneyu).pearsonrPearson's r and the p-value ofr = 0for normal data (the t-test onn - 2degrees of freedom; SciPy'spearsonr).shapiroThe Shapiro-Wilk test thatxcomes from a normal distribution,3 <= n <= 5000.spearmanrSpearman's rho and the p-value ofrho = 0by the same t approximation (SciPy'sspearmanr).ttest_1sampThe one-sample t-test ofmean(x) = popmean:t = (mean - popmean) / (s / sqrt(n))onn - 1degrees of freedom.ttest_indThe two-sample t-test of equal means.ttest_relThe paired t-test: the one-sample test of the differencesx - yagainst 0.wilcoxonThe Wilcoxon signed-rank test that the valuesxare symmetric about 0, or withythat the differencesx - yof paired samples are.
regress::{Logistic, Ols, logistic, ols, polyfit, polyval, wls}Source
pub use regress::{Logistic, Ols, logistic, ols, polyfit, polyval, wls}LogisticA fitted logistic regressionP(y = 1 | x) = 1 / (1 + e^-(x b)).OlsA fitted linear modely = X b + e: coefficients, their standard errors, t statistics and p-values, the fit's R^2, the residuals.logisticLogistic regression of 0/1 outcomesyon the columns ofxby Newton's method in its IRLS form (McCullagh and Nelder 1989): each step solvesX^T W X d = X^T (y - mu)by Cholesky (linalg), from b = 0, until no coefficient moves more thantol(relative) ormax_itersteps.olsOrdinary least squaresy = X b + eby Householder QR (linalg): coefficients fromR b = Q^T y, covariancesigma^2 R^-1 R^-T, soX^T Xis never formed.polyfitThe least-squares polynomial of degreedegthrough the points(x, y): coefficients rising, `c[0] + c[1] x + ...polyvalThe polynomial with rising coefficientscat each element ofx(Horner's rule), in the shape ofx.wlsWeighted least squares: minimizessum w_i (y_i - x_i b)^2(OLS on rows scaled bysqrt(w)), with weights>= 0, e.g.
Structs
ValuesSource
pub struct ValuesA contiguous copy of some data as f64, in row-major order: what
Sample::values gives.
use stats::Sample;
let v = [3.0, 1.0].values();
assert(v.len() == 2 && v.to_vector()[0] == 3.0);
The number of values.
nabiuse stats::Sample; assert([1.0, 2.0, 3.0].values().len() == 3);Whether there are none.
The values as a new rank-1 array.
nabiuse stats::Sample; let v = [1, 2].values().to_vector(); assert(v[1] == 2.0);
Trait implementations 1
impl Sample for Values
HistogramSource
pub struct HistogramCounts of values in bins: counts[i] values fell in [edges[i], edges[i + 1]), the last bin closed on the right.
The number of values in each bin.
The
len(counts) + 1bin edges, rising.The number of bins.
The density in each bin:
count / (total * width), which integrates to 1 over the range.nabilet h = try stats::histogram([1.0, 2.0, 3.0, 4.0], stats::Bins::Count(2)); assert(h.density()[0] == 1.0 / 3.0);The midpoints of the bins.
nabilet h = try stats::histogram([0.0, 1.0, 2.0, 4.0], stats::Bins::Count(2)); assert(h.centers().to_list() == [1.0, 3.0]);
IntervalSource
pub struct IntervalThe closed interval [lo, hi]. x in i (or x ∈ i) tests
membership.
use stats::Interval;
let i = Interval { lo: 1.0, hi: 3.0 };
assert(2.0 in i && !(4.0 in i));
assert(i.mid() == 2.0 && i.width() == 2.0);
assert(f"{i}" == "[1, 3]");
The lower end.
The upper end.
[mid - half, mid + half].nabiassert(stats::Interval::around(5.0, 1.5).lo == 3.5);hi - lo.nabiassert(stats::Interval { lo: 1.0, hi: 4.0 }.width() == 3.0);The midpoint.
nabiassert(stats::Interval { lo: 1.0, hi: 4.0 }.mid() == 2.5);
Trait implementations 2
impl ops::Contains<f64> for Intervalimpl Display for Interval
BootstrapSource
pub struct BootstrapThe outcome of bootstrap.
The statistic of the sample itself.
The standard deviation of the replicates (
ddof = 1).mean(replicates) - estimate.The confidence interval.
The statistic of each resample.
SamplerSource
pub struct SamplerA seeded Xoshiro256++ generator for g ~ d, which advances g as
d.sample(ref g) does. It is an Rng, so the method forms take it
too. A copy continues the same stream on its own.
use stats::{Distribution, Normal, Sampler};
let g = Sampler::seed(42);
let a = Normal::standard().sample(ref g);
let b = Normal::standard().sample(ref g);
assert(a != b);
The stream of
Xoshiro256PlusPlus::seed(seed).nabiuse std::random::Rng; let a = stats::Sampler::seed(1); let b = stats::Sampler::seed(1); assert(a.next_u64() == b.next_u64());A stream seeded from the operating system.
Trait implementations 1
impl Rng for Sampler
Enums
CorrMethodSource
pub enum CorrMethodHow corr measures association.
Pearson's r (linear).
Spearman's rho (monotone, on ranks).
Kendall's tau-b (concordance of pairs).
TiesSource
pub enum TiesHow rankdata ranks equal values (SciPy's method).
use stats::Ties;
let x = [10.0, 20.0, 10.0, 30.0];
assert(stats::rankdata(x)[0] == 1.5);
assert(stats::rankdata(x, Ties::Min)[2] == 1.0);
assert(stats::rankdata(x, Ties::Dense)[3] == 3.0);
The mean of the ranks the group spans (the default).
The lowest rank of the group.
The highest rank of the group.
Ranks 1, 2, 3, ... over the distinct values.
Distinct ranks in order of appearance.
StatsErrorSource
pub enum StatsErrorWhat went wrong in a statistics call.
use stats::StatsError;
let e = try {
_ = try stats::Normal::new(0.0, -1.0);
StatsError::NotFinite { what: "" }
} catch e: StatsError { e };
assert(f"{e}".contains("sigma"));
Fewer values than the statistic needs:
needofwhat,gotgiven.A distribution parameter out of its range;
whatnames it and the range.An argument out of its range (a probability above 1, an axis past the rank, a negative weight);
whatsays which.Operands whose lengths or shapes do not fit;
whatnames both.The input holds NaN or an infinity where the method cannot take one.
A design matrix without full column rank (collinear columns), or a singular covariance.
An iteration did not converge in
iterationssteps.
Trait implementations 2
impl Display for StatsErrorimpl Error for StatsError
BinsSource
pub enum BinsHow histogram and bin_edges choose the bins. The rules are
NumPy's, with the same results: each gives a bin width, and the
range is cut into ceil(range / width) equal bins.
use stats::Bins;
let x = [1.0, 2.0, 2.0, 3.0, 4.0];
assert((try stats::bin_edges(x, Bins::Count(3))).len() == 4);
assert((try stats::histogram(x, Bins::Width(1.0))).counts[1] == 2);
This many equal bins over the data's range.
Bins of this width from the minimum.
These edges, rising (bins
[e0, e1), ..., [e_n-1, e_n]).The smaller width of
SturgesandFd(NumPy's default estimator"auto").range / (log2(n) + 1): for small, roughly normal data.Scott (1979):
(24 sqrt(pi) / n)^(1/3) * std.Freedman and Diaconis (1981):
2 iqr / n^(1/3); robust to outliers.range / sqrt(n).range / (2 n^(1/3)).Doane (1976): Sturges corrected for skewness.
BootMethodSource
pub enum BootMethodHow bootstrap turns the replicates into an interval.
The quantiles of the replicates.
The percentile interval reflected about the estimate (
2 theta - q), the "basic" bootstrap.Bias-corrected and accelerated (Efron 1987): the percentile interval shifted by the median bias of the replicates and scaled by the jackknife acceleration. Second-order accurate; the default.
Traits
SampleSource
pub trait SampleThe data a statistic reads: List<T> and Array<T, N> of any rank
for T in f64, f32, i64, i32 and usize, fixed arrays and i64
ranges (what linalg::AsVector<f64> takes, plus any rank). Values
are taken in row-major order and converted to f64.
use core::array::Matrix;
let m: Matrix<f64> = [[1, 2], [3, 4]];
assert(stats::mean(m) == 2.5);
assert(stats::mean([1, 2, 3, 6]) == 3.0);
assert(stats::mean([1.5f32, 2.5f32]) == 2.0);
assert(stats::mean(1..5) == 2.5);
The values as a contiguous f64 copy.
Functions
corrSource
pub fn corr(x: Matrix<f64>, method: CorrMethod = CorrMethod::Pearson) throws (StatsError) -> Matrix<f64> The correlation matrix of the columns of x by method (default
Pearson). The diagonal is 1 (NaN for a constant column).
use core::array::Matrix;
use stats::CorrMethod;
let x: Matrix<f64> = [[1, 1], [2, 4], [3, 9], [4, 16]];
assert((try stats::corr(x, CorrMethod::Spearman))[0, 1] == 1.0);
covSource
pub fn cov(x: Matrix<f64>, ddof: usize = 1) throws (StatsError) -> Matrix<f64> The covariance matrix of the columns of x (rows are observations,
as pandas' DataFrame.cov; NumPy's cov(x, rowvar=False)),
dividing by n - ddof (default 1, the unbiased estimate). The
columns are centered by their means (two-pass), then Xc^T Xc is
one linalg product. O(n p^2). Throws TooFew when n <= ddof.
use core::array::Matrix;
let x: Matrix<f64> = [[1, 2], [2, 4], [3, 7]];
let c = try stats::cov(x);
assert(c[0, 0] == 1.0 && c[0, 1] == 2.5 && c[1, 1] == 6.333333333333333);
kendallSource
pub fn kendall<X: Sample, Y: Sample>(x: X, y: Y) throws (StatsError) -> f64 Kendall's tau-b: (concordant - discordant) / sqrt((n0 - n1) (n0 - n2)), which corrects for ties in either sample. Knight's
algorithm, O(n log n).
let t = try stats::kendall([12.0, 2.0, 1.0, 12.0, 2.0], [1.0, 4.0, 7.0, 1.0, 0.0]);
assert((t + 0.4714045207910316).abs() < 1e-15);
pearsonSource
pub fn pearson<X: Sample, Y: Sample>(x: X, y: Y) throws (StatsError) -> f64 Pearson's correlation coefficient. NaN when either sample is
constant. Throws ShapeMismatch for unequal lengths, TooFew
below 2 pairs.
assert(try stats::pearson([1.0, 2.0, 3.0], [2.0, 4.0, 6.5]) > 0.99);
assert(try stats::pearson([1.0, 2.0, 3.0], [3.0, 2.0, 1.0]) == -1.0);
rankdataSource
pub fn rankdata<X: Sample>(x: X, ties: Ties = Ties::Average) -> Vector<f64> The ranks of the values, 1 for the smallest, ties by ties
(default Average, the mid-rank). O(n log n). SciPy: rankdata.
let r = stats::rankdata([3.0, 1.0, 2.0]);
assert(r[0] == 3.0 && r[1] == 1.0);
spearmanSource
pub fn spearman<X: Sample, Y: Sample>(x: X, y: Y) throws (StatsError) -> f64 Spearman's rank correlation: Pearson's r of the mid-ranks.
assert(try stats::spearman([1.0, 2.0, 3.0, 4.0], [1.0, 4.0, 9.0, 16.0]) == 1.0);
bin_edgesSource
pub fn bin_edges<X: Sample>(x: X, bins: Bins = Bins::Auto) throws (StatsError) -> Vector<f64> The bin edges histogram would use for x (NaN and infinities
ignored). Throws InvalidArgument for an empty count, a width that
is not positive, or edges that do not rise.
let e = try stats::bin_edges([0.0, 1.0, 2.0, 3.0, 4.0], stats::Bins::Sturges);
assert(e.len() == 5 && e[0] == 0.0 && e[4] == 4.0);
histogramSource
pub fn histogram<X: Sample>(x: X, bins: Bins = Bins::Auto) throws (StatsError) -> Histogram The histogram of x over bins (default Auto): values outside
the edges and NaN are not counted; the last bin includes its right
edge. Bins of equal width are found by arithmetic, explicit edges
by binary search. O(n log bins).
use core::array::Array;
let h = try stats::histogram([1.0, 2.0, 2.0, 3.0, 4.0], stats::Bins::Count(3));
assert(h.counts == Array::<i64, 1>::from([1, 2, 2]));
bootstrapSource
pub fn bootstrap<X: Sample>(x: X, stat: fn(Vector<f64>) -> f64, resamples: usize = 9999, level: f64 = 0.95, method: BootMethod = BootMethod::Bca, seed: u64 = 0) throws (StatsError) -> Bootstrap A bootstrap confidence interval at level for stat of the sample
x: resamples resamples with replacement drawn from a
Xoshiro256++ stream seeded with seed (so the result repeats), the
interval by method (default BCa, which also evaluates stat on the
n leave-one-out samples). Throws TooFew below 2 values,
InvalidArgument for a level outside (0, 1) or fewer than 2
resamples.
use core::array::Vector;
let x = [2.1, 3.4, 1.9, 5.6, 4.4, 3.3, 2.8, 4.1, 3.9, 2.5];
let b = try stats::bootstrap(x, |v: Vector<f64>| -> f64 { stats::mean(v) }, 2000, 95pct);
assert(b.estimate in b.ci && b.ci.lo > 2.5 && b.ci.hi < 4.3);