Skip to content

Instantly share code, notes, and snippets.

@methodin
Created January 3, 2012 06:28
Show Gist options
  • Save methodin/1553779 to your computer and use it in GitHub Desktop.
Save methodin/1553779 to your computer and use it in GitHub Desktop.
Mersenne Twister
var MersenneTwister = function(seed) {
// Holds the state of the register
this.state = [seed];
this.index = 0;
for(var i=1;i<=623;i++) {
var s = this.state[i-1] ^ (this.state[i-1] >>> 30);
this.state[i] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253) + i;
this.state[i] >>>= 0;
}
// Extract a tempered pseudorandom number based on the index-th value,
// calling generate_numbers() every 624 numbers
this.random = function() {
if(this.index == 0) this.generate_numbers();
var y = this.state[this.index];
y = y ^ (y >>> 11);
y = y ^ ((y << 7) & 0x9d2c5680);
y = y ^ ((y << 15) & 0xefc60000);
y = y ^ (y >>> 18);
this.index = (this.index + 1) % 624;
return (y >>> 0) / 4294967296;
}
// Generate an array of 624 untempered numbers
this.generate_numbers = function() {
for(var i=0;i<623;i++) {
var y = ((this.state[i] >>> 32) & 1) + ((this.state[(i+1) % 624]) & (1<<31));
this.state[i] = this.state[(i + 397) % 624] ^ (y >>> 1);
if(y % 2 != 0) this.state[i] = this.state[i] ^ 2567483615;
}
}
};
var mt = new MersenneTwister(150);
alert(mt.random());
alert(mt.random());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment