Advertisement
Guest User

Untitled

a guest
Dec 1st, 2015
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. //a polyfill. seriously, node? you don't support this?
  2. if (Uint32Array.prototype.fill == undefined) {
  3. Uint32Array.prototype.fill = function(val, a, b) {
  4. for (var i=a; i<b; i++) {
  5. this[i] = val;
  6. }
  7. }
  8. }
  9.  
  10. //from: https://en.wikipedia.org/wiki/Mersenne_Twister
  11. function _int32(x) {
  12. // Get the 31 least significant bits.
  13. return ~~(((1<<30)-1) & (~~x))
  14. }
  15.  
  16. function MersenneRandom(seed) {
  17. // Initialize the index to 0
  18. this.index = 624;
  19. this.mt = new Uint32Array(624);
  20.  
  21. this.seed(seed);
  22. }
  23. MersenneRandom.prototype = {
  24. random : function random() {
  25. return this.extract_number() / (1<<30);
  26. },
  27.  
  28. seed : function seed(seed) {
  29. seed = ~~(seed*8192);
  30.  
  31. // Initialize the index to 0
  32. this.index = 624;
  33. this.mt.fill(0, 0, this.mt.length);
  34.  
  35. this.mt[0] = seed; // Initialize the initial state to the seed
  36.  
  37. for (var i=1; i<624; i++) {
  38. this.mt[i] = _int32(
  39. 1812433253 * (this.mt[i - 1] ^ this.mt[i - 1] >> 30) + i);
  40. }
  41. },
  42.  
  43. //private
  44. extract_number : function extract_number() {
  45. if (this.index >= 624)
  46. this.twist();
  47.  
  48. var y = this.mt[this.index];
  49.  
  50. // Right shift by 11 bits
  51. y = y ^ y >> 11;
  52. // Shift y left by 7 and take the bitwise and of 2636928640
  53. y = y ^ y << 7 & 2636928640;
  54. // Shift y left by 15 and take the bitwise and of y and 4022730752
  55. y = y ^ y << 15 & 4022730752;
  56. // Right shift by 18 bits
  57. y = y ^ y >> 18;
  58.  
  59. this.index = this.index + 1;
  60.  
  61. return _int32(y);
  62. },
  63.  
  64. //private
  65. twist : function twist() {
  66. for (var i=0; i<624; i++) {
  67. // Get the most significant bit and add it to the less significant
  68. // bits of the next number
  69. var y = _int32((this.mt[i] & 0x80000000) +
  70. (this.mt[(i + 1) % 624] & 0x7fffffff));
  71. this.mt[i] = this.mt[(i + 397) % 624] ^ y >> 1;
  72.  
  73. if (y % 2 != 0)
  74. this.mt[i] = this.mt[i] ^ 0x9908b0df;
  75. }
  76.  
  77. this.index = 0;
  78. }
  79. };
  80.  
  81. var mr = new MersenneRandom(0);
  82. for (var i=0; i<32; i++) {
  83. console.log(mr.random());
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement