samedi 24 novembre 2018

Seeding a random number generator with a random integer from another random number generator

In a Java project, I use the same unique Random object all over my code. I usually create it without a seed, but when debugging it is useful to initialize it with a seed so I get reproducible runs.

I am using Apache Commons Math 3.6 and its NormalDistribution class takes a RandomGenerator object. RandomGenerator is of course a different interface from Random, so I cannot just pass my unique Random object to NormalDistribution.

To keep the ability to introduce a single seed to a single random number generator and obtain reproducible runs, I create the RandomGenerator (specifically, its implementation JDKRandomGenerator) for NormalDistribution with a seed that comes from my unique Random object (using Random.nextInt()):

NormalDistribution(new JDKRandomGenerator(myUniqueRandom.nextInt()), mean, standardDeviation);

The reasoning is that, when I introduce a seed to the Random object, it will pass the same seed every time to the RandomGenerator and things will be reproducible.

Things seemed to be working but after a while I realized that the variance I was getting in my results was far from what it should have been. After some debugging I realized that if I don't pass a seed to JDKRandomGenerator from my unique Random (or use the NormalDistribution constructor that doesn't take a random number generator at all), then things work fine and the variance is what it should be. However, now I don't have the ability to obtain reproducible runs anymore.

Any idea why passing a RandomGenerator a seed coming from Random.nextInt() didn't work? It sounds like it should.




Aucun commentaire:

Enregistrer un commentaire