简体   繁体   English

自己播种 rand()

[英]Seeding rand() by itself

如果程序使用rand()生成一些数字,存储最后的rand()结果,并在重复运行时使用srand(stored_seed) ,这是否会提供一些更短但仍然可用的随机数序列?

srand should be run exactly once. srand应该只运行一次。 If you initialize it more than once the resulted sequence may not be so random.如果多次初始化它,结果序列可能不会那么随机。

A good way to initialize the PRNG is srand(time(NULL)*getpid()) ;初始化 PRNG 的一个好方法是srand(time(NULL)*getpid()) ;

alternatively you can try:或者你可以尝试:

timeval t;
gettimeofday(&t, NULL);
srand((t.tv_usec/100) + (t.tv_sec/100));//getpid is optional

Explanation:解释:

A PRNG (Pseudo-Random Number Generator) generates a deterministic sequence of numbers dependent on the algorithm used. PRNG(伪随机数生成器)根据所使用的算法生成确定性的数字序列。 A given algorithm will always produce the same sequence from a given starting point (seed).给定的算法将始终从给定的起点(种子)产生相同的序列。 If you don't explicitly see the PRNG then it will usually start from the same default seed every time an application is run, resulting in the same sequence of numbers being used.如果您没有明确看到 PRNG,那么它通常会在每次运行应用程序时从相同的默认种子开始,从而导致使用相同的数字序列。

To fix this you need to seed the PRNG yourself with a different seed (to give a different sequence) each time the application is run.要解决此问题,您需要在每次运行应用程序时自己为 PRNG 设置不同的种子(以提供不同的序列)。 The usual approach is to use time(NULL) which sets the seed based on the current time.通常的方法是使用 time(NULL) 根据当前时间设置种子。 As long as you don't start two instances of the application within a second of each other, you'll be guaranteed a different random sequence.只要您没有在一秒钟内启动应用程序的两个实例,您就可以保证不同的随机序列。

There's no need to seed the sequence each time you want a new random number.每次您想要一个新的随机数时,都无需为序列设定种子。 And I'm not sure about this, but I have the feeling that depending on the PRNG algorithm being used re-seeding for every new number may actually result in lower randomness in the resulting sequence.我不确定这一点,但我有一种感觉,根据所使用的 PRNG 算法为每个新数字重新播种实际上可能会导致结果序列的随机性较低。 Source: link来源: 链接

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

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