alea.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // From http://baagoe.com/en/RandomMusings/javascript/
  2. function Alea() {
  3. return (function(args) {
  4. // Johannes Baagøe <baagoe@baagoe.com>, 2010
  5. var state = {
  6. s0: 0,
  7. s1: 0,
  8. s2: 0,
  9. c: 1
  10. };
  11. if (args.length == 0) {
  12. args = [+new Date];
  13. }
  14. var mash = Mash();
  15. state.s0 = mash(' ');
  16. state.s1 = mash(' ');
  17. state.s2 = mash(' ');
  18. for (var i = 0; i < args.length; i++) {
  19. state.s0 -= mash(args[i]);
  20. if (state.s0 < 0) {
  21. state.s0 += 1;
  22. }
  23. state.s1 -= mash(args[i]);
  24. if (state.s1 < 0) {
  25. state.s1 += 1;
  26. }
  27. state.s2 -= mash(args[i]);
  28. if (state.s2 < 0) {
  29. state.s2 += 1;
  30. }
  31. }
  32. mash = null;
  33. var random = function() {
  34. var t = 2091639 * state.s0 + state.c * 2.3283064365386963e-10; // 2^-32
  35. state.s0 = state.s1;
  36. state.s1 = state.s2;
  37. return state.s2 = t - (state.c = t | 0);
  38. };
  39. random.uint32 = function() {
  40. return random() * 0x100000000; // 2^32
  41. };
  42. random.fract53 = function() {
  43. return random() +
  44. (random() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
  45. };
  46. random.version = 'Alea 0.9';
  47. random.args = args;
  48. random.state = state;
  49. return random;
  50. } (Array.prototype.slice.call(arguments)));
  51. };