http://qs321.pair.com?node_id=272881


in reply to Can I seed srand() with results from rand()?

If rand() is a linear congruential generator (usually the case) with modulus $M, then this

srand( rand($M) )

is likely to be almost equivalent to calling rand() once or twice. Not quite, because there might be extra magic in srand(), and some rand()s only return 15 bits of randomness (even though they're seeded with 31). You might not care about having your entropy reduced to that, so go ahead with your plan. Otherwise, look into an alternate PRNG that gives you access to its internal state, like Math::Random.

What you want to avoid is using a seed with an obvious pattern in a loop. This is bad:

srand( $n += 42 )

And keep in mind that more things have obvious patterns than you might think.

Replies are listed 'Best First'.
Re: Re: Can I seed srand() with results from rand()?
by no_slogan (Deacon) on Jul 10, 2003 at 05:53 UTC

    I should have been less cavalier. The generation of random numbers is too important to be left to chance, as they say. One of the desirable features of PRNGs is that they have a provably long period before they start repeating themselves. By reseeding this way, you lose that. After a large number of iterations, you might end up in a short limit cycle of possible values for the next seed. That will depend on the details of your rand() and exactly how many times you call it per loop. So I'm afraid I have to take back my advice. Don't reseed this way, epecially if you're going to do a lot of loops.

    You could use rand() with the initial seed to generate all the other seeds you need. You'd either have to know the number of loops ahead of time, or keep winding rand() forward from the initial seed.

    The best solution would be to use a different random number generator that lets you get at the current seed value. There are several available. They're also easy to write -- just don't try to pick the constants yourself.

      You could use rand() with the initial seed to generate all the other seeds you need.

      ... but that's a terrible idea if your rand() doesn't hide some bits from you. Gack. Stay away.