-
-
Save bbarry/2d424230ba1464755389 to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
Implemented pseudocode available at | |
http://en.wikipedia.org/wiki/Mersenne_twister | |
as an asm.js module to learn about asm.js | |
*/ | |
function MersenneTwister(stdlib, foreign, heap) { | |
"use asm"; | |
//imports | |
var imul = stdlib.Math.imul; | |
//constants | |
var LW = 0xffff; | |
var HW = 0xffff0000; | |
var length = 624; | |
var offset = 397; | |
//internal state | |
var mt = new stdlib.Uint32Array(heap); | |
var temp = 0; | |
var temp2 = 0; | |
var i = 0; | |
//exposed functions | |
function init(seed) { | |
seed = seed|0; | |
mt[0] = seed >>> 0; | |
for (i = 1; (i>>>0) < (length>>>0); i = (i + 1)|0) { | |
temp = mt[((i-1)<<2)>>2]|0; | |
temp = temp ^ (temp >>> 30); | |
temp2 = (temp & HW) >>> 16; | |
temp2 = imul(temp2, 1812433253)|0; | |
temp2 = temp2 & LW; //truncate bits higher than 0xffff | |
temp2 = temp2 << 16; | |
temp = imul((temp & LW), 1812433253)|0; | |
mt[(i<<2)>>2] = (temp + temp2 + i) >>> 0; | |
} | |
i = 0; | |
} | |
function rand() { | |
if (i>>>0 == 0) { | |
for (i = 1; (i>>>0) < (length>>>0); i = (i + 1)|0) { | |
temp = ((mt[(i<<2)>>2] & 0x80000000) + (mt[((((i+1)>>>0) % (length>>>0))<<2)>>2] & 0x7fffffff))|0; | |
temp2 = (temp + (mt[((((i+offset)>>>0) % (length>>>0))<<2)>>2]|0))|0; | |
if ((temp & 1) == 1) { | |
temp2 = temp2 ^ 2567483615; | |
} | |
mt[(i<<2)>>2] = temp2; | |
} | |
i = 0; | |
} | |
temp = mt[(i<<2)>>2]|0; | |
i = (((i + 1)>>>0) % (length>>>0))|0; | |
/* Tempering */ | |
temp = (temp>>>0) ^ (temp >>> 11); | |
temp = (temp>>>0) ^ (temp << 7) & 0x9d2c5680; | |
temp = (temp>>>0) ^ (temp << 15) & 0xefc60000; | |
temp = (temp>>>0) ^ (temp >>> 18); | |
return (temp >>> 0)|0; | |
} | |
return { init: init, rand: rand }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment