Weird randomSeed() behaviour

Hey, so I found this weird thing while experimenting with randomSeed();

void setup(){
  for(int i = -100;i<100;i++){
    randomSeed(i);
    println(i,int(random(100)));
  }
}

this code prints the i, then the first random number with a set seed, BUT the random number is 27 with negative seeds and 73 with positive and 0. Can anyone explain this?? or am i doing something wrong? Thank you in advance.

-Ripolas

Also, some other observations:
with 10 its the exact same - just the numbers are 2 and 7 (first digits of 27 and 73?!?!)
then with 1000 the numbers vary a little, but stay around 270 and 730. same with bigger numbers. they vary a bit more, but never the less - WEIRD

The implementation is in this file processing4/core/src/processing/core/PApplet.java at main · benfry/processing4 · GitHub

In processing the usual workflow is to set the seed once, maybe something to do with the underlying java implementation. In any case, I agree it’s unexpected behaviour https://docs.oracle.com/javase%2F7%2Fdocs%2Fapi%2F%2F/java/util/Random.html

Every time you use randomSeed you are resetting the seed value for the next sequence of random numbers. The seed value created for randomSeed(-100) is very close to randomSeed(-99) is very small (bitwise) so that the result from int(random(100)) is also very small. Also your code masks the actual difference because you force the result to an integer try random(100) instead.

If you try

void setup(){
  for(int i = -100;i<100;i++){
    randomSeed(i*10000);
    println(i,random(100));
  }
}

You will see what I mean when you use large numbers to initialise the seed. It is common to do

randomSeed(System.currentTimeMillis())

to guarantee a random sequence everytime the program is run.

The difference between negative and positive numbers (zero is positive in your code) is also easy to explain. Negative integers set their most significant bit and the random seed and random numbers are generated by performing a complex bit manipulation algorithm to get the next result.

So nothing really surprising but an interesting diversion. :smile:

4 Likes

@TiborUdvari is absolutely right here. The point of being able to set the random seed is to get a repeatable series of random numbers which can be used to debug code.

3 Likes