Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //a polyfill. seriously, node? you don't support this?
- if (Uint32Array.prototype.fill == undefined) {
- Uint32Array.prototype.fill = function(val, a, b) {
- for (var i=a; i<b; i++) {
- this[i] = val;
- }
- }
- }
- //from: https://en.wikipedia.org/wiki/Mersenne_Twister
- function _int32(x) {
- // Get the 31 least significant bits.
- return ~~(((1<<30)-1) & (~~x))
- }
- function MersenneRandom(seed) {
- // Initialize the index to 0
- this.index = 624;
- this.mt = new Uint32Array(624);
- this.seed(seed);
- }
- MersenneRandom.prototype = {
- random : function random() {
- return this.extract_number() / (1<<30);
- },
- seed : function seed(seed) {
- seed = ~~(seed*8192);
- // Initialize the index to 0
- this.index = 624;
- this.mt.fill(0, 0, this.mt.length);
- this.mt[0] = seed; // Initialize the initial state to the seed
- for (var i=1; i<624; i++) {
- this.mt[i] = _int32(
- 1812433253 * (this.mt[i - 1] ^ this.mt[i - 1] >> 30) + i);
- }
- },
- //private
- extract_number : function extract_number() {
- if (this.index >= 624)
- this.twist();
- var y = this.mt[this.index];
- // Right shift by 11 bits
- y = y ^ y >> 11;
- // Shift y left by 7 and take the bitwise and of 2636928640
- y = y ^ y << 7 & 2636928640;
- // Shift y left by 15 and take the bitwise and of y and 4022730752
- y = y ^ y << 15 & 4022730752;
- // Right shift by 18 bits
- y = y ^ y >> 18;
- this.index = this.index + 1;
- return _int32(y);
- },
- //private
- twist : function twist() {
- for (var i=0; i<624; i++) {
- // Get the most significant bit and add it to the less significant
- // bits of the next number
- var y = _int32((this.mt[i] & 0x80000000) +
- (this.mt[(i + 1) % 624] & 0x7fffffff));
- this.mt[i] = this.mt[(i + 397) % 624] ^ y >> 1;
- if (y % 2 != 0)
- this.mt[i] = this.mt[i] ^ 0x9908b0df;
- }
- this.index = 0;
- }
- };
- var mr = new MersenneRandom(0);
- for (var i=0; i<32; i++) {
- console.log(mr.random());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement