Interesting quirks of P5js random number generator
function draw() {
randomSeed(frameCount);
console.log(random());
}
This is a really interesting piece of code. Try it online.
=> https://editor.p5js.org/sixhat/sketches/WRBChpIXz
See the interesting thing? The random numbers generated are growing sequentially.
This is a side effect of using a Linear Congruent Generator. The random seed just applies the value of the seed sequentially and as the seeds are close enough, the resulting random numbers are also close to each other.
Curiously, if the user doesn’t use the randomSeed function the PRNG still sets a seed given by Math.random() * 2**32. And as Math.random() is not possible to seed…
=> https://github.com/processing/p5.js/blob/v2.2.3/src/math/random.js#L30
The solution for your sketch is not to use randomSeed with close seeds. Always multiply them with a big constant. In the previous example, multiplying frameCount by 2**16 will spread the seeds so the resulting random numbers at least don’t seem so sequential.
function draw() {
randomSeed(frameCount * 2**16 );
console.log(random());
}
Why do you need this? Probably you don’t need to set different seeds like this, but if you are trying to do something based on the current time (let’s say using the second() as your seed, so you have changing random values each second) then you’ll have the unpleasant surprise that it doesn’t behave randomly. For this if using second() as seed, multiply it with a big constant (eg. 1<<16).
A suggestion to p5js would be to implement a hashing algorithm to the seed value in the above example.