GitHub
deepbox/random

Distributions

Sample from common probability distributions. All functions return Tensors of the requested shape. Samples are drawn using seeded PRNGs — set a seed via setSeed() for full reproducibility. Continuous distributions use Box-Muller and inverse-CDF transforms; discrete distributions use direct sampling.
uniform
uniform(low: number, high: number, shape: Shape): Tensor

Sample from the continuous uniform distribution U(low, high). Every value in [low, high) is equally likely. PDF: f(x) = 1/(high − low) for x ∈ [low, high). Mean = (low + high)/2, Variance = (high − low)²/12.

Parameters:
low: number - Lower bound (inclusive)
high: number - Upper bound (exclusive)
shape: Shape - Output tensor shape
normal
normal(mean: number, std: number, shape: Shape): Tensor

Sample from the normal (Gaussian) distribution N(μ, σ²). Uses the Box-Muller transform for generation. The bell curve — 68% of values fall within ±1σ of the mean, 95% within ±2σ, 99.7% within ±3σ.

Parameters:
mean: number - Mean (μ) — center of the distribution
std: number - Standard deviation (σ) — spread. Must be > 0.
rand
rand(shape: Shape, opts?: RandomOptions): Tensor

Random floats uniformly distributed in [0, 1). Shorthand for uniform(0, 1, shape). The most basic random tensor — use it for random masks, dropout, and Monte Carlo sampling.

randn
randn(shape: Shape, opts?: RandomOptions): Tensor

Random floats from the standard normal distribution N(0, 1). Shorthand for normal(0, 1, shape). Used for Gaussian noise injection, weight initialization (Xavier/He), and generative models.

binomial
binomial(n: number, p: number, shape: Shape): Tensor

Sample from the binomial distribution B(n, p). Each sample counts the number of successes in n independent Bernoulli trials, each with success probability p. PMF: P(k) = C(n,k) · pᵏ · (1−p)ⁿ⁻ᵏ. Mean = np, Variance = np(1−p). When n=1, this is a Bernoulli distribution.

Parameters:
n: number - Number of trials (positive integer)
p: number - Probability of success per trial, in [0, 1]
poisson
poisson(lambda: number, shape: Shape): Tensor

Sample from the Poisson distribution with rate λ. Models the number of events occurring in a fixed time interval when events happen independently at a constant average rate. PMF: P(k) = λᵏe⁻λ / k!. Mean = Variance = λ. Approximates B(n,p) when n is large and p is small.

Parameters:
lambda: number - Average rate of events (λ > 0)
exponential
exponential(lambda: number, shape: Shape): Tensor

Sample from the exponential distribution with rate λ. Models the waiting time until the next Poisson event. The only memoryless continuous distribution — P(X > s+t | X > s) = P(X > t). PDF: f(x) = λe⁻λˣ for x ≥ 0. Mean = 1/λ, Variance = 1/λ².

Parameters:
lambda: number - Rate parameter (λ > 0). Higher λ → shorter waiting times.
gamma
gamma(alpha: number, beta: number, shape: Shape): Tensor

Sample from the gamma distribution Γ(α, β). Generalizes the exponential (α=1) and chi-squared (α=k/2, β=0.5) distributions. PDF: f(x) = βᵅ xᵅ⁻¹ e⁻βˣ / Γ(α) for x > 0. Mean = α/β, Variance = α/β². Used as a conjugate prior in Bayesian statistics.

Parameters:
alpha: number - Shape parameter (α > 0). Controls the skewness.
beta: number - Rate parameter (β > 0). Inverse of the scale.
beta
beta(alpha: number, beta: number, shape: Shape): Tensor

Sample from the beta distribution Beta(α, β). Values are always in (0, 1), making it natural for modeling probabilities, proportions, and rates. PDF: f(x) = xᵅ⁻¹(1−x)ᵝ⁻¹ / B(α,β). Mean = α/(α+β). When α=β=1, this is uniform; when α=β>1, it is bell-shaped; when α≠β, it is skewed.

Parameters:
alpha: number - Shape parameter α > 0. Larger α → more weight near 1.
beta: number - Shape parameter β > 0. Larger β → more weight near 0.
randint
randint(low: number, high: number, shape: Shape): Tensor

Random integers uniformly distributed in [low, high). Each integer in the range is equally likely with probability 1/(high − low). Output dtype is int32. Useful for random indexing, label generation, and discrete sampling.

Parameters:
low: number - Lower bound (inclusive, integer)
high: number - Upper bound (exclusive, integer)
permutation
permutation(x: Tensor | number): Tensor

Generate a random permutation. If x is a number n, returns a random permutation of [0, 1, ..., n−1]. If x is a 1D Tensor, returns a new tensor with elements shuffled in random order (does not mutate the input). Uses the Fisher-Yates algorithm for O(n) uniform shuffling.

Parameters:
x: Tensor | number - Length of permutation or tensor to shuffle
choice
choice(a: Tensor, size: number, replace?: boolean, p?: Tensor): Tensor

Draw a random sample from a 1D tensor. With replace=true (default), the same element can appear multiple times (bootstrap sampling). With replace=false, elements are drawn without replacement (like dealing cards). Provide p for weighted sampling — p must sum to 1.

Parameters:
a: Tensor - 1D source tensor to sample from
size: number - Number of items to draw
replace: boolean - Sample with replacement (default: true)
p: Tensor - Probability weights for each element (must sum to 1)
shuffle
shuffle(x: Tensor): void

Shuffle elements of a tensor in place using the Fisher-Yates algorithm. This is the ONLY mutating operation in deepbox/ndarray — all other tensor operations return new tensors. O(n) time, O(1) extra space.

Parameters:
x: Tensor - Tensor to shuffle in place

Normal PDF

f(x) = (1 / σ√(2π)) · e^(−(x−μ)² / 2σ²)

Where:

  • μ = Mean (center)
  • σ = Standard deviation (spread)

Binomial PMF

P(k) = C(n,k) · pᵏ · (1−p)ⁿ⁻ᵏ

Where:

  • n = Number of trials
  • p = Success probability

Poisson PMF

P(k) = λᵏ e⁻λ / k!

Where:

  • λ = Rate parameter (mean = variance = λ)

Exponential PDF

f(x) = λ e⁻λˣ for x ≥ 0

Where:

  • λ = Rate parameter (mean = 1/λ)

Gamma PDF

f(x) = βᵅ xᵅ⁻¹ e⁻βˣ / Γ(α)

Where:

  • α = Shape (controls skewness)
  • β = Rate (inverse scale)

Beta PDF

f(x) = xᵅ⁻¹ (1−x)ᵝ⁻¹ / B(α, β)

Where:

  • B(α,β) = Beta function (normalizing constant)
distributions.ts
import { rand, randn, uniform, normal, binomial, poisson, exponential, gamma, beta, randint, permutation, choice, setSeed } from "deepbox/random";import { tensor } from "deepbox/ndarray";setSeed(42); // All calls below are deterministic// ── Quick random tensors ──const r = rand([3, 3]);        // Uniform [0, 1)const n = randn([100]);         // Standard normal N(0, 1)// ── Parametric continuous distributions ──const u = uniform(0, 10, [3, 3]);   // U(0, 10)const g = normal(5, 2, [1000]);      // N(μ=5, σ=2)const exp = exponential(0.5, [100]); // Exp(λ=0.5), mean = 2const gam = gamma(2, 1, [100]);      // Γ(α=2, β=1)const b = beta(2, 5, [100]);         // Beta(2, 5), mean ≈ 0.286// ── Discrete distributions ──const coin = binomial(10, 0.5, [100]); // 10 coin flips × 100const events = poisson(3, [100]);       // Poisson arrivals, λ=3const ints = randint(0, 10, [5]);       // Random integers [0, 10)// ── Sampling utilities ──const perm = permutation(10);                          // Random order of 0..9const data = tensor([10, 20, 30, 40, 50]);const sample = choice(data, 3, false);                 // 3 unique elementsconst weighted = choice(data, 3, true, tensor([0.5, 0.3, 0.1, 0.05, 0.05]));

When to Use

  • uniform / rand — Weight initialization (uniform Glorot), random masks, Monte Carlo integration
  • normal / randn — Gaussian noise injection, He/Xavier weight init, variational autoencoders, diffusion models
  • binomial — A/B testing simulation, dropout mask generation, counting success events
  • poisson — Modeling count data (website visits, particle decay, customer arrivals per hour)
  • exponential — Waiting times, survival analysis, queuing theory, reliability engineering
  • gamma — Bayesian conjugate prior for rates, modeling right-skewed positive data (income, insurance claims)
  • beta — Modeling probabilities and proportions, Bayesian prior for Bernoulli/binomial parameters, A/B test posterior
  • permutation — Shuffling dataset indices for cross-validation splits
  • choice — Bootstrap resampling (replace=true), stratified sampling (replace=false, weighted)