RiptideRiptide
Download Riptide SDKInstall Riptorch
Menu
Raya docs · Numerical computing

Statistics and random numbers

Counter-based Philox and Threefry generators that give the same bits on the CPU and the GPU, distributions with pdf, cdf and ppf, descriptive statistics, regression, PCA and k-means.

import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
22 classes142 functions and methods70 of 211 documented127 runnable examplesWhat scipy.stats does

Overview

Statistics and random numbers, over Float64List (matrices row-major, the layout of a 2-D NDArray; Pca.fitArray takes one directly).

Counter-based random numbers, identical on CPU and GPU

Philox4x32 (Philox4x32-10) and Threefry2x32 (Threefry2x32-20) are the Random123 generators (Salmon, Moraes, Dror and Shaw, SC'11): a counter and a key go in, random words come out, with no state. Every step is a 32-bit add, xor, rotate or a 32 \times 32 \to 64 multiply, so a GLSL kernel with umulExtended (or the 16-bit split multiply that Philox4x32.mulhilo16 mirrors) produces the same words bit for bit; riptide_numerics_gpu's Philox kernel is checked against this on Metal. Verified against Random123's known-answer vectors and 64 random (counter, key) pairs from randomgen's independent implementation.

// Raw block: the function a GPU thread evaluates.
Philox4x32.block(c0, c1, c2, c3, k0, k1, out);          // 4 words into out (a Uint32List)

// Streams: key = seed (64-bit), counter = (position lo, position hi, stream lo, stream hi).
final rng = PhiloxStream(seed, stream: 7);
rng.nextU32(); rng.nextDouble(); rng.nextNormal(); rng.nextInt(n);
rng.fillUniformF32(f32); rng.fillUniform(f64); rng.fillNormal(f64); rng.fillNormalF32(f32); rng.fillU32(words);

// One substream per element and step, no shared state (particles, Monte Carlo collisions):
final s = PhiloxStream.substream(seed, particleIndex, step);   // = block(position, 0, particleIndex, step, seedLo, seedHi)

Exact conversions (U32), the same on CPU and GPU:

OutputFormula
f32 in [0, 1)(u >> 8) · 2⁻²⁴ (one word)
f32 in (0, 1]((u >> 8) + 1) · 2⁻²⁴
f64 in [0, 1)((a >> 5) · 2²⁶ + (b >> 6)) · 2⁻⁵³ (two words, a first)
f64 in (0, 1]the same + 2^{-53}
normalBox–Muller on an open and a half-open uniform; two normals per pair (transcendentals may differ by an ulp on a GPU)

Words are taken from a block in order 0–3, then the position advances; seek(position) jumps. Native Raya only (the 64-bit product relies on int wrapping; not the JavaScript compiler).

Distributions

Uniform, Normal, Exponential, GammaDistribution, BetaDistribution (ContinuousDistribution: pdf, logpdf, cdf, sf, ppf, isf, mean, variance, sample, sampleInto), Poisson, Binomial (DiscreteDistribution: pmf, logpmf, cdf, sf, ppf, …), MultivariateNormal (Cholesky; logpdf, sample), Dirichlet. SciPy parameterisations (loc/scale, GammaDistribution(a, scale)).

SamplerMethod
normalBox–Muller
gammaMarsaglia and Tsang (2000), U^{1/a} boost for a < 1
beta, Dirichletnormalised gammas
Poissonmultiplication of uniforms for \mu < 10; Hörmann's PTRS (1993)
binomialinversion for n \cdot \min(p, 1-p) < 30; Hörmann's BTRS (1993)

Cdf/ppf come from riptide_numerics_special (incomplete gamma/beta, erfc and their inverses); Poisson and binomial pmfs use Loader's saddle-point form (as R and SciPy), so they keep full precision at n = 5000.

Descriptive statistics and models

Stats: compensated sum/mean, Welford variance/std (ddof), skewness, kurtosis (SciPy defaults and the unbiased forms), median, quantile with all 13 NumPy methods (bit-identical to numpy.quantile in the tests), histogram (bit-identical counts and edges to numpy.histogram), pearson, spearman, rank, covariance, correlationMatrix.

LinearRegression.fit (Householder QR: coefficients, standard errors, R^{2}, residuals), LogisticRegression.fit (IRLS/Newton, optional L2, standard errors, log-likelihood), Pca.fit (SVD of the centred data with part A's la.svd), KMeans.fit (k-means++ seeded from Philox, Lloyd, best of restarts).

Classes

class

Stats

abstract final class Stats

Descriptive statistics over a sample (any List<double>, typically a Float64List or one axis of an NDArray).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:typed_data';

void main() {
  final xs = Float64List.fromList([2, 4, 4, 4, 5, 5, 7, 9]);
  print('mean ${Stats.mean(xs)}, std ${Stats.std(xs)}, median ${Stats.median(xs)}');
  print('variance ${Stats.variance(xs)}');
  print('90th percentile ${Stats.quantile(xs, 0.9)}');
}
Output
mean 5.0, std 2.0, median 4.5
variance 4.0
90th percentile 7.6

Static

meanstaticmethod
static double mean(List<double> x)

Mean with Neumaier's compensated sum.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final x = [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
  print('mean = ${Stats.mean(x)}');
}
Output
mean = 5.0
sumstaticmethod
static double sum(List<double> x)

Neumaier (improved Kahan) summation.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final x = List<double>.filled(100000, 0.1);
  print('compensated sum of 100000 × 0.1 = ${Stats.sum(x)}');
}
Output
compensated sum of 100000 × 0.1 = 10000.0
variancestaticmethod
static double variance(List<double> x, {int ddof = 0})

Variance by Welford's one-pass algorithm; ddof = 0 (population, NumPy's default) or 1 (sample).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final x = [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
  print('population variance = ${Stats.variance(x)}');
  print('sample variance (ddof 1) = ${Stats.variance(x, ddof: 1)}');
}
Output
population variance = 4.0
sample variance (ddof 1) = 4.571428571428571
stdstaticmethod
static double std(List<double> x, {int ddof = 0})
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final x = [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
  print('std = ${Stats.std(x)}, sample std = ${Stats.std(x, ddof: 1).toStringAsFixed(6)}');
}
Output
std = 2.0, sample std = 2.138090
skewnessstaticmethod
static double skewness(List<double> x, {bool bias = true})

Skewness g1 (SciPy skew, bias=True by default; bias=False gives the adjusted Fisher–Pearson G1).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = PhiloxStream(1);
  final ex = Float64List(5000);
  const Exponential().sampleInto(rng, ex);
  print('exponential samples: skewness ${Stats.skewness(ex).toStringAsFixed(3)} (theory 2)');
  print('symmetric data: ${Stats.skewness([1, 2, 3, 4, 5])}');
}
Output
exponential samples: skewness 1.978 (theory 2)
symmetric data: 0.0
kurtosisstaticmethod
static double kurtosis(List<double> x, {bool fisher = true, bool bias = true})

Kurtosis (SciPy kurtosis: Fisher's definition, excess over 3, by default; bias=True by default).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = PhiloxStream(1);
  final ex = Float64List(5000);
  const Exponential().sampleInto(rng, ex);
  print('excess kurtosis ${Stats.kurtosis(ex).toStringAsFixed(3)} (theory 6)');
  print('Pearson (not excess): ${Stats.kurtosis(ex, fisher: false).toStringAsFixed(3)}');
}
Output
excess kurtosis 5.470 (theory 6)
Pearson (not excess): 8.470
medianstaticmethod
static double median(List<double> x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final x = [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
  print('median = ${Stats.median(x)}');
  print('odd count: ${Stats.median([5, 1, 3])}');
}
Output
median = 4.5
odd count: 3.0
quantilestaticmethod
static double quantile(List<double> x, double q, {String method = 'linear'})

Quantile q in [0, 1] with NumPy's method names (default 'linear'). Methods: linear, lower, higher, nearest, midpoint, weibull, hazen, median_unbiased, normal_unbiased, interpolated_inverted_cdf, inverted_cdf, averaged_inverted_cdf, closest_observation.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final x = [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
  for (final m in ['linear', 'lower', 'higher', 'nearest', 'midpoint']) {
    print('${m.padRight(8)} q(0.3) = ${Stats.quantile(x, 0.3, method: m)}');
  }
}
Output
linear   q(0.3) = 4.0
lower    q(0.3) = 4.0
higher   q(0.3) = 4.0
nearest  q(0.3) = 4.0
midpoint q(0.3) = 4.0
quantileSortedstaticmethod
static double quantileSorted(List<double> s, double q, {String method = 'linear'})

quantile over already sorted data.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final s = [1.0, 2.0, 3.0, 10.0];
  print('quartiles of sorted data: ${[for (final q in [0.25, 0.5, 0.75]) Stats.quantileSorted(s, q)]}');
}
Output
quartiles of sorted data: [1.75, 2.5, 4.75]
histogramstaticmethod
static (Int64List, Float64List) histogram(List<double> x, int bins, {(double, double)? range})

Histogram with NumPy's semantics: bins equal-width bins over range (default the data's min/max; \pm0.5 when they are equal), every bin half-open except the last, values outside excluded. Returns (counts, edges).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = PhiloxStream(7);
  final x = Float64List(4000);
  rng.fillNormal(x);
  final (counts, edges) = Stats.histogram(x, 20, range: (-4, 4));
  print('bins: ${counts.length}, total ${counts.reduce((a, b) => a + b)}');
  print('edges ${edges.first} … ${edges.last}');
}
Output
bins: 20, total 4000
edges -4.0 … 4.0
pearsonstaticmethod
static double pearson(List<double> x, List<double> y)

Pearson correlation coefficient (two-pass).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:typed_data';

void main() {
  final x = Float64List.fromList([1, 2, 3, 4, 5]);
  final y = Float64List.fromList([2, 4, 5, 4, 5]);
  print('pearson  ${Stats.pearson(x, y).toStringAsFixed(6)}');
  print('spearman ${Stats.spearman(x, y).toStringAsFixed(6)}');
}
Output
pearson  0.774597
spearman 0.737865
spearmanstaticmethod
static double spearman(List<double> x, List<double> y)

Spearman's rank correlation (ties get average ranks, as SciPy).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final x = [1.0, 2.0, 3.0, 4.0, 5.0];
  final y = [for (final v in x) math.exp(v)]; // monotone but not linear
  print('Spearman ${Stats.spearman(x, y)}, Pearson ${Stats.pearson(x, y).toStringAsFixed(4)}');
}
Output
Spearman 1.0, Pearson 0.8863
rankstaticmethod
static Float64List rank(List<double> x)

Ranks 1…n with ties averaged (SciPy rankdata, method='average').

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  print(Stats.rank([30, 10, 20, 20, 50]));
}
Output
[4.0, 1.0, 2.5, 2.5, 5.0]
covariancestaticmethod
static Float64List covariance(List<double> data, int n, int p, {int ddof = 1})

Covariance matrix of data (n rows = observations, p columns = variables, row-major), p \times p, with ddof.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // 6 observations of 3 variables (rows): y = 2x roughly, z unrelated.
  final d = [1.0, 2.1, 5.0, 2.0, 3.9, 1.0, 3.0, 6.2, 4.0, 4.0, 7.8, 2.0, 5.0, 10.1, 3.0, 6.0, 11.9, 6.0];
  final c = Stats.covariance(d, 6, 3);
  for (var i = 0; i < 3; i++) {
    print([for (var j = 0; j < 3; j++) c[3 * i + j].toStringAsFixed(3)]);
  }
}
Output
[3.500, 6.920, 0.900]
[6.920, 13.704, 1.900]
[0.900, 1.900, 3.500]
correlationMatrixstaticmethod
static Float64List correlationMatrix(List<double> data, int n, int p)

Correlation matrix (NumPy corrcoef with rowvar=False).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // 6 observations of 3 variables (rows): y = 2x roughly, z unrelated.
  final d = [1.0, 2.1, 5.0, 2.0, 3.9, 1.0, 3.0, 6.2, 4.0, 4.0, 7.8, 2.0, 5.0, 10.1, 3.0, 6.0, 11.9, 6.0];
  final r = Stats.correlationMatrix(d, 6, 3);
  print('corr(x, y) = ${r[1].toStringAsFixed(4)}, corr(x, z) = ${r[2].toStringAsFixed(4)}');
}
Output
corr(x, y) = 0.9992, corr(x, z) = 0.2571
abstract base class ContinuousDistribution

A univariate continuous distribution. Parameters follow SciPy (loc/scale names where SciPy has them).

Constructors

const ContinuousDistribution()
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // Any continuous law: subclass and give pdf, cdf and ppf; the rest come for free.
  const ContinuousDistribution tri = Triangular();
  print('pdf(0.25) = ${tri.pdf(0.25)}, cdf(0.5) = ${tri.cdf(0.5)}, sf(0.5) = ${tri.sf(0.5)}');
  print('median by ppf: ${tri.ppf(0.5).toStringAsFixed(6)}');
  print('sample: ${tri.sample(PhiloxStream(1)).toStringAsFixed(6)}');
}

final class Triangular extends ContinuousDistribution {
  const Triangular();
  @override
  double pdf(double x) => x < 0 || x > 1 ? 0 : 2 * x;
  @override
  double cdf(double x) => x <= 0 ? 0 : (x >= 1 ? 1 : x * x);
  @override
  double ppf(double p) => math.sqrt(p);
  @override
  double logpdf(double x) => math.log(pdf(x));
  @override
  double sample(PhiloxStream rng) => ppf(rng.nextDouble());
  @override
  double get mean => 2 / 3;
  @override
  double get variance => 1 / 18;
}
Output
pdf(0.25) = 0.5, cdf(0.5) = 0.25, sf(0.5) = 0.75
median by ppf: 0.707107
sample: 0.943535

Properties

meangetter
double get mean
variancegetter
double get variance
stdgetter
double get std

Methods

pdfmethod
double pdf(double x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The ContinuousDistribution API, shown on Normal(1, 2).
  const n = Normal(1, 2);
  print('N(1, 2²) pdf(1) = ${n.pdf(1).toStringAsFixed(8)}');
}
Output
N(1, 2²) pdf(1) = 0.19947114
logpdfmethod
double logpdf(double x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The ContinuousDistribution API, shown on Normal(1, 2).
  const n = Normal(1, 2);
  print('logpdf(1) = ${n.logpdf(1)}, log(pdf(1)) = ${math.log(n.pdf(1))}');
}
Output
logpdf(1) = -1.612085713764618, log(pdf(1)) = -1.612085713764618
cdfmethod
double cdf(double x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The ContinuousDistribution API, shown on Normal(1, 2).
  const n = Normal(1, 2);
  print('cdf(1) = ${n.cdf(1)}, cdf(3) = ${n.cdf(3).toStringAsFixed(6)}');
}
Output
cdf(1) = 0.5, cdf(3) = 0.841345
sfmethod
double sf(double x)

Survival function 1 - cdf, computed without cancellation.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The ContinuousDistribution API, shown on Normal(1, 2).
  const n = Normal(1, 2);
  print('sf(9) = ${n.sf(9).toStringAsExponential(4)}  (1 − cdf would lose digits)');
}
Output
sf(9) = 3.1671e-5  (1 − cdf would lose digits)
ppfmethod
double ppf(double p)

Quantile function (inverse cdf).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The ContinuousDistribution API, shown on Normal(1, 2).
  const n = Normal(1, 2);
  print('ppf(0.975) = ${n.ppf(0.975).toStringAsFixed(6)}');
}
Output
ppf(0.975) = 4.919928
isfmethod
double isf(double q)

Inverse survival function.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The ContinuousDistribution API, shown on Normal(1, 2).
  const n = Normal(1, 2);
  print('isf(1e-10) = ${n.isf(1e-10).toStringAsFixed(6)}');
}
Output
isf(1e-10) = 13.722682
samplemethod
double sample(PhiloxStream rng)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The ContinuousDistribution API, shown on Normal(1, 2).
  const n = Normal(1, 2);
  print('one draw: ${n.sample(PhiloxStream(4)).toStringAsFixed(6)}');
}
Output
one draw: -0.921938
void sampleInto(PhiloxStream rng, Float64List out)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The ContinuousDistribution API, shown on Normal(1, 2).
  const n = Normal(1, 2);
  final out = Float64List(10000);
  n.sampleInto(PhiloxStream(4), out);
  print('mean ${Stats.mean(out).toStringAsFixed(3)}, std ${Stats.std(out).toStringAsFixed(3)}');
}
Output
mean 0.991, std 2.016
abstract base class DiscreteDistribution

A univariate distribution on the integers.

Constructors

const DiscreteDistribution()
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const DiscreteDistribution die = Die();
  print('P(3) = ${die.pmf(3)}, P(≤ 4) = ${die.cdf(4)}, P(> 4) = ${die.sf(4)}');
  print('ppf(0.5) = ${die.ppf(0.5)}');
}

final class Die extends DiscreteDistribution {
  const Die();
  @override
  double pmf(int k) => k >= 1 && k <= 6 ? 1 / 6 : 0;
  @override
  double cdf(int k) => k < 1 ? 0 : (k >= 6 ? 1 : k / 6);
  @override
  int ppf(double p) => (p * 6).ceil().clamp(1, 6);
  @override
  double logpmf(int k) => math.log(pmf(k));
  @override
  int sample(PhiloxStream rng) => 1 + rng.nextInt(6);
  @override
  double get mean => 3.5;
  @override
  double get variance => 35 / 12;
}
Output
P(3) = 0.16666666666666666, P(≤ 4) = 0.6666666666666666, P(> 4) = 0.33333333333333337
ppf(0.5) = 3

Properties

meangetter
double get mean
variancegetter
double get variance

Methods

pmfmethod
double pmf(int k)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The DiscreteDistribution API, shown on Binomial(20, 0.3).
  const b = Binomial(20, 0.3);
  print('P(6) = ${b.pmf(6).toStringAsFixed(8)}');
}
Output
P(6) = 0.19163898
logpmfmethod
double logpmf(int k)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The DiscreteDistribution API, shown on Binomial(20, 0.3).
  const b = Binomial(20, 0.3);
  print('log P(6) = ${b.logpmf(6).toStringAsFixed(8)}');
}
Output
log P(6) = -1.65214198
cdfmethod
double cdf(int k)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The DiscreteDistribution API, shown on Binomial(20, 0.3).
  const b = Binomial(20, 0.3);
  print('P(≤ 6) = ${b.cdf(6).toStringAsFixed(8)}');
}
Output
P(≤ 6) = 0.60800981
sfmethod
double sf(int k)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The DiscreteDistribution API, shown on Binomial(20, 0.3).
  const b = Binomial(20, 0.3);
  print('P(> 15) = ${b.sf(15).toStringAsExponential(4)}');
}
Output
P(> 15) = 5.5503e-6
ppfmethod
int ppf(double p)

Smallest k with \operatorname{cdf}(k) \ge p.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The DiscreteDistribution API, shown on Binomial(20, 0.3).
  const b = Binomial(20, 0.3);
  print('median = ${b.ppf(0.5)}, 95th percentile = ${b.ppf(0.95)}');
}
Output
median = 6, 95th percentile = 9
samplemethod
int sample(PhiloxStream rng)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The DiscreteDistribution API, shown on Binomial(20, 0.3).
  const b = Binomial(20, 0.3);
  final r = PhiloxStream(2);
  print('draws: ${[for (var i = 0; i < 8; i++) b.sample(r)]}');
}
Output
draws: [6, 10, 3, 10, 6, 7, 4, 2]
class

Uniform

final class Uniform extends ContinuousDistribution

Uniform on [low, high).

Constructors

Uniformconstructor
const Uniform([this.low = 0, this.high = 1])
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Uniform(-1, 3);
  print('mean ${d.mean.toStringAsFixed(6)}, variance ${d.variance.toStringAsFixed(6)}');
}
Output
mean 1.000000, variance 1.333333

Properties

lowfield
final double low
highfield
final double high
meangetter
double get mean
variancegetter
double get variance

Methods

logpdfmethod
double logpdf(double x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Uniform(-1, 3);
  print('logpdf at the middle: ${d.logpdf(1.0).toStringAsFixed(8)}');
}
Output
logpdf at the middle: -1.38629436
cdfmethod
double cdf(double x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Uniform(-1, 3);
  print('cdf at the middle: ${d.cdf(1.0).toStringAsFixed(8)}');
}
Output
cdf at the middle: 0.50000000
sfmethod
double sf(double x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Uniform(-1, 3);
  print('sf at the middle: ${d.sf(1.0).toStringAsFixed(8)}');
  print('far tail: ${d.sf(4).toStringAsExponential(4)}');
}
Output
sf at the middle: 0.50000000
far tail: 0.0000e+0
ppfmethod
double ppf(double p)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Uniform(-1, 3);
  print('quartiles: ${[for (final p in [0.25, 0.5, 0.75]) d.ppf(p).toStringAsFixed(6)]}');
  print('round trip cdf(ppf(0.3)) = ${d.cdf(d.ppf(0.3)).toStringAsFixed(12)}');
}
Output
quartiles: [0.000000, 1.000000, 2.000000]
round trip cdf(ppf(0.3)) = 0.300000000000
samplemethod
double sample(PhiloxStream rng)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Uniform(-1, 3);
  final rng = PhiloxStream(11);
  final s = Float64List(5000);
  for (var i = 0; i < s.length; i++) {
    s[i] = d.sample(rng);
  }
  print('sample mean ${Stats.mean(s).toStringAsFixed(3)}, sample variance ${Stats.variance(s).toStringAsFixed(3)}');
  print('theory: mean ${d.mean.toStringAsFixed(3)}, variance ${d.variance.toStringAsFixed(3)}');
  final (c, e) = Stats.histogram(s, 30, range: (-2.0, 4.0));
}
Output
sample mean 0.997, sample variance 1.356
theory: mean 1.000, variance 1.333
class

Normal

final class Normal extends ContinuousDistribution

Normal N(loc, scale²). Sampling: Box–Muller (two uniforms per pair of normals).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';

void main() {
  const z = Normal();
  print('pdf(0) = ${z.pdf(0)}');
  print('cdf(1.96) = ${z.cdf(1.96)}');
  print('ppf(0.975) = ${z.ppf(0.975)}');
  const n = Normal(10, 2);
  print('N(10, 2): mean ${n.mean}, variance ${n.variance}, P(X > 13) = ${n.sf(13).toStringAsFixed(6)}');
        {'label': 'pdf', 'points': [for (var i = -40; i <= 40; i++) [i / 10, z.pdf(i / 10)]]},
        {'label': 'cdf', 'points': [for (var i = -40; i <= 40; i++) [i / 10, z.cdf(i / 10)]]},
      ]})}');
}
Output
pdf(0) = 0.3989422804014327
cdf(1.96) = 0.9750021048517795
ppf(0.975) = 1.959963984540054
N(10, 2): mean 10.0, variance 4.0, P(X > 13) = 0.066807

Constructors

Normalconstructor
const Normal([this.loc = 0, this.scale = 1])
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Normal(10, 3);
  print('mean ${d.mean}, variance ${d.variance}');
}
Output
mean 10.0, variance 9.0

Properties

locfield
final double loc
scalefield
final double scale
meangetter
double get mean
variancegetter
double get variance

Methods

logpdfmethod
double logpdf(double x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Normal(0, 1);
  print('logpdf at the middle: ${d.logpdf(0.0).toStringAsFixed(8)}');
}
Output
logpdf at the middle: -0.91893853
cdfmethod
double cdf(double x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Normal(0, 1);
  print('cdf at the middle: ${d.cdf(0.0).toStringAsFixed(8)}');
}
Output
cdf at the middle: 0.50000000
sfmethod
double sf(double x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Normal(0, 1);
  print('sf at the middle: ${d.sf(0.0).toStringAsFixed(8)}');
  print('far tail: ${d.sf(4).toStringAsExponential(4)}');
}
Output
sf at the middle: 0.50000000
far tail: 3.1671e-5
ppfmethod
double ppf(double p)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Normal(0, 1);
  print('quartiles: ${[for (final p in [0.25, 0.5, 0.75]) d.ppf(p).toStringAsFixed(6)]}');
  print('round trip cdf(ppf(0.3)) = ${d.cdf(d.ppf(0.3)).toStringAsFixed(12)}');
}
Output
quartiles: [-0.674490, 0.000000, 0.674490]
round trip cdf(ppf(0.3)) = 0.300000000000
isfmethod
double isf(double q)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Normal(0, 1);
  print('upper 5% point: ${d.isf(0.05).toStringAsFixed(6)}');
  print('upper 1e-8 point: ${d.isf(1e-8).toStringAsFixed(6)}');
}
Output
upper 5% point: 1.644854
upper 1e-8 point: 5.612001
samplemethod
double sample(PhiloxStream rng)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Normal(0, 1);
  final rng = PhiloxStream(11);
  final s = Float64List(5000);
  for (var i = 0; i < s.length; i++) {
    s[i] = d.sample(rng);
  }
  print('sample mean ${Stats.mean(s).toStringAsFixed(3)}, sample variance ${Stats.variance(s).toStringAsFixed(3)}');
  print('theory: mean ${d.mean.toStringAsFixed(3)}, variance ${d.variance.toStringAsFixed(3)}');
  final (c, e) = Stats.histogram(s, 30, range: (-4.0, 4.0));
}
Output
sample mean -0.016, sample variance 1.021
theory: mean 0.000, variance 1.000
final class Exponential extends ContinuousDistribution

Exponential with mean scale (rate 1/scale).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:typed_data';

void main() {
  const e = Exponential(2);
  print('mean ${e.mean}, median ${e.ppf(0.5)}');
  final xs = Float64List(10000);
  e.sampleInto(PhiloxStream(9), xs);
  print('10 000 seeded samples: mean ${Stats.mean(xs).toStringAsFixed(3)}, median ${Stats.median(xs).toStringAsFixed(3)}');
}
Output
mean 2.0, median 1.3862943611198906
10 000 seeded samples: mean 2.008, median 1.400

Constructors

Exponentialconstructor
const Exponential([this.scale = 1])
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Exponential(2);
  print('mean ${d.mean}, variance ${d.variance}');
}
Output
mean 2.0, variance 4.0

Properties

scalefield
final double scale
meangetter
double get mean
variancegetter
double get variance

Methods

logpdfmethod
double logpdf(double x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Exponential(2);
  print('logpdf at the middle: ${d.logpdf(5.0).toStringAsFixed(8)}');
}
Output
logpdf at the middle: -3.19314718
cdfmethod
double cdf(double x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Exponential(2);
  print('cdf at the middle: ${d.cdf(5.0).toStringAsFixed(8)}');
}
Output
cdf at the middle: 0.91791500
sfmethod
double sf(double x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Exponential(2);
  print('sf at the middle: ${d.sf(5.0).toStringAsFixed(8)}');
  print('far tail: ${d.sf(10).toStringAsExponential(4)}');
}
Output
sf at the middle: 0.08208500
far tail: 6.7379e-3
ppfmethod
double ppf(double p)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Exponential(2);
  print('quartiles: ${[for (final p in [0.25, 0.5, 0.75]) d.ppf(p).toStringAsFixed(6)]}');
  print('round trip cdf(ppf(0.3)) = ${d.cdf(d.ppf(0.3)).toStringAsFixed(12)}');
}
Output
quartiles: [0.575364, 1.386294, 2.772589]
round trip cdf(ppf(0.3)) = 0.300000000000
isfmethod
double isf(double q)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Exponential(2);
  print('upper 5% point: ${d.isf(0.05).toStringAsFixed(6)}');
  print('upper 1e-8 point: ${d.isf(1e-8).toStringAsFixed(6)}');
}
Output
upper 5% point: 5.991465
upper 1e-8 point: 36.841361
samplemethod
double sample(PhiloxStream rng)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Exponential(2);
  final rng = PhiloxStream(11);
  final s = Float64List(5000);
  for (var i = 0; i < s.length; i++) {
    s[i] = d.sample(rng);
  }
  print('sample mean ${Stats.mean(s).toStringAsFixed(3)}, sample variance ${Stats.variance(s).toStringAsFixed(3)}');
  print('theory: mean ${d.mean.toStringAsFixed(3)}, variance ${d.variance.toStringAsFixed(3)}');
  final (c, e) = Stats.histogram(s, 30, range: (0.0, 10.0));
}
Output
sample mean 2.041, sample variance 4.342
theory: mean 2.000, variance 4.000
final class GammaDistribution extends ContinuousDistribution

Gamma with shape a and scale. Sampling: Marsaglia and Tsang (2000), with the U^{1/a} boost for a < 1.

Constructors

const GammaDistribution(this.a, [this.scale = 1])
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = GammaDistribution(3, 1.5);
  print('mean ${d.mean.toStringAsFixed(6)}, variance ${d.variance.toStringAsFixed(6)}');
}
Output
mean 4.500000, variance 6.750000

Static

standardGammastaticmethod
static double standardGamma(double a, PhiloxStream rng)

A Gamma(a, 1) variate.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = PhiloxStream(3);
  final s = Float64List(4000);
  for (var i = 0; i < s.length; i++) {
    s[i] = GammaDistribution.standardGamma(0.5, rng);
  }
  print('Gamma(0.5) samples: mean ${Stats.mean(s).toStringAsFixed(3)} (theory 0.5)');
}
Output
Gamma(0.5) samples: mean 0.500 (theory 0.5)

Properties

afield
final double a
scalefield
final double scale
meangetter
double get mean
variancegetter
double get variance

Methods

logpdfmethod
double logpdf(double x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = GammaDistribution(3, 1.5);
  print('logpdf at the middle: ${d.logpdf(7.5).toStringAsFixed(8)}');
}
Output
logpdf at the middle: -2.87973646
cdfmethod
double cdf(double x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = GammaDistribution(3, 1.5);
  print('cdf at the middle: ${d.cdf(7.5).toStringAsFixed(8)}');
}
Output
cdf at the middle: 0.87534798
sfmethod
double sf(double x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = GammaDistribution(3, 1.5);
  print('sf at the middle: ${d.sf(7.5).toStringAsFixed(8)}');
  print('far tail: ${d.sf(15).toStringAsExponential(4)}');
}
Output
sf at the middle: 0.12465202
far tail: 2.7694e-3
ppfmethod
double ppf(double p)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = GammaDistribution(3, 1.5);
  print('quartiles: ${[for (final p in [0.25, 0.5, 0.75]) d.ppf(p).toStringAsFixed(6)]}');
  print('round trip cdf(ppf(0.3)) = ${d.cdf(d.ppf(0.3)).toStringAsFixed(12)}');
}
Output
quartiles: [2.590949, 4.011090, 5.880603]
round trip cdf(ppf(0.3)) = 0.300000000000
isfmethod
double isf(double q)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = GammaDistribution(3, 1.5);
  print('upper 5% point: ${d.isf(0.05).toStringAsFixed(6)}');
  print('upper 1e-8 point: ${d.isf(1e-8).toStringAsFixed(6)}');
}
Output
upper 5% point: 9.443690
upper 1e-8 point: 36.271971
samplemethod
double sample(PhiloxStream rng)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = GammaDistribution(3, 1.5);
  final rng = PhiloxStream(11);
  final s = Float64List(5000);
  for (var i = 0; i < s.length; i++) {
    s[i] = d.sample(rng);
  }
  print('sample mean ${Stats.mean(s).toStringAsFixed(3)}, sample variance ${Stats.variance(s).toStringAsFixed(3)}');
  print('theory: mean ${d.mean.toStringAsFixed(3)}, variance ${d.variance.toStringAsFixed(3)}');
  final (c, e) = Stats.histogram(s, 30, range: (0.0, 15.0));
}
Output
sample mean 4.461, sample variance 6.860
theory: mean 4.500, variance 6.750
final class BetaDistribution extends ContinuousDistribution

\operatorname{Beta}(a, b) on [0, 1]. Sampling: \frac{X}{X + Y} with X ~ Gamma(a), Y ~ Gamma(b).

Constructors

BetaDistributionconstructor
const BetaDistribution(this.a, this.b)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = BetaDistribution(2, 5);
  print('mean ${d.mean.toStringAsFixed(6)}, variance ${d.variance.toStringAsFixed(6)}');
}
Output
mean 0.285714, variance 0.025510

Properties

afield
final double a
bfield
final double b
meangetter
double get mean
variancegetter
double get variance

Methods

logpdfmethod
double logpdf(double x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = BetaDistribution(2, 5);
  print('logpdf at the middle: ${d.logpdf(0.5).toStringAsFixed(8)}');
}
Output
logpdf at the middle: -0.06453852
cdfmethod
double cdf(double x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = BetaDistribution(2, 5);
  print('cdf at the middle: ${d.cdf(0.5).toStringAsFixed(8)}');
}
Output
cdf at the middle: 0.89062500
sfmethod
double sf(double x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = BetaDistribution(2, 5);
  print('sf at the middle: ${d.sf(0.5).toStringAsFixed(8)}');
  print('far tail: ${d.sf(1).toStringAsExponential(4)}');
}
Output
sf at the middle: 0.10937500
far tail: 0.0000e+0
ppfmethod
double ppf(double p)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = BetaDistribution(2, 5);
  print('quartiles: ${[for (final p in [0.25, 0.5, 0.75]) d.ppf(p).toStringAsFixed(6)]}');
  print('round trip cdf(ppf(0.3)) = ${d.cdf(d.ppf(0.3)).toStringAsFixed(12)}');
}
Output
quartiles: [0.161163, 0.264450, 0.389479]
round trip cdf(ppf(0.3)) = 0.300000000000
isfmethod
double isf(double q)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = BetaDistribution(2, 5);
  print('upper 5% point: ${d.isf(0.05).toStringAsFixed(6)}');
  print('upper 1e-8 point: ${d.isf(1e-8).toStringAsFixed(6)}');
}
Output
upper 5% point: 0.581803
upper 1e-8 point: 0.982394
samplemethod
double sample(PhiloxStream rng)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = BetaDistribution(2, 5);
  final rng = PhiloxStream(11);
  final s = Float64List(5000);
  for (var i = 0; i < s.length; i++) {
    s[i] = d.sample(rng);
  }
  print('sample mean ${Stats.mean(s).toStringAsFixed(3)}, sample variance ${Stats.variance(s).toStringAsFixed(3)}');
  print('theory: mean ${d.mean.toStringAsFixed(3)}, variance ${d.variance.toStringAsFixed(3)}');
  final (c, e) = Stats.histogram(s, 30, range: (0.0, 1.0));
}
Output
sample mean 0.284, sample variance 0.026
theory: mean 0.286, variance 0.026
class

