Get random seed value in p5.js?

I’ve looked at the source code for the p5.js randomSeed() function but can’t quite figure this out: is it possible to get the seed value currently being used by the random() function? I’d like to grab this is setup() so I can replicate the results later by feeding in this seed value.


Looking through the code I didn’t see an obvious way to get the seed. You could just set it yourself at the beginning of your program to have a repeatable value.

1 Like

I also don’t think that you can. As @BrendanL said, you can always set one yourself that you can reuse.
Have a look at this post: randomSeed() reuse - #14 by jb4x

1 Like

I´d say in most scenarios for pseudo random numbers (as generated by random()) finding out the seed value is somewhere between “doesn´t matter” and “definitely not wanted”.

This explains why it is not (easy) to get the current seed.

For cases like yours where knowledge of the seed is interesting/important seeding with a known value is therefore at least the easiest way - if not the only one.

1 Like

Until randomSeed() is invoked for the 1st time there’s no seed yet, so random() merely invokes JS builtin Math.random() till then:

The local constant randomStateProp contains the string name of the “secret” seed property:

And that property is initialized w/ null by default:

We can log that property like this: print(_lcg_random_state);

AFAIK that “seed” algorithm is used by both Java Mode & Pjs flavors as well.

1 Like

Thanks all! I realize this is maybe a but unusual but I could see a good use here: when working with random values you often want variety (ie randomness) but also to be able to return to something you like. By running random() with the built-in seed, each time you run the sketch the results are different. But by being able to print that seed (or use it to build a filename for the output) you can return to those exact settings later.

For sure: I could create a seed myself and I do that a lot, but this involves updating that seed manually.

@GoToLoop – thanks for tracking that down! I tried several permutations but _lcg_random_state always returns null for me.

Seems like maybe the best option is something like this:

function setup() {
  createCanvas(400, 400);
  // create a random random-seed :)
  let seed = random(0, 10000);

function draw() {
  // do random stuff