This is designed to be a mathematically correct random number generator library for JavaScript.
Inspiration was primarily taken from C++11's <random>
.
Despite Math.random()
being capable of producing numbers within [0, 1), there are a few downsides to doing so:
- It is inconsistent between engines as to how many bits of randomness:
- Internet Explorer: 53 bits
- Mozilla Firefox: 53 bits
- Google Chrome/node.js: 32 bits
- Apple Safari: 32 bits
- It is non-deterministic, which means you can't replay results consistently
- In older browsers, there can be manipulation through cross-frame random polling. This is mostly fixed in newer browsers and is required to be fixed in ECMAScript 6.
Also, and most crucially, most developers tend to use improper and biased logic as to generating integers within a uniform distribution.
Random.js provides a set of "engines" for producing random integers, which consistently provide values within [0, 4294967295], i.e. 32 bits of randomness.
nativeMath
: UtilizesMath.random()
and converts its result to an unsigned integer. This is appropriate to use if you do not care for a deterministic implementation. Based on the implementation (which is hidden to you as a developer), the period may be shorter than expected and start repeating itself.browserCrypto
: Utilizescrypto.getRandomValues(Uint32Array)
. Only supported on newer browsers, but promises cryptographically random numbers.mt19937()
: An implementation of the Mersenne Twister algorithm. Not cryptographically secure, but its results are repeatable. Must be seeded with a single integer or an array of integers or call.autoSeed()
to automatically seed initial data. Guaranteed to produce consistent results across all JavaScript implementations assuming the same seed.
One is also free to implement their own engine as long as it returns 32-bit integers, either signed or unsigned.
Some common, biased, incorrect tool for generating random integers is as follows:
// DO NOT USE, BIASED LOGIC
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
// DO NOT USE, BIASED LOGIC (typical C-like implementation)
function randomIntByModulo(min, max) {
var i = (Math.random() * 32768) >>> 0;
return (i % (min - max)) + min;
}
The problem with both of these approaches is that the distribution of integers that it returns is not uniform. That is, it might be more biased to return 0
rather than 1
, making it inherently broken.
randomInt
may more evenly distribute its biased, but it is still wrong. randomIntByModulo
, at least in the example given, is heavily biased to return [0, 67] over [68, 99].
In order to eliminate bias, sometimes the engine which random data is pulled from may need to be used more than once.
Random.js provides a series of distributions to alleviate this.
Random.engines.nativeMath
: UtilizesMath.random()
Random.engines.browserCrypto
: Utilizescrypto.getRandomValues()
Random.engines.mt19937()
: Produces a new Mersenne Twister. Must be seeded before use.
Assuming one has done var mt = Random.engines.mt19937()
:
mt()
: Produce a 32-bit unsigned integer.mt.seed(value)
: Seed the twister with an initial 32-bit integer.mt.seedWithArray(array)
: Seed the twister with an array of 32-bit integers.mt.autoSeed()
: Seed the twister with automatic information. This uses the current Date and other entropy sources.mt.discard(count)
: Discardcount
random values. More efficient than runningmt()
repeatedly.
Random.js also provides a set of methods for producing useful data from an engine.
Random.integer(min, max)(engine)
: Produce an integer within the inclusive range [min
,max
].min
can be at its minimum -9007199254740992 (-2 ** 53).max
can be at its maximum 9007199254740992 (2 ** 53).Random.real(min, max, inclusive)(engine)
: Produce a floating point number within the range [min
,max
) or [min
,max
]. Uses 53 bits of randomness.Random.bool()(engine)
: Produce a boolean with a 50% chance of it beingtrue
.Random.bool(percentage)(engine)
: Produce a boolean with the specified chance causing it to betrue
.Random.bool(numerator, denominator)(engine)
: Produce a boolean withnumerator
/denominator
chance of it being true.Random.pick(engine, array)
: Return a random value within the providedarray
.Random.picker(array)(engine)
: Same asRandom.pick(engine, array)
.Random.shuffle(engine, array)
: Shuffle the providedarray
(in-place). Similar to.sort()
.Random.sample(engine, population, sampleSize)
: From thepopulation
array, produce an array withsampleSize
elements that are randomly chosen without repeats.Random.die(sideCount)(engine)
: Same asRandom.integer(1, sideCount)(engine)
Random.dice(sideCount, dieCount)(engine)
: Produce an array of lengthdieCount
with as manydie
rolls.Random.uuid4(engine)
: Produce a Universally Unique Identifier Version 4.Random.string()(engine, length)
: Produce a random string using numbers, uppercase and lowercase letters,_
, and-
of lengthlength
.Random.string(pool)(engine, length)
: Produce a random string using the provided stringpool
as the possible characters to choose from of lengthlength
.Random.hex()(engine, length)
orRandom.hex(false)(engine, length)
: Produce a random string comprised of numbers or the charactersabcdef
of lengthlength
.Random.hex(true)(engine, length)
: Produce a random string comprised of numbers or the charactersABCDEF
of lengthlength
.
An example of using integer
would be as such:
// create a Mersenne Twister-19937 that is auto-seeded based on time and other random values
var engine = Random.engines.mt19937().autoSeed();
// create a distribution that will consistently produce integers within inclusive range [0, 99].
var distribution = Random.integer(0, 99);
// generate a number that is guaranteed to be within [0, 99] without any particular bias.
function generateNaturalLessThan100() {
return distribution(engine);
}
Producing a distribution should be considered a cheap operation, but producing a new Mersenne Twister can be expensive.
An example of producing a random SHA1 hash:
// using essentially Math.random()
var engine = Random.engines.nativeMath;
// lower-case Hex string distribution
var distribution = Random.hex(false);
// generate a 40-character hex string
function generateSHA1() {
return distribution(40);
}
There is an alternate API which may be easier to use, but may be less performant. In scenarios where performance is paramount, it is recommended to use the aforementioned API.
var r = new Random(Random.engines.mt19937().seedWithArray([0x12345678, 0x90abcdef]));
var value = r.integer(0, 99);
This abstracts the concepts of engines and distributions.
r.integer(min, max)
: Produce an integer within the inclusive range [min
,max
].min
can be at its minimum -9007199254740992 (2 ** 53).max
can be at its maximum 9007199254740992 (2 ** 53). The special number-0
is never returned.r.real(min, max, inclusive)
: Produce a floating point number within the range [min
,max
) or [min
,max
]. Uses 53 bits of randomness.r.bool()
: Produce a boolean with a 50% chance of it beingtrue
.r.bool(percentage)
: Produce a boolean with the specified chance causing it to betrue
.r.bool(numerator, denominator)
: Produce a boolean withnumerator
/denominator
chance of it being true.r.pick(array)
: Return a random value within the providedarray
.r.shuffle(array)
: Shuffle the providedarray
(in-place). Similar to.sort()
.r.sample(population, sampleSize)
: From thepopulation
array, produce an array withsampleSize
elements that are randomly chosen without repeats.r.die(sideCount)
: Same asr.integer(1, sideCount)
r.dice(sideCount, dieCount)
: Produce an array of lengthdieCount
with as manydie
rolls.r.uuid4()
: Produce a Universally Unique Identifier Version 4.r.string(length)
: Produce a random string using numbers, uppercase and lowercase letters,_
, and-
of lengthlength
.r.string(length, pool)
: Produce a random string using the provided stringpool
as the possible characters to choose from of lengthlength
.r.hex(length)
orr.hex(length, false)
: Produce a random string comprised of numbers or the charactersabcdef
of lengthlength
.r.hex(length, true)
: Produce a random string comprised of numbers or the charactersABCDEF
of lengthlength
.
In your project, run the following command:
npm install random-js
In your code:
var Random = require("random-js");
var random = new Random(Random.engines.mt19937().autoSeed());
var value = random.integer(1, 100);
It is recommended to create one shared engine and/or Random
instance per-process rather than one per file.
Download random.min.js
and place it in your project, then use one of the following patterns:
define(function (require) {
var Random = require("random");
return new Random(Random.engines.mt19937().autoSeed());
});
define(["random"], function (Random) {
return new Random(Random.engines.mt19937().autoSeed());
});
Download random.min.js
and place it in your project, then add it as a <script>
tag as such:
<script src="lib/random.min.js"></script>
<script>
// Random is now available as a global (on the window object)
var random = new Random(Random.engines.mt19937().autoSeed());
alert("Random value from 1 to 100: " + random.integer(1, 100));
</script>
If you use Bower for your client-side package management, Random.js can be installed with the following command:
bower install random
All the code in Random.js is fully tested and covered using jasmine
.
To run tests in node.js:
npm install -g jasmine-node
npm test
To run tests in browsers:
karma start
You may need to run
npm install
In order to get karma
to run.
By default, karma
runs tests in PhantomJS, but that can be overridden as such:
karma start --browsers Chrome,IE,Firefox
The MIT License (MIT).
See the LICENSE file in this project for more details.