简体   繁体   English

为什么在使用rand生成随机数之前需要调用srand

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

calling srand on the lines of srand(time(NULL)); srand(time(NULL));的行上调用srand srand(time(NULL)); is required to setup the seed for rand() to generate a random number. 需要为rand()设置种子以生成随机数。 My question is what is the need for the seed ? 我的问题是需要种子吗?

The rand() function is a pseudo-random number generator , ie, rand()函数是伪随机数生成器 ,即

The rand() function returns a pseudo-random integer in the range 0 to RAND_MAX inclusive rand()函数返回一个伪随机整数,范围为0到RAND_MAX(含)

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. 如果您没有提供与seed不同的值,则在应用程序的每次调用中都会获得相同的随机数。 That's why, the srand() is used to randomize the seed itself. 这就是为什么srand()用于随机化种子本身的原因。

Most common practice : srand(time(NULL)) [Suitable for single-run evaluations]. 最常见的做法: srand(time(NULL)) [适用于单次运行评估]。

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. 如果没有提供种子值,则rand()函数将自动以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: 每次您致电rand时,都会发生以下情况:

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). (请注意, create_new_seedrandom_number_from_seed是纯函数,它们仅使用其参数,而不访问任何全局变量)。

This means that if the seed is always 0, then the series of values returned by rand calls will always be the same. 这意味着,如果种子始终为0,则rand调用返回的一系列值将始终相同。 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都会生成相同的随机数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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