Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A very simple, seedable JavaScript PRNG.
/**
* Creates a pseudo-random value generator. The seed must be an integer.
*
* Uses an optimized version of the Park-Miller PRNG.
* http://www.firstpr.com.au/dsp/rand31/
*/
function Random(seed) {
this._seed = seed % 2147483647;
if (this._seed <= 0) this._seed += 2147483646;
}
/**
* Returns a pseudo-random value between 1 and 2^32 - 2.
*/
Random.prototype.next = function () {
return this._seed = this._seed * 16807 % 2147483647;
};
/**
* Returns a pseudo-random floating point number in range [0, 1).
*/
Random.prototype.nextFloat = function (opt_minOrMax, opt_max) {
// We know that result of next() will be 1 to 2147483646 (inclusive).
return (this.next() - 1) / 2147483646;
};

madole commented Jul 30, 2014

You dont check that the seed is a number before performing arithmetic calculations on it. potential NaN returned.

Didn't think it would be this simple, but I guess it is! I wrote a graphic representation of the distribution here: https://www.khanacademy.org/computer-programming/prng-test/5500564014432256
A couple thousand runs show that it's pretty much uniform. Nice work 👍

rayfoss commented Aug 24, 2017

Unlike the Math.sin versions of this, this will produce the same result on Node, Chrome, Safari and Firefox... meaning I can save the seed and regenerate the same results across environments.

Very nice! This is just what I needed for my multi-player game, where some random events need to generated on all clients at the same time. With this generator all clients will get the same "random" values, without having to talk over the network.

TBubba commented Sep 19, 2017

Well done! Also, thanks @rayfoss for pointing out that it works across platforms, because that's exactly what I was looking for! 👍

Do bear in mind that the float version will be affected by floating point rounding errors in different ways on different platforms - so if you want the same numbers on all platforms make sure you stick to using the integer version!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment