Skip to content

Instantly share code, notes, and snippets.

@orodio
Forked from blixt/prng.js
Created March 3, 2020 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orodio/961700053a7c0c66fb46c327ff049acd to your computer and use it in GitHub Desktop.
Save orodio/961700053a7c0c66fb46c327ff049acd to your computer and use it in GitHub Desktop.
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;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment