?? understanding random # generation code

srand(time(NULL));
I don't get what this exactly does. I have read that it accesses the computers clock, and converts to seconds. I just don't quite understand the reason for it.
The other thing I don't quite get is RAND_MAX. I have read the stuff in the library about it but I still don't understand where it gets the number from.
Maybe if some one coukd just explain the whole process in different words then my book says it It might help. Thanks
srand() seeds the random number generator. This sets up it's initial state, as it is a pseudo-random number generator. By placing time(NULL) as the parameter, take the current time in seconds and use this as the seed value; which is a fairly good way to initialize it as it will tend to be different each time you run it.

RAND_MAX is simply the maximum value that can be returned by the rand() function, limited by the size of the type it returns. (as char's can only go from 0-255, etc.)
the numbers he produced with a different way each time.
need to define in this way.

srand(56);

for (int i = 0; i < 10; i++)
data[i] = rand() % 1000;


srand(100);

for (int i = 0; i < 10; i++)
data[i] = rand() % 1000;
C's random number generator is essentially this:

rng(N+1) = rng(N) * CONST1 + CONST2

In other words, the N+1st random number is equal to the Nth random number multiplied by some constant CONST1, then CONST2 added to it. (And this whole thing is done in 32-bit arithmetic; when overflow occurs, as it will, the extra bits are simply discarded). CONST1 and CONST2 and hard-coded constants.

Obviously if rng(0) is always the same every time you run the program, then you will always generate the same sequence of random numbers. If you think of rng(N) as "the last random number I generated", then srand() just sets the "last random number I generated" to the specified value. To avoid getting the same random numbers each run, you should try to set the "last random number generated" to ... well ... a random value. The "simplest" source of randomness, if you will, is the number of seconds elapsed since the epoch (jan 1, 1970). That's what time(NULL) returns.

Topic archived. No new replies allowed.