-
-
Save stonegao/626569d0de90f4fc03a43f224a435a3b to your computer and use it in GitHub Desktop.
A very simple, seedable JavaScript PRNG. NOTE: Please read comments on why this is not a good choice.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// NOTICE 2020-04-18 | |
// Please see the comments below about why this is not a great PRNG. | |
// Read summary by @bryc here: | |
// https://github.com/bryc/code/blob/master/jshash/PRNGs.md | |
// Have a look at js-arbit which uses Alea: | |
// https://github.com/blixt/js-arbit | |
/** | |
* 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