The first random value is always the same when using randomSeed

I’ve found that no matter how I change the seed, the first random value is always the same when using randomSeed(). Here is the a really simple test:

void draw() {
  randomSeed(frameCount);
  println(frameCount + ": " + (int)random(10) + " " +  (int)random(10) + " " +  (int)random(10) );
}

In this case, the first value is always 7, but the later two numbers seems random. I have to dispose the first value in my application. Did I do anything wrong? :thinking:

1 Like

Hi Reva,

I might be wrong but, try initializing the randomSeed() only one time at setup:

void setup(){
  randomSeed(frameCount);
}

void draw() {
  println(frameCount + ": " + (int)random(10) + " " +  (int)random(10) + " " +  (int)random(10) );
}

and please have a look at https://processing.org/reference/randomSeed_.html
If you " Set the seed parameter to a constant it will return the same pseudo-random numbers each time the software is run.". If you don’t which this to happen just don’t set the randomSeed()

I hope it helps! :slight_smile:

1 Like

Thanks for your reply~
In fact, I use randomSeed() somewhere else to generate some pattern, and the seed is determined according to the user’s input. Later I want to simulate arbitrary input to test the program, but I found once I use randomSeed(), I can’t reset it to the “random()” state. So I change the seed in runtime. Then I found this situation. Is there any way to switch between seed mode and default mode?

Hi Reva,

Not that I am aware, but check this link: https://forum.processing.org/two/discussion/22852/random-numbers-after-using-randomseed
You can try using time as a new seed, or you can try create object’s each with a random process. Example, one object has in its contructor the randomSeed(), and another does not. Then, you create a getter to retrieve the random number. Not sure if it will work for your case, but give it a try.
Later on, I will try it myself, but let me know if it worked.

2 Likes

Correlation of the first numbers is a well-documented aspect of the Java PRNG. For more, read:

(Aside: This correlation also happens in p5.js.)

If you want a pseudo-random number, don’t set the random seed each frame – and especially don’t set the seed with 1, 2, 3, 4, 5, et cetera, because contiguous first values are highly correlated. Instead, either:

  1. set the seed once in setup randomSeed(0) and then call random() in draw as often as you want with no correlation, or
  2. if you must set a different seed each frame (which is a bad idea), at least do it from non-contiguous numbers, for example multiplying the frameCount by a large prime number: randomSeed(frameCount*1777)

( or don’t set the seed at all!)

3 Likes

Thanks a lot, finally know the reason. :smiley: