1. // This snippet compares two PRNG algorithms using the incremental seed test
  2. // "Small Fast Counter 32"
  3. // This is a good algorithm from the PractRand test suite: http://pracrand.sourceforge.net/RNG_engines.txt
  4. // It passes stringent randomness tests (PractRand, TestU01).
  5. function sfc32(a, b, c, d) {
  6. return function() {
  7. a >>>= 0; b >>>= 0; c >>>= 0; d >>>= 0;
  8. var t = (a + b) | 0;
  9. a = b ^ b >>> 9;
  10. b = c + (c << 3) | 0;
  11. c = (c << 21 | c >>> 11);
  12. d = d + 1 | 0;
  13. t = t + d | 0;
  14. c = c + t | 0;
  15. return (t >>> 0) / 4294967296;
  16. }
  17. }
  18. // MWC1616, as used in Chrome's Math.random() circa 2015
  19. // This is NOT a good algorithm: https://medium.com/@betable/tifu-by-using-math-random-f1c308c4fd9d#.7p3lk9bvk
  20. // It fails stringent randomness tests.
  21. function mwc(a, b) {
  22. return function() {
  23. a = 36969 * (a & 65535) + (a >>> 16);
  24. b = 18000 * (b & 65535) + (b >>> 16);
  25. var result = (a << 16) + (b & 65535) >>> 0;
  26. return result / 4294967296;
  27. }
  28. }
  29. // Which one passes the seed test?
  30. let count = 0; setInterval(() => {
  31. console.log(
  32. Math.round(sfc32(count++,count++,count++,count++)()*100),
  33. Math.round(mwc(count++,count++)()*100),
  34. );
  35. }, 500);