dronus
dronus

Reputation: 11272

Seeding rand() by itself

If a program generates a few numbers using rand(), stores the last rand() result, and on repeated runs use srand(stored_seed), would this provide some shorter, but still usable random number sequence?

Upvotes: 2

Views: 162

Answers (1)

A B
A B

Reputation: 487

srand should be run exactly once. If you initialize it more than once the resulted sequence may not be so random.

A good way to initialize the PRNG is srand(time(NULL)*getpid());

alternatively you can try:

timeval t;
gettimeofday(&t, NULL);
srand((t.tv_usec/100) + (t.tv_sec/100));//getpid is optional

Explanation:

A PRNG (Pseudo-Random Number Generator) generates a deterministic sequence of numbers dependent on the algorithm used. A given algorithm will always produce the same sequence from a given starting point (seed). If you don't explicitly see the PRNG then it will usually start from the same default seed every time an application is run, resulting in the same sequence of numbers being used.

To fix this you need to seed the PRNG yourself with a different seed (to give a different sequence) each time the application is run. The usual approach is to use time(NULL) which sets the seed based on the current time. As long as you don't start two instances of the application within a second of each other, you'll be guaranteed a different random sequence.

There's no need to seed the sequence each time you want a new random number. And I'm not sure about this, but I have the feeling that depending on the PRNG algorithm being used re-seeding for every new number may actually result in lower randomness in the resulting sequence. Source: link

Upvotes: 2

Related Questions