1
0

rand.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. "use strict";
  2. const assert = require("assert");
  3. // From http://baagoe.com/en/RandomMusings/javascript/
  4. // Johannes Baagøe <baagoe@baagoe.com>, 2010
  5. function Mash() {
  6. var n = 0xefc8249d;
  7. var mash = function(data) {
  8. data = data.toString();
  9. for(var i = 0; i < data.length; i++) {
  10. n += data.charCodeAt(i);
  11. var h = 0.02519603282416938 * n;
  12. n = h >>> 0;
  13. h -= n;
  14. h *= n;
  15. n = h >>> 0;
  16. h -= n;
  17. n += h * 0x100000000; // 2^32
  18. }
  19. return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
  20. };
  21. return mash;
  22. }
  23. // From http://baagoe.com/en/RandomMusings/javascript/
  24. function KISS07() {
  25. return (function(args) {
  26. // George Marsaglia, 2007-06-23
  27. //http://groups.google.com/group/comp.lang.fortran/msg/6edb8ad6ec5421a5
  28. var x = 123456789;
  29. var y = 362436069;
  30. var z = 21288629;
  31. var w = 14921776;
  32. var c = 0;
  33. if(args.length === 0) {
  34. args = [+new Date];
  35. }
  36. var mash = Mash();
  37. for(var i = 0; i < args.length; i++) {
  38. x ^= mash(args[i]) * 0x100000000; // 2^32
  39. y ^= mash(args[i]) * 0x100000000;
  40. z ^= mash(args[i]) * 0x100000000;
  41. w ^= mash(args[i]) * 0x100000000;
  42. }
  43. if(y === 0) {
  44. y = 1;
  45. }
  46. c ^= z >>> 31;
  47. z &= 0x7fffffff;
  48. if((z % 7559) === 0) {
  49. z++;
  50. }
  51. w &= 0x7fffffff;
  52. if((w % 7559) === 0) {
  53. w++;
  54. }
  55. mash = null;
  56. var int32 = function() {
  57. var t;
  58. x += 545925293;
  59. x >>>= 0;
  60. y ^= y << 13;
  61. y ^= y >>> 17;
  62. y ^= y << 5;
  63. t = z + w + c;
  64. z = w;
  65. c = t >>> 31;
  66. w = t & 0x7fffffff;
  67. return x + y + w | 0;
  68. };
  69. var uint32 = function() {
  70. var t;
  71. x += 545925293;
  72. x >>>= 0;
  73. y ^= y << 13;
  74. y ^= y >>> 17;
  75. y ^= y << 5;
  76. t = z + w + c;
  77. z = w;
  78. c = t >>> 31;
  79. w = t & 0x7fffffff;
  80. return x + y + w >>> 0;
  81. };
  82. return {
  83. int32,
  84. uint32,
  85. };
  86. } (Array.prototype.slice.call(arguments)));
  87. }
  88. module.exports = KISS07;