简体   繁体   中英

why is srand required to be called before generating a random number using rand

calling srand on the lines of srand(time(NULL)); is required to setup the seed for rand() to generate a random number. My question is what is the need for the seed ?

The rand() function is a pseudo-random number generator , ie,

The rand() function returns a pseudo-random integer in the range 0 to RAND_MAX inclusive

The generation of the pseudo-random number depends on the seed . If you don't provide a different value as seed , you'll get the same random number on every invocation(s) of your application. That's why, the srand() is used to randomize the seed itself.

Most common practice : srand(time(NULL)) [Suitable for single-run evaluations].

what is the need for the [explicit] seed ?

Worthy to mention, from the man page

If no seed value is provided, the rand() function is automatically seeded with a value of 1.

I guess your question is why isn't it seeded automatically with an unpredictable value (like the current time).

Having the random number generator generate the same sequence every time a program starts can be handy for debugging.

Random number generation is the result of an iterative process. Each time you call rand the following happens:

seed := create_new_seed(seed);
return random_number_from_seed(seed);

(Note that create_new_seed and random_number_from_seed are pure functions, they only use their parameters and do not access any globals).

This means that if the seed is always 0, then the series of values returned by rand calls will always be the same. In order to allow for different values, a different seed is used in each run. One thing that changes between runs and can easily be used is the start time of the program.

如果不添加srand(),则每次运行程序时,rand都会生成相同的随机数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM