random

repository·master·Indexed 42 days ago

https://github.com/transitive-bullshit/random

A seedable random number generator supporting many common probability distributions, including uniform, normal, poisson, bernoulli, and more. Version 5.5.1 serves as a modern, dependency-free replacement for seedrandom, featuring distribution thunks for efficient sampling and utilities for picking, sampling, and shuffling arrays.

Tokens
6K
Snippets
24
Records
24
Agent score
53%

What's inside random

  1. Generate samples using distribution thunks

    master

    Most distribution methods in random return a thunk (a function with no parameters). Calling this thunk returns a series of independent, identically distributed random variables. This pattern is more efficient when generating multiple samples from the same distribution.

    Supported Distributions

    Uniform Distributions (return thunks):

    • random.uniform(min, max): [min, max)
    • random.uniformInt(min, max): [min, max]
    • random.uniformBoolean(): [false, true]

    Normal Distributions (return thunks):

    • random.normal(mu, sigma)
    • random.logNormal(mu, sigma)

    Bernoulli Distributions (return thunks):

    • random.bernoulli(p)
    • random.binomial(n, p)
    • random.geometric(p)

    Poisson Distributions (return thunks):

    • random.poisson(lambda)
    • random.exponential(lambda)

    Misc Distributions (return thunks):

    • random.irwinHall(n)
    • random.bates(n)
    • random.pareto(alpha)
    // create a normal distribution with default params (mu=0 and sigma=1)
    const normal = random.normal()
    normal() // 0.4855465422678824
    normal() // -0.06696771815439678
    
    // create a poisson distribution with default params (lambda=1)
    const poisson = random.poisson()
    poisson() // 0
    poisson() // 4
  2. How distributions and thunks work in Random

    master

    Most distribution methods in the Random class (like normal(), poisson(), or uniform()) do not return a value immediately. Instead, they return a thunk (a function).

    When you call the distribution method, you are configuring the distribution. When you call the resulting function, you are sampling a single value from that distribution. This allows the library to memoize the distribution configuration for efficiency.

    Pattern:

    1. Call random.distribution(params) to get a sampler.
    2. Call the sampler sampler() to get a value.
    import random from 'random';
    
    // 1. Configure the distribution (returns a thunk)
    const normalSampler = random.normal(0, 1);
    
    // 2. Sample values using the thunk
    const value1 = normalSampler();
    const value2 = normalSampler();
  3. Use the random package entrypoint

    master

    The random package provides a collection of random data generators, random number generators (RNG), and utility functions. You can import the default export for the main random object or import specific generators and utilities directly from the package.

    Commonly exported modules include:

    • Generators (e.g., strings, numbers, booleans, arrays, objects)
    • RNG (Random Number Generators)
    • Types and Utilities
    import random from 'random';
    // or
    import { string, number, boolean } from 'random';
  4. Use quick uniform shortcuts

    master

    For simple, one-off random values, use the direct shortcut methods. These return values immediately rather than returning a thunk.

    • random.float(min, max): Returns a uniform float in the range [min, max).
    • random.int(min, max): Returns a uniform integer in the range [min, max].
    • random.boolean(): Returns true or false.
    import random from 'random'
    
    // quick uniform shortcuts
    random.float((min = 0), (max = 1)) // uniform float in [ min, max )
    random.int((min = 0), (max = 1)) // uniform integer in [ min, max ]
    random.boolean() // true or false
  5. Seed and configure the random number generator

    master

    By default, random uses Math.random(), which is not seedable. If a seed is provided, it uses xoshiro128**.

    Global Configuration

    Use random.use(seed) to change the seed for the global instance.

    Creating Independent Instances

    • random.clone(seedOrPrng): Creates a new independent generator with a specific seed or a custom PRNG.
    • new Random(seedOrPrng): Manually instantiate a Random class instance.

    Custom PRNGs and Stability

    For cryptographic purposes, do not use these generators. For simulation stability across major versions, explicitly choose your RNG engine:

    • Xoshiro128StarStarRNG: A high-quality generator.
    • ARC4RNG: Used to reproduce legacy seeded sequences from random v5 and seedrandom.

    Note: seedOrPrng can be a string (for seeding) or a function () => number (for a custom PRNG).

    import { Random, Xoshiro128StarStarRNG, ARC4RNG } from 'random'
    
    // change the underlying pseudo random number generator seed globally
    random.use('my-seed')
    
    // create a new independent random number generator with a different seed
    const rng = random.clone('my-new-seed')
    
    // instantiate a fresh instance of Random
    const rng2 = new Random('my-seed-string')
    const rng3 = new Random(() => Math.random())
    
    // For stable sequences, use explicit engines
    const stableRng = new Random(new Xoshiro128StarStarRNG('my-seed'))
    
    // Reproduce legacy sequences (v5/seedrandom)
    const legacyRng = new Random(new ARC4RNG('my-seed'))
  6. Pick a random item from an array with choice()

    master

    The choice() method returns an item chosen uniformly at random from the provided array. You can optionally provide an array of weights to make certain items more likely to be picked. The weights array must be the same length as the input array.

    const items = ['apple', 'banana', 'cherry'];
    const weights = [1, 10, 1]; // banana is much more likely
    const picked = random.choice(items, weights);
  7. Pick, sample, and shuffle arrays

    master

    The random module provides utilities for working with arrays:

    • random.choice(array, weights?): Picks a random item from an array. If weights is provided, it performs weighted selection.
    • random.sample(array, k): Returns an array of k items sampled from the input array without replacement.
    • random.sampler(array, k): Returns a thunk that, when called, returns a sample of k items without replacement.
    • random.shuffle(array): Shuffles the input array in place.
    • random.shuffler(array): Returns a thunk that, when called, returns a shuffled version of the array.
    import random from 'random'
    
    // random array item
    random.choice([1, true, 'foo']) // 'foo'
    
    // random array item with weights
    random.choice([1, true, 'foo'], [8, 1, 1]) // 1 (80% of the time)
    
    // sample multiple items without replacement
    random.sample([1, true, 'foo'], 2) // [true, 'foo']
    
    const dist = random.sampler([1, true, 'foo'], 2)
    dist() // [true, 'foo']
    
    // shuffle arrays
    random.shuffle([1, true, 'foo']) // ['foo', 1, true]
    
    const distShuffler = random.shuffler([1, true, 'foo'])
    distShuffler() // [true, 'foo', 1]
  8. Sample uniform distributions (float, int, boolean)

    master

    These methods are convenience wrappers for sampling from uniform distributions:

    • float(min, max): Samples a uniform random floating point number between min (inclusive, default 0) and max (exclusive, default 1).
    • int(min, max): Samples a uniform random integer between min (inclusive, default 0) and max (inclusive, default 1).
    • boolean(): Samples a uniform random boolean value (analogous to a coin flip).
    random.float(0, 10); // float between 0 and 10
    random.int(1, 100);   // integer between 1 and 100
    random.boolean();     // true or false
  9. Create a new Random instance with clone()

    master

    Use clone() to create a new Random instance. This is useful for branching off a specific state or setting new parameters. You can optionally specify a seed (string) and opts (object) to initialize the new RNG.

    // Signature: clone(args, seed, opts)
    const newRandom = random.clone(args, 'optional_seed', { optional: 'config' });
  10. Generate various statistical distributions

    master

    The random library provides factory functions to generate samplers for many common statistical distributions. Calling these functions returns a function that, when executed, produces a sample from that distribution.

    Continuous Distributions

    • uniform(min, max): Continuous uniform distribution.
    • normal(mu, sigma): Normal distribution with mean mu and standard deviation sigma.
    • logNormal(mu, sigma): Log-normal distribution.
    • exponential(lambda): Exponential distribution with inverse mean lambda.
    • irwinHall(n): Irwin Hall distribution (sum of n uniform samples).
    • bates(n): Bates distribution (average of n uniform samples).
    • pareto(alpha): Pareto distribution with parameter alpha.
    • weibull(lambda, k): Weibull distribution with scale lambda and shape k.

    Discrete Distributions

    • uniformInt(min, max): Discrete uniform distribution.
    • uniformBoolean(): Discrete uniform distribution with two outcomes (true/false).
    • bernoulli(p): Bernoulli distribution with success probability p.
    • binomial(n, p): Binomial distribution with n trials and success probability p.
    • geometric(p): Geometric distribution with success probability p.
    • poisson(lambda): Poisson distribution with mean lambda.
    // Example: Create a normal distribution sampler
    const normalSampler = random.normal(0, 1);
    const sample = normalSampler();
    
    // Example: Create a Poisson distribution sampler
    const poissonSampler = random.poisson(5);
    const count = poissonSampler();
  11. Configure the underlying PRNG with use()

    master

    The use() method allows you to set the underlying pseudorandom number generator (PRNG) used by the random instance. You can provide an instance of seedrandom, a custom RNG instance (for PRNG plugins), or a string specifying the PRNG to use along with optional seed and opts to initialize it. By default, the library uses Math.random.

    import random from 'random'
    
    random.use('example_seedrandom_string')
    // or
    random.use(seedrandom('kittens'))
    // or
    random.use(Math.random)