random v5.3.0
random
Seedable random number generator supporting many common distributions.
Welcome to the most random module on npm! 😜
Highlights
- Simple TS API with zero dependencies
- Seedable
- Plugin support for different pseudo random number generators
- Includes many common distributions
- uniform, normal, poisson, bernoulli, etc
- Replacement for
seedrandomwhich hasn't been updated in over 5 years - Supports all modern JS/TS runtimes
Install
npm install randomUsage
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
// uniform distribution
random.uniform((min = 0), (max = 1)) // () => [ min, max )
random.uniformInt((min = 0), (max = 1)) // () => [ min, max ]
random.uniformBoolean() // () => [ false, true ]
// normal distribution
random.normal((mu = 0), (sigma = 1))
random.logNormal((mu = 0), (sigma = 1))
// bernoulli distribution
random.bernoulli((p = 0.5))
random.binomial((n = 1), (p = 0.5))
random.geometric((p = 0.5))
// poisson distribution
random.poisson((lambda = 1))
random.exponential((lambda = 1))
// misc distribution
random.irwinHall(n)
random.bates(n)
random.pareto(alpha)For convenience, several common uniform samplers are exposed directly:
random.float() // 0.2149383367670885
random.int(0, 100) // 72
random.boolean() // true
// random array item
random.choice([1, true, 'foo']) // 'foo'
// shuffle arrays
random.shuffle([1, true, 'foo']) // ['foo', 1, true]
const dist = random.shuffler([1, true, 'foo'])
dist() // [true, 'foo', 1]
dist() // ['foo', true, 1]
dist() // [1, 'foo', true]All distribution methods return a thunk (function with no params), which will return a series of independent, identically distributed random variables from the specified distribution.
// create a normal distribution with default params (mu=1 and sigma=0)
const normal = random.normal()
normal() // 0.4855465422678824
normal() // -0.06696771815439678
normal() // 0.7350852689834705
// create a poisson distribution with default params (lambda=1)
const poisson = random.poisson()
poisson() // 0
poisson() // 4
poisson() // 1Note that returning a thunk here is more efficient when generating multiple samples from the same distribution.
You can change the underlying PRNG or its seed as follows:
// change the underlying pseudo random number generator seed.
// by default, Math.random is used as the underlying PRNG, but it is not seedable,
// so if a seed is given, we use an ARC4 PRNG (the same one used by `seedrandom`).
random.use('my-seed')
// create a new independent random number generator with a different seed
const rng = random.clone('my-new-seed')
// create a third independent random number generator using a custom PRNG
import seedrandom from 'seedrandom'
const rng2 = random.clone(seedrandom('kitty-seed'))You can also instantiate a fresh instance of Random:
import { Random } from 'random'
const rng = new Random() // (uses Math.random)
const rng2 = new Random('my-seed-string')
const rng3 = new Random(() => {
/* custom PRNG */ return Math.random()
})API
Table of Contents
Random
Seedable random number generator supporting many common distributions.
Defaults to Math.random as its underlying pseudorandom number generator.
Type: function (rng)
rng(RNG | function) Underlying pseudorandom number generator. (optional, defaultMath.random)
rng
Type: function ()
clone
- See: RNG.clone
Creates a new Random instance, optionally specifying parameters to
set a new seed.
Type: function (args, seed, opts): Random
use
Sets the underlying pseudorandom number generator used via
either an instance of seedrandom, a custom instance of RNG
(for PRNG plugins), or a string specifying the PRNG to use
along with an optional seed and opts to initialize the
RNG.
Type: function (args)
args...any
Example:
import random from 'random'
random.use('example_seedrandom_string')
// or
random.use(seedrandom('kittens'))
// or
random.use(Math.random)next
Convenience wrapper around this.rng.next()
Returns a floating point number in [0, 1).
Type: function (): number
float
Samples a uniform random floating point number, optionally specifying lower and upper bounds.
Convence wrapper around random.uniform()
Type: function (min, max): number
minnumber Lower bound (float, inclusive) (optional, default0)maxnumber Upper bound (float, exclusive) (optional, default1)
int
Samples a uniform random integer, optionally specifying lower and upper bounds.
Convence wrapper around random.uniformInt()
Type: function (min, max): number
minnumber Lower bound (integer, inclusive) (optional, default0)maxnumber Upper bound (integer, inclusive) (optional, default1)
integer
Samples a uniform random integer, optionally specifying lower and upper bounds.
Convence wrapper around random.uniformInt()
Type: function (min, max): number
minnumber Lower bound (integer, inclusive) (optional, default0)maxnumber Upper bound (integer, inclusive) (optional, default1)
bool
Samples a uniform random boolean value.
Convence wrapper around random.uniformBoolean()
Type: function (): boolean
boolean
Samples a uniform random boolean value.
Convence wrapper around random.uniformBoolean()
Type: function (): boolean
choice
Returns an item chosen uniformly at random from the given array.
Convence wrapper around random.uniformInt()
Type: function choice <T> (array: Array<T>): T | undefined
arrayArray Array of items to sample from
uniform
Generates a Continuous uniform distribution.
Type: function (min, max): function
minnumber Lower bound (float, inclusive) (optional, default0)maxnumber Upper bound (float, exclusive) (optional, default1)
uniformInt
Generates a Discrete uniform distribution.
Type: function (min, max): function
minnumber Lower bound (integer, inclusive) (optional, default0)maxnumber Upper bound (integer, inclusive) (optional, default1)
uniformBoolean
Generates a Discrete uniform distribution,
with two possible outcomes, true or false.
This method is analogous to flipping a coin.
Type: function (): function
normal
Generates a Normal distribution.
Type: function (mu, sigma): function
logNormal
Generates a Log-normal distribution.
Type: function (mu, sigma): function
munumber Mean of underlying normal distribution (optional, default0)sigmanumber Standard deviation of underlying normal distribution (optional, default1)
bernoulli
Generates a Bernoulli distribution.
Type: function (p): function
pnumber Success probability of each trial. (optional, default0.5)
binomial
Generates a Binomial distribution.
Type: function (n, p): function
nnumber Number of trials. (optional, default1)pnumber Success probability of each trial. (optional, default0.5)
geometric
Generates a Geometric distribution.
Type: function (p): function
pnumber Success probability of each trial. (optional, default0.5)
poisson
Generates a Poisson distribution.
Type: function (lambda): function
lambdanumber Mean (lambda > 0) (optional, default1)
exponential
Generates an Exponential distribution.
Type: function (lambda): function
lambdanumber Inverse mean (lambda > 0) (optional, default1)
irwinHall
Generates an Irwin Hall distribution.
Type: function (n): function
nnumber Number of uniform samples to sum (n >= 0) (optional, default1)
bates
Generates a Bates distribution.
Type: function (n): function
nnumber Number of uniform samples to average (n >= 1) (optional, default1)
pareto
Generates a Pareto distribution.
Type: function (alpha): function
alphanumber Alpha (optional, default1)
weibull
Generates a Weibull distribution.
Type: function (lambda, k): function
Todo
Distributions
- uniform
- uniformInt
- uniformBoolean
- normal
- logNormal
- chiSquared
- cauchy
- fischerF
- studentT
- bernoulli
- binomial
- negativeBinomial
- geometric
- poisson
- exponential
- gamma
- hyperExponential
- weibull
- beta
- laplace
- irwinHall
- bates
- pareto
Generators
- pluggable prng
- port more prng from boost / seedrandom
Related
- d3-random - D3's excellent random number generation library.
- seedrandom - Seedable pseudo random number generator.
- random-int - For the common use case of generating uniform random ints.
- random-float - For the common use case of generating uniform random floats.
- randombytes - Random crypto bytes for Node.js and the browser.
- jshash prngs
Credit
Thanks go to Andrew Moss for the TypeScript port and for helping to maintain this package.
Shoutout to Roger Combs for donating the random npm package for this project!
Lots of inspiration from d3-random (@mbostock and @svanschooten).
Some distributions and PRNGs are ported from C++ boost::random.
License
MIT © Travis Fischer
Support my OSS work by following me on twitter
8 months ago
8 months ago
1 year ago
1 year ago
1 year ago
1 year ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
14 years ago
14 years ago
14 years ago