Can I have multiple independent random number generators with different seeds?

Normally, we would expect that each instance of p5 would have its own random seed. :seedling:

In such case, we could instantiate a new p5 and call its noCanvas(), just for the sake of using its random() method w/ a specific randomSeed(). :money_mouth_face:

However, the code responsible to generate seeded pseudo-random values in p5js is a singleton object stored in a closure variable named lcg: :neutral_face:

B/c lcg is a closure variable, no matter how many times we instantiate the class p5, there’ll only be 1 unique lcg object shared across all p5 instances! :astonished:

Instead, lcg needs to be changed into a class property, so each instance of that class would have its own lcg, rather than a shared 1. :face_with_monocle:

BtW, the p5js library is littered w/ such closure local variables, which are a dumb, poor, short-sighted attempt to make private, unaccessible states. :male_detective:

And considering the library is supposed to have multiple instances of it at the same time, it shouldn’t have any shared states at all! :no_good_man:

Now, as a workaround, you can simply rewrite the “random.js” file as a class, whose instances will have their own seed state. :bulb:

More discussion about pseudo-random generation: :sunglasses:

6 Likes