# 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 randomGender()

{

double rand;

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...

return gender;

}

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 formula^{1}, which is quite simple, really:

X_{n+1} = (aX_{n} + c)_{mod m} where n>= 0 ^{2}

By DEFAULT (which is the way I used the PRNG):

m = 2^{48}

a = 5DEECE66D_{16} = 273673163155_{8}

c = B_{16} = 13_{8}

To start, X_{0} is the seed, which the programmer sets. As you start generating numbers, X_{1} is the first random number generated, X_{2} 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.