http://www.perlmonks.org?node_id=864838


in reply to srand producing the same sequence of random numbers

You have greatly misunderstood the purpose of srand. This is not a bug. If you repeatedly call srand with the same seed, then you will get the same sequence of pseudorandom numbers from rand each time. That's what srand does.

If you want a different set of pseudorandom numbers each time, then forget that srand even exists. The first call to rand will automatically seed the PRNG with a value based on the system clock, which will get you close enough to actual randomness for most practical purposes.

Replies are listed 'Best First'.
Re^2: srand producing the same sequence of random numbers
by pemungkah (Priest) on Oct 12, 2010 at 21:04 UTC
    This is the answer the OP is looking for.

    Seeding a random number generator means giving it a number to start from - all "random number generators" that are not hooked to an actual source of entropy (like atomic decay, thermal noise, or the like) are simply doing calculations that return a sequence of numbers whose distribution looks random "enough". Knuth spends an entire volume of different definitions of "enough"; it's a very deep (and interesting) subject. (Most random number generators use a "linear congruential" calculation that essentially uses two largish numbers that are relatively prime to one another; the seed is multiplied by one, and then the product is reduced modulo the other. This has the advantage that it's a fairly fast operation (one multiply and one divide), and yields fairly good results.)

    Seed functions exist to allow you to reproduce a given random sequence; this can be very useful when you're trying to test a module which contains a random component, as the behavior is still "random" (that is driven by the output of the rand() function) but at the same time completely predictable (since the sequence of numbers coming from rand() will be exactly the same every time for the same seed).