rand()

Sorry if this is being ignorant but why has the rand() function not been changed? It's clearly not so random and I know that you can use srand() and seed the random function but why is that not just the norm?
rand() implement a linear congruential random number generator (LCRNG).
An LCRNG has the "formula":

R(i+1) = ( c1 * R(i) + k ) mod p

where

R(i) is the ith random number generated by the function;
c1 and k are carefully chosen constants
p is typically 2^32

By default, R(0) is 0, and thus the RNG will generate the same sequence of numbers every time.

srand() simply sets R(0) to something other than 0.

A "good" LCRNG such as the one provided by the C library has a maximal period. That is, the mod 2^32 operation means that the RNG generates numbers between 0 and 2^32 - 1, which is 2^32 numbers. Maximal period means that the RNG is guaranteed to generate every number exactly once before the sequence repeats. (Poorly chosen c and k can cause the period to become much less than 2^32 and thus not all numbers can be generated).

Since every number in the range 0...2^32-1 is generated by the C RNG, and since srand() takes a 32-bit value as parameter, all srand() does is change the "starting point" in the RNG "stream".
Last edited on
In the next version of C++ ( C++0x ) should be some new random number generators
When's this new version meant to be released?

Thanks for both of you're replies! It just seems that a lot of people seems to seed rand with (time(null)) so maybe that should just be what R should be set to by default. Just a though anywho.

Could I ask you to write a small c++ version using srand(time(null)) please? Simply outputing the value.
time(0) (NULL is a macro for 0) returns the number of seconds passed since January 1st 1970. It is used to have a "random" number as seed. If you call srand(time(0)); only one in your program, you will get good random numbers as you can't know for sure which seed was set.

C++0x had to be released at the end of the 2008 but they are still working on it
http://www.research.att.com/~bs/C++0xFAQ.html#when-standard
Let's just say it will be a while because even once its released it will take time for compiler vendors to implement it. The new standard only has about 500 more pages than the previous one.
Topic archived. No new replies allowed.