Hacker News new | past | comments | ask | show | jobs | submit login
Exploring Randomness in JavaScript (bennadel.com)
26 points by kiyanwang 3 months ago | hide | past | favorite | 6 comments



The behaviour of Math.random() is technically browser specific since the algorithm isn't specified, but I think all the big engines have settled on xorshift128+. That's probably good enough for most non-crypto things.

Still, if you want consistent quality and speed across all browsers current and future, you're better off bundling your own PRNG code. That's also necessary if you want a repeatable sequence from a specific seed value, neither of the browser built-in methods support that.


I was also exploring randomness in JS at some point and found lots of interesting things! One was that the Alea PRNG algorithm[1] by Johannes Baagøe performed faster on JavaScript's floating point numbers. Another was that Dieharder[2] is a really fun tool to test PRNGs. I also made an attempt at consolidating other PRNG methods which were not great[3] and that led me to other people who had done the same[4].

And finally I tried to make a nicer Dieharder wrapper and a simple PRNG library, but lord knows how relevant it is anymore: https://github.com/blixt/js-arbit

I guess in this archaeological dig I also found how many useful resources on the internet disappear in less than a decade.

[1]: https://web.archive.org/web/20120502223108/http://baagoe.com... (Baagøe's original site is down)

[2]: https://rurban.github.io/dieharder/ (old site is dead, though here's a web archive link: https://web.archive.org/web/20170609075452/http://www.phy.du...)

[3]: https://gist.github.com/blixt/f17b47c62508be59987b (Don't use this)

[4]: https://github.com/nquinlan/better-random-numbers-for-javasc... (this is mainly a mirror of Baagøe's wiki)


Here's my favorite deterministic PRNG optimizing for implementation simplicity:

    function random() {
      random._s = random._s || 11224; // seed
      return (random._s = random._s * 16807 % 2147483647) / 2147483646;
    }
Wikipedia says this approach has been around at least since the 1950s.

https://en.wikipedia.org/wiki/Linear_congruential_generator


What would be the best way for me to create a truly random approach to sampling from a specified distribution in my Monte Carlo simulator app? In my current MVP Beta app I’m just using Math.random() as I cannot access or install any external libraries. How would you go about implementing something more robust in something like, say, Apps Script (a Google proprietary derivative of JavaScript for cloud apps)?


You can convert from the uniform random numbers math.random() gives you to the distribution of your choice with inverse transform sampling, or any number of other methods (e.g. ziggurat).


Nice article, and reminds me of my personally most used method: window.crypto.randomUUID()




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: