jwatte / node-mersenne

Node.js port of the Mersenne Twister random number generator
http://www.enchantedage.com/node-mersenne
BSD 3-Clause "New" or "Revised" License
12 stars 2 forks source link

default random seed not random enough in parallel execution #6

Open klplentific opened 6 years ago

klplentific commented 6 years ago

Is the below snippet the default random seed?

gen.init_genrand((new Date).getTime() % 1000000000);

If it is it could be unexpected behavior. Because when executed in parallel the chances of matching initial seeds increases like it did in my app where I executed code in parallel.

My issues were gone when I manually set the seeds with a combination of both a date timestamp and Math.random()

I think the principle of least astonishment here would to make the initial seed collision less likely when running code in parallel such as running selenium browser tests.

jwatte commented 6 years ago

If you need high-quality random seeds, I recommend using whatever system-specific random generator is available to you (CryptRandom(), /dev/urand, crypto.getRandomValues(), etc) and initialize using that.

For multiple parallel invocations to share a random seed, each parallel process needs to be created within the same millisecond as the one before it. While that can totally happen, this is not the common case, and even when it happens, it shouldn't break anything.

For the principle of least astonishment, the generator should be seeded by a constant value (such as 1) each time, and the original source of entropy should be entirely left up to the user. So, on the spectrum between: