We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › randomSeed() tip
Page Index Toggle Pages: 1
randomSeed() tip (Read 532 times)
randomSeed() tip
Jul 27th, 2006, 8:26pm
 
Not so much a "bug" per se, just a tip on a subtle aspect of Java's PRNG, in case anyone else runs across it...

In my sketches I frequently do something like this:

// globally defined seed value
int seed = 0;

// helper function to setup for next generation
void next() {
 randomSeed(seed++);
 // set various parameters with calls to random()
 // then generate output
}

In this way I can refer to and reproduce any given output of the sketch by specifying its "seed".

However, the problem with sequential seeds is that the first number returned by random() after seeding is going to be very much like the first number returned by the prior seed.  In other words:

randomSeed(1); float r1 = random(1.0);
randomSeed(2); float r2 = random(1.0);
// abs(r2-r1) is very small
randomSeed(3); float r3 = random(1.0);
// abs(r3-r2) is again very small

So that if the first random number were converted to an integer you'd likely return the same first number repeatedly.  In other words:

randomSeed(1); int r1 = (int)(random(10));
randomSeed(2); int r2 = (int)(random(10));
// r1 == r2
// (with a high likelihood, until you cross a "threshold"
// seed, which will vary according to the parameter given
// to random() modulo the LCG's prime)

The solution is to burn the first number after calling randomSeed() in order to properly "prime" the LCG - the second and subsequent numbers returned by random() are mangled enough to no longer closely correlate with the intial seed, and thus appear random.  In other words:

float burn;
randomSeed(1); burn=random(1.0); int r1 = (int)(random(10));
randomSeed(2); burn=random(1.0); int r2 = (int)(random(10));
// r1 is no longer correlated to r2 in an obvious way

Note that this is only a problem when intentionally specifying multiple and sequential seeds.  Typical "running" use of the rng without reseeding would not expose any problem with the first random() returned.
Page Index Toggle Pages: 1