Last active
December 17, 2015 06:08
-
-
Save lovasoa/5562901 to your computer and use it in GitHub Desktop.
Javascript implementation of C stdlib random() function (the spec specifies no algorithm, the one of the GNU GLIBC is used). For a description of the algorithm, see: http://www.mathstat.dal.ca/~selinger/random/. I just realised that I was not logged in when I created the gist, so it's also available as an anonymous gist.
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
function Random(seed) { | |
/*JS implementation of GNU C stdlib random() algorithm described here: | |
http://www.mathstat.dal.ca/~selinger/random/ | |
*/ | |
/*Usage : | |
r = new Random(1); | |
r.random(); | |
this will generate the same sequence of pseudo-random numbers as C stdlib's random(). | |
*/ | |
seed = seed>>>0; | |
var r = [], i; | |
r[0] = seed; | |
for (i=1; i<31; i++) { | |
r[i] = (16807 * (r[i-1]>>>0)) % 2147483647; | |
if (r[i] < 0) { | |
r[i] += 2147483647; | |
} | |
} | |
for (i=31; i<34; i++) { | |
r[i] = r[i-31]; | |
} | |
for (i=34; i<344; i++) { | |
r[i] = (r[i-31] + r[i-3])|0; | |
} | |
//Here i=344 | |
i=343; | |
this.random = function() { | |
i++; | |
r[i] = (r[i-31] + r[i-3])|0; | |
return (r[i]>>>1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment