Why aren't my random numbers random?

If you're using a version of Perl before 5.004, you must call srand once at the start of your program to seed the random number generator. 5.004 and later automatically call srand at the beginning. Don't call srand more than once--you make your numbers less random, rather than more.

Computers are good at being predictable and bad at being random (despite appearances caused by bugs in your programs :-). see the random artitcle in the "Far More Than You Ever Wanted To Know" collection in http://www.cpan.org/olddoc/FMTEYEWTK.tgz , courtesy of Tom Phoenix, talks more about this. John von Neumann said, ``Anyone who attempts to generate random numbers by deterministic means is, of course, living in a state of sin.''

If you want numbers that are more random than rand with srand provides, you should also check out the Math::TrulyRandom module from CPAN. It uses the imperfections in your system's timer to generate random numbers, but this takes quite a while. If you want a better pseudorandom generator than comes with your operating system, look at ``Numerical Recipes in C'' at http://www.nr.com/ .


Back to perlfaq4