JavaScript Seedable Random Numbers

Every software developer I know has a love-hate relationship with the JavaScript language — usually with an emphasis on the hate.

For example, if you want to generate random numbers, as far as I can tell the built-in Math.random() function has no way to set a seed value in situations where you want to be able to reproduce results. Annoying. Very annoying.

After a bit of searching the Internet, I coded up a demo that creates a seedable random number generator. In my demo, I first call the built-in Math.random() function to generate two sets of three values. The sets are different because JavaScript uses a global RNG and there’s no way to set its seed.

The I call my program-defined Math.myRandom() function a total of three times. The first two times I use a seed value of 13 and get the same set of values. Then I change the seed to 99 and get a different set of values.


The key definition code is short but extremely tricky:

Math.seed = function(n) {
  return function() {
    n = Math.sin(n) * 10000;
    return n - Math.floor(n);

The calling code is also wacky. For example:

Math.myRandom = Math.seed(s);
var rn1 = Math.myRandom();
var rn2 = Math.myRandom();

Parts of JavaScript are quite technically cool, but there are some areas where JavaScript is really, really awkward.


This entry was posted in Machine Learning. Bookmark the permalink.