d3-random is a JavaScript library that provides functions for generating random numbers from various statistical distributions. Part of the D3.js ecosystem, it offers high-quality pseudorandom number generation with support for seeded random number generators, making it suitable for reproducible statistical simulations, data visualization, Monte Carlo methods, and scientific computing applications.
npm install d3-randomES6 modules:
import { randomUniform, randomNormal, randomLcg } from "d3-random";Specific imports:
import { randomUniform } from "d3-random";
import { randomNormal } from "d3-random";CommonJS (legacy):
const { randomUniform, randomNormal } = require("d3-random");UMD global (legacy browsers):
<script src="https://cdn.jsdelivr.net/npm/d3-random@3"></script>
<script>
const random = d3.randomUniform(1, 10);
</script>import { randomUniform, randomNormal, randomLcg } from "d3-random";
// Basic uniform random numbers
const uniform = randomUniform(0, 100);
console.log(uniform()); // Random number between 0 and 100
// Normal distribution
const normal = randomNormal(50, 10); // mean=50, stddev=10
console.log(normal()); // Normally distributed random number
// Using custom seeded generator for reproducible results
const seed = 0.44871573888282423;
const seededRandom = randomNormal.source(randomLcg(seed))(0, 1);
console.log(seededRandom()); // Always produces the same sequenced3-random is built around several key patterns:
.source(source) method for custom random number generatorsrandomLcg provides deterministic pseudorandom sequences for reproducible resultsCommon statistical distributions for general-purpose random number generation, including uniform, normal, and integer distributions.
function randomUniform(min?: number, max?: number): () => number;
function randomInt(min?: number, max?: number): () => number;
function randomNormal(mu?: number, sigma?: number): () => number;Specialized statistical distributions for scientific computing and advanced simulations, including gamma, beta, Weibull, and other continuous and discrete distributions.
function randomGamma(k: number, theta?: number): () => number;
function randomBeta(alpha: number, beta: number): () => number;
function randomWeibull(k: number, a?: number, b?: number): () => number;
function randomPoisson(lambda: number): () => number;Utilities for creating reproducible random number sequences using linear congruential generators and custom random sources.
function randomLcg(seed?: number): () => number;
// Source method pattern (available on all distribution functions)
interface RandomFunction {
source(source: () => number): RandomFunction;
}// Generator function returned by all distribution functions
type RandomGenerator = () => number;
// Random source function (compatible with Math.random)
type RandomSource = () => number;
// Distribution function with source method
interface DistributionFunction extends Function {
source(source: RandomSource): DistributionFunction;
}