How NOT to seed your (pseudo-) random number generator…
This is how you write a function to generate a random number BEFORE you remember how PRNG’s normally work:
int gender; //if rand <= 0.6 then gender = 1, else gender = 0
srand48( SEED );//SEED is defined elsewhere
rand = drand48();
... determine gender based on comment, not really important for the purposes of this post...
Then you run your code, in which you call randomGender() 20 times.
Then you wonder why in the hell it’s returning the same value each time. (The head banging starts here, lasts about 30 – 40 minutes, I was pretty tired, and this was my first major C program in a while).
THEN, and ONLY THEN, do you remember how most PRNG’s work. You don’t TRULY learn your lesson until the head and desk are dented.
Here is how this particular PRNG does it. It uses something called the linear congruential formula1, which is quite simple, really:
Xn+1 = (aXn + c)mod m where n>= 0 2
By DEFAULT (which is the way I used the PRNG):
m = 248
a = 5DEECE66D16 = 2736731631558
c = B16 = 138
To start, X0 is the seed, which the programmer sets. As you start generating numbers, X1 is the first random number generated, X2 is the second random number generated, and so on and so forth (this is tracked internally, the programmer doesn’t have to worry about this part).
Once I remembered, my mistake became obvious. The PRNG needed to be seeded (call to srand48()) OUTSIDE of the function.
C: 1, James: 0
1 I haven’t fully read this page yet, so perhaps it contradicts stuff in this post. Please be smart. Trust them and not me :).
2 I took the form of the equation I used from here.