Poisson

final class Poisson extends DiscreteDistribution

Poisson with mean mu. Sampling: inversion for \mu < 10, Hörmann's PTRS transformed rejection otherwise.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';

void main() {
  const p = Poisson(3);
  for (var k = 0; k <= 5; k++) {
    print('P($k) = ${p.pmf(k).toStringAsFixed(6)}');
  }
  print('P(at most 3) = ${p.cdf(3).toStringAsFixed(6)}');
}
Output
P(0) = 0.049787
P(1) = 0.149361
P(2) = 0.224042
P(3) = 0.224042
P(4) = 0.168031
P(5) = 0.100819
P(at most 3) = 0.647232

Constructors

Poissonconstructor
const Poisson(this.mu)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Poisson(4);
  print('mean ${d.mean}, variance ${d.variance}');
}
Output
mean 4.0, variance 4.0

Properties

mufield
final double mu
meangetter
double get mean
variancegetter
double get variance

Methods

logpmfmethod
double logpmf(int k)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Poisson(4);
  print('logpmf(3) = ${d.logpmf(3).toStringAsFixed(8)}, log pmf = ${math.log(d.pmf(3)).toStringAsFixed(8)}');
}
Output
logpmf(3) = -1.63287639, log pmf = -1.63287639
cdfmethod
double cdf(int k)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Poisson(4);
  print('P(X ≤ 4) = ${d.cdf(4).toStringAsFixed(8)}');
}
Output
P(X ≤ 4) = 0.62883694
sfmethod
double sf(int k)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Poisson(4);
  print('P(X > 8) = ${d.sf(8).toStringAsExponential(4)}');
}
Output
P(X > 8) = 2.1363e-2
ppfmethod
int ppf(double p)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Poisson(4);
  print('quantiles 0.1, 0.5, 0.9: ${[d.ppf(0.1), d.ppf(0.5), d.ppf(0.9)]}');
}
Output
quantiles 0.1, 0.5, 0.9: [2, 4, 7]
samplemethod
int sample(PhiloxStream rng)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Poisson(4);
  final rng = PhiloxStream(8);
  final counts = List<int>.filled(15, 0);
  for (var i = 0; i < 5000; i++) {
    final k = d.sample(rng);
    if (k <= 14) counts[k]++;
  }
  print('most frequent value: ${counts.indexOf(counts.reduce(math.max))}');
}
Output
most frequent value: 4
final class Binomial extends DiscreteDistribution

\operatorname{Binomial}(n, p). Sampling: inversion for n \cdot \min(p, 1-p) < 30, Hörmann's BTRS transformed rejection otherwise.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';

void main() {
  const coin = Binomial(10, 0.5);
  print('P(5 heads in 10) = ${coin.pmf(5).toStringAsFixed(10)}  (252/1024 = ${252 / 1024})');
  print('P(at most 2) = ${coin.cdf(2).toStringAsFixed(10)}  (56/1024 = ${56 / 1024})');
  print('mean ${coin.mean}, variance ${coin.variance}');
        {'style': 'points', 'points': [for (var k = 0; k <= 10; k++) [k, coin.pmf(k)]]}
      ]})}');
}
Output
P(5 heads in 10) = 0.2460937500  (252/1024 = 0.24609375)
P(at most 2) = 0.0546875000  (56/1024 = 0.0546875)
mean 5.0, variance 2.5

Constructors

Binomialconstructor
const Binomial(this.n, this.p)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Binomial(12, 0.4);
  print('mean ${d.mean}, variance ${d.variance}');
}
Output
mean 4.800000000000001, variance 2.8800000000000003

Properties

nfield
final int n
pfield
final double p
meangetter
double get mean
variancegetter
double get variance

Methods

logpmfmethod
double logpmf(int k)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Binomial(12, 0.4);
  print('logpmf(3) = ${d.logpmf(3).toStringAsFixed(8)}, log pmf = ${math.log(d.pmf(3)).toStringAsFixed(8)}');
}
Output
logpmf(3) = -1.95267526, log pmf = -1.95267526
cdfmethod
double cdf(int k)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Binomial(12, 0.4);
  print('P(X ≤ 4) = ${d.cdf(4).toStringAsFixed(8)}');
}
Output
P(X ≤ 4) = 0.43817822
sfmethod
double sf(int k)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Binomial(12, 0.4);
  print('P(X > 8) = ${d.sf(8).toStringAsExponential(4)}');
}
Output
P(X > 8) = 1.5267e-2
ppfmethod
int ppf(double q)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Binomial(12, 0.4);
  print('quantiles 0.1, 0.5, 0.9: ${[d.ppf(0.1), d.ppf(0.5), d.ppf(0.9)]}');
}
Output
quantiles 0.1, 0.5, 0.9: [3, 5, 7]
samplemethod
int sample(PhiloxStream rng)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const d = Binomial(12, 0.4);
  final rng = PhiloxStream(8);
  final counts = List<int>.filled(13, 0);
  for (var i = 0; i < 5000; i++) {
    final k = d.sample(rng);
    if (k <= 12) counts[k]++;
  }
  print('most frequent value: ${counts.indexOf(counts.reduce(math.max))}');
}
Output
most frequent value: 5
final class MultivariateNormal

Multivariate normal with mean (d) and covariance cov (d \times d row-major, positive definite).

Constructors

MultivariateNormal(this.mean, this.cov)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final d = MultivariateNormal(Float64List.fromList([0, 0]), Float64List.fromList([1, 0.8, 0.8, 1]));
  final rng = PhiloxStream(6), out = Float64List(2);
  final pts = <List<double>>[];
  for (var i = 0; i < 400; i++) {
    d.sample(rng, out);
    pts.add([out[0], out[1]]);
  }
  print('correlation of 400 draws: ${Stats.pearson([for (final p in pts) p[0]], [for (final p in pts) p[1]]).toStringAsFixed(3)} (0.8)');
}
Output
correlation of 400 draws: 0.787 (0.8)

Properties

meanfield
final Float64List mean
covfield
final Float64List cov
dfield
final int d

Methods

logpdfmethod
double logpdf(Float64List x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final d = MultivariateNormal(Float64List.fromList([0, 0]), Float64List.fromList([1, 0.8, 0.8, 1]));
  print('logpdf(0, 0) = ${d.logpdf(Float64List.fromList([0, 0])).toStringAsFixed(8)}');
  print('along the ridge (1, 1): ${d.logpdf(Float64List.fromList([1, 1])).toStringAsFixed(4)}, across (1, −1): ${d.logpdf(Float64List.fromList([1, -1])).toStringAsFixed(4)}');
}
Output
logpdf(0, 0) = -1.32705144
along the ridge (1, 1): -1.8826, across (1, −1): -6.3271
pdfmethod
double pdf(Float64List x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final d = MultivariateNormal(Float64List.fromList([0, 0]), Float64List.fromList([1, 0.8, 0.8, 1]));
  print('pdf(0, 0) = ${d.pdf(Float64List.fromList([0, 0])).toStringAsFixed(8)}');
}
Output
pdf(0, 0) = 0.26525824
samplemethod
void sample(PhiloxStream rng, Float64List out)

One sample written to out (length d): \operatorname{mean} + L z with z standard normal.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final d = MultivariateNormal(Float64List.fromList([0, 0]), Float64List.fromList([1, 0.8, 0.8, 1]));
  final out = Float64List(2);
  d.sample(PhiloxStream(1), out);
  print('one draw: (${out[0].toStringAsFixed(4)}, ${out[1].toStringAsFixed(4)})');
}
Output
one draw: (-0.4139, -0.4795)
final class Dirichlet

Dirichlet(alpha) on the simplex. Sampling: normalised \operatorname{Gamma}(\alpha_{i}) variates.

Constructors

Dirichletconstructor
Dirichlet(this.alpha)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final d = Dirichlet(Float64List.fromList([2, 3, 5]));
  print('mean ${d.mean}');
  final rng = PhiloxStream(9), out = Float64List(3);
  final pts = <List<double>>[];
  for (var i = 0; i < 300; i++) {
    d.sample(rng, out);
    pts.add([out[1] + out[2] / 2, out[2] * 0.8660254037844386]); // barycentric -> triangle
  }
}
Output
mean [0.2, 0.3, 0.5]

Properties

alphafield
final Float64List alpha
alpha0getter
double get alpha0
meangetter
Float64List get mean
variancegetter
Float64List get variance

Methods

logpdfmethod
double logpdf(Float64List x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final d = Dirichlet(Float64List.fromList([2, 3, 5]));
  print('logpdf at the mean: ${d.logpdf(d.mean).toStringAsFixed(6)}');
}
Output
logpdf at the mean: 2.140654
pdfmethod
double pdf(Float64List x)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final d = Dirichlet(Float64List.fromList([2, 3, 5]));
  print('pdf at (0.2, 0.3, 0.5): ${d.pdf(Float64List.fromList([0.2, 0.3, 0.5])).toStringAsFixed(6)}');
  print('pdf at (0.6, 0.2, 0.2): ${d.pdf(Float64List.fromList([0.6, 0.2, 0.2])).toStringAsFixed(6)}');
}
Output
pdf at (0.2, 0.3, 0.5): 8.505000
pdf at (0.6, 0.2, 0.2): 0.290304
samplemethod
void sample(PhiloxStream rng, Float64List out)
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final d = Dirichlet(Float64List.fromList([2, 3, 5]));
  final out = Float64List(3);
  d.sample(PhiloxStream(2), out);
  print('draw ${out.map((v) => v.toStringAsFixed(4)).toList()}, sum ${out.reduce((a, b) => a + b)}');
}
Output
draw [0.4046, 0.2402, 0.3551], sum 1.0
final class LinearRegression

Ordinary least squares fit (Householder QR, so no normal equations).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:typed_data';
import 'raya:convert';

void main() {
  final rng = PhiloxStream(2026);
  const n = 40;
  final x = Float64List(n), y = Float64List(n);
  for (var i = 0; i < n; i++) {
    x[i] = i / 4;
    y[i] = 3 + 2 * x[i] + 0.8 * rng.nextNormal();
  }
  final fit = LinearRegression.fit(x, n, 1, y);
  final b = fit.coefficients;
  print('intercept ${b[0].toStringAsFixed(3)}, slope ${b[1].toStringAsFixed(3)} (true 3 and 2)');
  print('R² = ${fit.rSquared.toStringAsFixed(4)}');
        {'label': 'data', 'style': 'points', 'points': [for (var i = 0; i < n; i++) [x[i], y[i]]]},
        {'label': 'fit', 'points': [[0, b[0]], [x[n - 1], b[0] + b[1] * x[n - 1]]]},
      ]})}');
}
Output
intercept 2.827, slope 2.008 (true 3 and 2)
R² = 0.9852

Constructors

factory LinearRegression.fit(List<double> x, int n, int p, List<double> y, {bool intercept = true})

Fits y \approx X \beta for X (n \times p row-major). With intercept a column of ones is prepended (\beta[0] is the intercept).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = PhiloxStream(12);
  final x = [for (var i = 0; i < 30; i++) i / 3];
  final y = [for (final v in x) 1.5 + 0.8 * v + 0.5 * rng.nextNormal()];
  final m = LinearRegression.fit(x, 30, 1, y);
  print('intercept ${m.coefficients[0].toStringAsFixed(3)} ± ${m.standardErrors[0].toStringAsFixed(3)}');
  print('slope ${m.coefficients[1].toStringAsFixed(3)} ± ${m.standardErrors[1].toStringAsFixed(3)}, R² ${m.rSquared.toStringAsFixed(3)}');
}
Output
intercept 1.439 ± 0.179
slope 0.815 ± 0.032, R² 0.959

Properties

final Float64List coefficients
final Float64List standardErrors
final Float64List residuals
final double rSquared
final double residualVariance
final class LogisticRegression

Logistic regression by iteratively reweighted least squares (Newton's method on the log-likelihood), with an optional L2 penalty l2 on the non-intercept coefficients.

Constructors

factory LogisticRegression.fit(List<double> x, int n, int p, List<double> y, {bool intercept = true, double l2 = 0, int maxIterations = 100, double tolerance = 1e-12})
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // Pass/fail against hours studied.
  final rng = PhiloxStream(4);
  final hours = [for (var i = 0; i < 60; i++) i / 6];
  final passed = [for (final h in hours) rng.nextDouble() < 1 / (1 + math.exp(-(h - 5) * 1.2)) ? 1.0 : 0.0];
  final m = LogisticRegression.fit(hours, 60, 1, passed);
  print('coefficients ${m.coefficients.map((v) => v.toStringAsFixed(3)).toList()} after ${m.iterations} iterations');
  print('log-likelihood ${m.logLikelihood.toStringAsFixed(3)}');
}
Output
coefficients [-6.813, 1.184] after 8 iterations
log-likelihood -16.377

Properties

final Float64List coefficients
final Float64List standardErrors
final double logLikelihood
final int iterations
final bool intercept

Methods

predictmethod
double predict(List<double> features)

P(y = 1 | features) for one row of p features.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // Pass/fail against hours studied.
  final rng = PhiloxStream(4);
  final hours = [for (var i = 0; i < 60; i++) i / 6];
  final passed = [for (final h in hours) rng.nextDouble() < 1 / (1 + math.exp(-(h - 5) * 1.2)) ? 1.0 : 0.0];
  final m = LogisticRegression.fit(hours, 60, 1, passed);
  for (final h in [2.0, 5.0, 8.0]) {
    print('$h hours: P(pass) = ${m.predict([h]).toStringAsFixed(3)}');
  }
}
Output
2.0 hours: P(pass) = 0.012
5.0 hours: P(pass) = 0.290
8.0 hours: P(pass) = 0.934
class

Pca

final class Pca

Principal component analysis by the SVD of the centred data (part A's svd, LAPACK-style one-sided bidiagonal QR), which avoids squaring the condition number as the covariance route does.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:typed_data';

void main() {
  // Points along the line y = 2x with a little noise: one component explains almost everything.
  final rng = PhiloxStream(3);
  const n = 50;
  final data = Float64List(n * 2);
  for (var i = 0; i < n; i++) {
    final t = i / 10;
    data[2 * i] = t + 0.05 * rng.nextNormal();
    data[2 * i + 1] = 2 * t + 0.05 * rng.nextNormal();
  }
  final p = Pca.fit(data, n, 2);
  print('explained variance ratio: ${[for (final r in p.explainedVarianceRatio) r.toStringAsFixed(4)]}');
}
Output
explained variance ratio: [0.9998, 0.0002]

Constructors

Pca.fitfactory
factory Pca.fit(List<double> data, int n, int p, {int? k})

Fits data (n \times p row-major), keeping k components (all by default).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = PhiloxStream(3);
  const n = 60;
  final data = Float64List(n * 2);
  for (var i = 0; i < n; i++) {
    final t = rng.nextNormal();
    data[2 * i] = 2 * t + 0.3 * rng.nextNormal();
    data[2 * i + 1] = t + 0.3 * rng.nextNormal();
  }
  final p = Pca.fit(data, n, 2);
  print('first component (${p.components[0].toStringAsFixed(3)}, ${p.components[1].toStringAsFixed(3)}), ratio ${p.explainedVarianceRatio[0].toStringAsFixed(3)}');
  final c = p.components, m = p.mean, s = math.sqrt(p.explainedVariance[0]);
}
Output
first component (0.905, 0.426), ratio 0.981
factory Pca.fitArray(NDArray x, {int? k})

Fits the rows of a 2-D NDArray (n \times p, any real dtype).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
import 'package:riptide_numerics_cpu/riptide_numerics_cpu.ray' as np;

void main() {
  final rng = PhiloxStream(3);
  const n = 60;
  final data = Float64List(n * 2);
  for (var i = 0; i < n; i++) {
    final t = rng.nextNormal();
    data[2 * i] = 2 * t + 0.3 * rng.nextNormal();
    data[2 * i + 1] = t + 0.3 * rng.nextNormal();
  }
  final p = Pca.fitArray(np.NDArray.fromTypedData(data, shape: [n, 2]), k: 1);
  print('k = 1: component (${p.components[0].toStringAsFixed(3)}, ${p.components[1].toStringAsFixed(3)})');
}
Output
k = 1: component (0.905, 0.426)

Properties

pfield
final int p
meanfield
final Float64List mean
final Float64List components

k \times p row-major: row i is the i-th principal axis (unit length; largest component positive).

final Float64List explainedVariance
final Float64List explainedVarianceRatio
kgetter
int get k

Methods

transformmethod
Float64List transform(List<double> data, int n)

Projects n rows of p features onto the k components (n \times k).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = PhiloxStream(3);
  const n = 60;
  final data = Float64List(n * 2);
  for (var i = 0; i < n; i++) {
    final t = rng.nextNormal();
    data[2 * i] = 2 * t + 0.3 * rng.nextNormal();
    data[2 * i + 1] = t + 0.3 * rng.nextNormal();
  }
  final p = Pca.fit(data, n, 2);
  final z = p.transform(data, n);
  print('variance of the scores: ${Stats.variance([for (var i = 0; i < n; i++) z[2 * i]], ddof: 1).toStringAsFixed(4)}, ${Stats.variance([for (var i = 0; i < n; i++) z[2 * i + 1]], ddof: 1).toStringAsFixed(4)}');
}
Output
variance of the scores: 5.2017, 0.0984
class

KMeans

final class KMeans

k-means clustering: k-means++ seeding (Arthur and Vassilvitskii 2007) from a Philox stream, then Lloyd iterations; the best of restarts runs by inertia.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:typed_data';
import 'raya:convert';

void main() {
  final rng = PhiloxStream(5);
  const centres = [[0.0, 0.0], [5.0, 5.0], [0.0, 8.0]];
  final pts = Float64List(90 * 2);
  for (var i = 0; i < 90; i++) {
    pts[2 * i] = centres[i ~/ 30][0] + 0.7 * rng.nextNormal();
    pts[2 * i + 1] = centres[i ~/ 30][1] + 0.7 * rng.nextNormal();
  }
  final km = KMeans.fit(pts, 90, 2, 3, seed: 1);
  for (var j = 0; j < 3; j++) {
    print('cluster $j: centre (${km.centroids[2 * j].toStringAsFixed(2)}, ${km.centroids[2 * j + 1].toStringAsFixed(2)}), '
        '${km.labels.where((l) => l == j).length} points');
  }
        for (var j = 0; j < 3; j++)
          {'label': 'cluster $j', 'style': 'points', 'points': [for (var i = 0; i < 90; i++) if (km.labels[i] == j) [pts[2 * i], pts[2 * i + 1]]]}
      ]})}');
}
Output
cluster 0: centre (-0.04, 8.03), 30 points
cluster 1: centre (5.07, 5.11), 30 points
cluster 2: centre (-0.04, -0.12), 30 points

Constructors

KMeans.fitfactory
factory KMeans.fit(List<double> data, int n, int p, int k, {int seed = 0, int restarts = 4, int maxIterations = 300, double tolerance = 1e-10})
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = PhiloxStream(21);
  const c = [[0.0, 0.0], [4.0, 1.0], [2.0, 4.0], [6.0, 5.0]];
  final pts = Float64List(160 * 2);
  for (var i = 0; i < 160; i++) {
    pts[2 * i] = c[i % 4][0] + 0.6 * rng.nextNormal();
    pts[2 * i + 1] = c[i % 4][1] + 0.6 * rng.nextNormal();
  }
  final km = KMeans.fit(pts, 160, 2, 4, seed: 2);
  print('inertia ${km.inertia.toStringAsFixed(2)} after ${km.iterations} iterations');
}
Output
inertia 111.40 after 3 iterations

Properties

final Float64List centroids

k \times p row-major centroids.

labelsfield
final Int32List labels
inertiafield
final double inertia
final int iterations
abstract final class Philox4x32

Philox4x32-10: a 4×32-bit counter and a 2×32-bit key give 4 independent 32-bit words.

Static

m0constant
static const int m0 = 0xD2511F53
m1constant
static const int m1 = 0xCD9E8D57
w0constant
static const int w0 = 0x9E3779B9
w1constant
static const int w1 = 0xBB67AE85
mulhilo16staticmethod
static (int, int) mulhilo16(int a, int b)

The 32 \times 32 → 64-bit product as (hi, lo) using only 16-bit partial products and 32-bit wrapping arithmetic: the fallback a GLSL kernel uses where umulExtended is missing (it is mirrored here so the test pins the method).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final (hi, lo) = Philox4x32.mulhilo16(0xD2511F53, 0x12345678);
  print('hi 0x${hi.toRadixString(16)}, lo 0x${lo.toRadixString(16)}');
  final p = 0xD2511F53 * 0x12345678;
  print('check: ${(p >> 32) & 0xffffffff == hi && p & 0xffffffff == lo}');
}
Output
hi 0xef4b3b8, lo 0x96890e8
check: true
blockstaticmethod
static void block(int c0, int c1, int c2, int c3, int k0, int k1, Uint32List out, [int offset = 0])

One block: writes Philox4x32-10(counter (c_{0}, c_{1}, c_{2}, c_{3}), key (k_{0}, k_{1})) to out[offset..offset+3]. All inputs are taken mod 2^{32}. This is the function a GPU kernel reproduces.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final out = Uint32List(4);
  Philox4x32.block(0, 0, 0, 0, 0, 0, out);
  print('Philox-4x32-10(ctr 0, key 0): ${out.map((v) => v.toRadixString(16).padLeft(8, '0')).toList()}');
  Philox4x32.block(1, 0, 0, 0, 0, 0, out);
  print('counter 1:                    ${out.map((v) => v.toRadixString(16).padLeft(8, '0')).toList()}');
}
Output
Philox-4x32-10(ctr 0, key 0): [6627e8d5, e169c58d, bc57ac4c, 9b00dbd8]
counter 1:                    [f8e4cca4, 5cb200db, b1a574eb, 097eff67]
abstract final class Threefry2x32

Threefry2x32-20: a 2×32-bit counter and a 2×32-bit key give 2 words (Threefish-style add/rotate/xor).

Static

parityconstant
static const int parity = 0x1BD11BDA
blockstaticmethod
static void block(int c0, int c1, int k0, int k1, Uint32List out, [int offset = 0])

One block: writes Threefry2x32-20(counter (c_{0}, c_{1}), key (k_{0}, k_{1})) to outoffset, out[offset+1].

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final out = Uint32List(2);
  Threefry2x32.block(0, 0, 0, 0, out);
  print('Threefry-2x32-20(0, 0): ${out.map((v) => v.toRadixString(16).padLeft(8, '0')).toList()}');
}
Output
Threefry-2x32-20(0, 0): [6b200159, 99ba4efe]
class

U32

abstract final class U32

The exact u32 → floating-point conversions (identical on CPU and GPU: integer shifts and a power-of-two scale).

Static

toFloat01staticmethod
static double toFloat01(int u)

[0, 1) float32: (u > > 8) \cdot 2^{-24}.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  for (final u in [0, 0x80000000, 0xffffffff]) {
    print('0x${u.toRadixString(16).padLeft(8, '0')} -> ${U32.toFloat01(u)}');
  }
}
Output
0x00000000 -> 0.0
0x80000000 -> 0.5
0xffffffff -> 0.9999999403953552
toFloatOpenstaticmethod
static double toFloatOpen(int u)

(0, 1] float32: ((u > > 8) + 1) \cdot 2^{-24} (safe for log).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  print('0 -> ${U32.toFloatOpen(0)}  (never 0)');
  print('max -> ${U32.toFloatOpen(0xffffffff)}  (never 1)');
}
Output
0 -> 5.960464477539063e-8  (never 0)
max -> 1.0  (never 1)
toDouble01staticmethod
static double toDouble01(int a, int b)

[0, 1) double from two words: ((a > > 5) \cdot 2^{26} + (b > > 6)) \cdot 2^{-53}.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  print(U32.toDouble01(0, 0));
  print(U32.toDouble01(0xffffffff, 0xffffffff));
}
Output
0.0
0.9999999999999999
toDoubleOpenstaticmethod
static double toDoubleOpen(int a, int b)

(0, 1] double from two words.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  print(U32.toDoubleOpen(0, 0));
  print(U32.toDoubleOpen(0xffffffff, 0xffffffff));
}
Output
1.1102230246251565e-16
1.0
abstract interface class RandomSource

A source of 32-bit words (the generators below).

Methods

nextU32method
int nextU32()

The next uniformly distributed 32-bit word (0 \cdots 2^{32} - 1).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // Both streams implement RandomSource.
  final List<RandomSource> sources = [PhiloxStream(1), ThreefryStream(1)];
  for (final s in sources) {
    print('${s.runtimeType}: ${[for (var i = 0; i < 3; i++) s.nextU32()]}');
  }
}
Output
PhiloxStream: [3823634032, 3842641596, 2515673792]
ThreefryStream: [3023415290, 2531993477, 247883890]
final class PhiloxStream implements RandomSource

A Philox4x32-10 stream.

Layout: key = (seed low 32 bits, seed high 32 bits); counter = (position low, position high, stream low, stream high). Each block of 4 words advances the 64-bit position by one. A stream is a 64-bit id; for per-element substreams (one per particle per step, say) use PhiloxStream.substream with (a, b) = (element index, step), so a GPU thread computes the same words with block(position, 0, a, b, seedLo, seedHi) and no shared state.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:typed_data';

void main() {
  // A counter-based generator: the same seed gives the same numbers on every machine.
  final rng = PhiloxStream(42);
  print('first words: ${[for (var i = 0; i < 4; i++) rng.nextU32()]}');
  print('same seed again: ${PhiloxStream(42).nextU32()}');
  print('another stream: ${PhiloxStream(42, stream: 1).nextU32()}');
  final xs = Float64List(10000);
  PhiloxStream(7).fillNormal(xs);
  print('normal samples: mean ${Stats.mean(xs).toStringAsFixed(3)}, std ${Stats.std(xs).toStringAsFixed(3)}');
}
Output
first words: [2632642643, 2012563771, 314527917, 1463989207]
same seed again: 2632642643
another stream: 43202409
normal samples: mean 0.015, std 1.021

Constructors

PhiloxStreamconstructor
PhiloxStream(int seed, {int stream = 0})

seed and stream are 64-bit; words are drawn from block position 0 upward.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = PhiloxStream(42), b = PhiloxStream(42), c = PhiloxStream(42, stream: 1);
  print('same seed, same numbers: ${a.nextU32() == b.nextU32()}');
  print('stream 1 differs: ${PhiloxStream(42).nextU32() != c.nextU32()}');
  final r = PhiloxStream(42);
  final pts = [for (var i = 0; i < 300; i++) [r.nextDouble(), r.nextDouble()]];
}
Output
same seed, same numbers: true
stream 1 differs: true
PhiloxStream.substream(int seed, int a, int b)

Stream (a, b) of seed: counter words c_{2} = a, c_{3} = b.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // Independent streams for (worker, task) pairs from one seed.
  for (var w = 0; w < 2; w++) {
    for (var t = 0; t < 2; t++) {
      print('worker $w task $t: ${PhiloxStream.substream(7, w, t).nextDouble().toStringAsFixed(6)}');
    }
  }
}
Output
worker 0 task 0: 0.954597
worker 0 task 1: 0.838473
worker 1 task 0: 0.495040
worker 1 task 1: 0.532841

Properties

k0field
final int k0
k1field
final int k1
s0field
final int s0
s1field
final int s1
positiongetter
int get position

The block position the next refill uses (a 64-bit counter).

Methods

seekmethod
void seek(int position)

Jumps to block position, discarding buffered words.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final r = PhiloxStream(2024);
  final first = [for (var i = 0; i < 6; i++) r.nextU32()];
  r.seek(4);
  print('after seek(4): ${r.nextU32() == first[4]} ${r.nextU32() == first[5]}');
}
Output
after seek(4): false false
nextU32method
int nextU32()
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final r = PhiloxStream(2024);
  print([for (var i = 0; i < 4; i++) r.nextU32()]);
}
Output
[2592828275, 1153470534, 4228819385, 359042194]
double nextDouble()

A uniform double in [0, 1) (two words).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final r = PhiloxStream(2024);
  final s = [for (var i = 0; i < 10000; i++) r.nextDouble()];
  print('mean ${Stats.mean(s).toStringAsFixed(4)} (0.5), variance ${Stats.variance(s).toStringAsFixed(4)} (1/12 = 0.0833)');
}
Output
mean 0.5015 (0.5), variance 0.0836 (1/12 = 0.0833)
double nextDoubleOpen()

A uniform double in (0, 1] (two words).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final r = PhiloxStream(2024);
  final s = [for (var i = 0; i < 100000; i++) r.nextDoubleOpen()];
  print('min ${s.reduce(math.min) > 0}, safe for log: ${s.map(math.log).every((v) => v.isFinite)}');
}
Output
min true, safe for log: true
nextFloatmethod
double nextFloat()

A uniform float32 value in [0, 1) (one word), returned as a double.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final r = PhiloxStream(2024);
  print([for (var i = 0; i < 4; i++) r.nextFloat()]);
}
Output
[0.6036898493766785, 0.26856327056884766, 0.984598696231842, 0.08359599113464355]
double nextNormal()

A standard normal by the Box–Muller transform on two open uniforms; values come in pairs (the second is cached).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final r = PhiloxStream(2024);
  final s = Float64List.fromList([for (var i = 0; i < 5000; i++) r.nextNormal()]);
  print('mean ${Stats.mean(s).toStringAsFixed(3)}, std ${Stats.std(s).toStringAsFixed(3)}');
  final (c, e) = Stats.histogram(s, 24, range: (-4, 4));
}
Output
mean 0.005, std 1.008
nextIntmethod
int nextInt(int n)

An integer uniform in [0, n) without modulo bias (Lemire's multiply-shift with rejection), n \le 2^{32}.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final r = PhiloxStream(2024);
  final counts = List<int>.filled(6, 0);
  for (var i = 0; i < 6000; i++) {
    counts[r.nextInt(6)]++;
  }
  print('die faces: $counts');
}
Output
die faces: [1037, 993, 993, 1029, 952, 996]
void fillUniform(Float64List out)

Fills out with uniform doubles in [0, 1).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final r = PhiloxStream(2024);
  final out = Float64List(5);
  r.fillUniform(out);
  print(out);
}
Output
[0.6036898737293727, 0.9845987341075839, 0.34628420647900005, 0.8978964497441596, 0.5752686414814819]
void fillUniformF32(Float32List out)

Fills out with float32 uniforms in [0, 1) (one word each: the GPU-identical conversion).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final r = PhiloxStream(2024);
  final out = Float32List(5);
  r.fillUniformF32(out);
  print(out);
}
Output
[0.6036898493766785, 0.26856327056884766, 0.984598696231842, 0.08359599113464355, 0.3462841510772705]
void fillNormal(Float64List out, {double mean = 0, double std = 1})

Fills out with standard normals (Box–Muller).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final r = PhiloxStream(2024);
  final out = Float64List(4000);
  r.fillNormal(out, mean: 10, std: 2);
  print('mean ${Stats.mean(out).toStringAsFixed(3)}, std ${Stats.std(out).toStringAsFixed(3)}');
}
Output
mean 10.010, std 2.016
void fillNormalF32(Float32List out, {double mean = 0, double std = 1})

Fills out with float32 standard normals by Box–Muller on float32 uniforms (one word per uniform), the formula a GPU kernel evaluates; transcendental functions may differ by an ulp between CPU and GPU.

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final r = PhiloxStream(2024);
  final out = Float32List(6);
  r.fillNormalF32(out);
  print(out.map((v) => v.toStringAsFixed(4)).toList());
}
Output
[-0.1169, 0.9979, 0.1524, 0.0883, -1.3398, 0.5709]
fillU32method
void fillU32(Uint32List out)

Fills out with raw words, block by block (what a GPU kernel writes for the same seed and stream).

Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final r = PhiloxStream(2024);
  final out = Uint32List(4);
  r.fillU32(out);
  print(out);
}
Output
[2592828275, 1153470534, 4228819385, 359042194]
final class ThreefryStream implements RandomSource

A Threefry2x32-20 stream: key = seed, counter = (position, stream).

Constructors

ThreefryStreamconstructor
ThreefryStream(int seed, {int stream = 0})
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final t = ThreefryStream(9);
  print('first draws: ${[for (var i = 0; i < 3; i++) t.nextDouble().toStringAsFixed(6)]}');
  print('stream 2: ${ThreefryStream(9, stream: 2).nextDouble().toStringAsFixed(6)}');
}
Output
first draws: [0.684154, 0.863381, 0.174206]
stream 2: 0.048245

Properties

k0field
final int k0
k1field
final int k1
sfield
final int s

Methods

nextU32method
int nextU32()
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final t = ThreefryStream(1);
  print([for (var i = 0; i < 4; i++) t.nextU32()]);
}
Output
[3023415290, 2531993477, 247883890, 763684785]
double nextDouble()
Example
import 'package:riptide_numerics_stats/riptide_numerics_stats.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final t = ThreefryStream(1);
  final s = [for (var i = 0; i < 10000; i++) t.nextDouble()];
  print('mean ${Stats.mean(s).toStringAsFixed(4)}');
}
Output
mean 0.5010