[英]What's the Right Way to use the rand() Function in C++?
我正在做一本书练习,说要写一个生成伪随机数的程序。 我从简单开始。
#include "std_lib_facilities.h"
int randint()
{
int random = 0;
random = rand();
return random;
}
int main()
{
char input = 0;
cout << "Press any character and enter to generate a random number." << endl;
while (cin >> input)
cout << randint() << endl;
keep_window_open();
}
我注意到,每次运行程序时,都会有相同的“随机”输出。 因此,我研究了随机数生成器,并决定尝试通过将其首先包含在randint()中来进行播种。
srand(5355);
只是一遍又一遍地产生相同的数字(我现在对实现它感到很愚蠢。)
所以我想我会很聪明,像这样实现种子。
srand(rand());
基本上,这和程序最初做的一样,只是输出了一组不同的数字(这很有意义,因为rand()生成的第一个数字始终为41。)
我唯一能想到的就是使:
我在头上,现在应该停下来吗? 选项2难以实施吗? 还有其他想法吗?
提前致谢。
选项2并不困难,这里您可以:
srand(time(NULL));
你需要包括stdlib.h
的srand()
和time.h
的time()
srand()只能使用一次:
int randint()
{
int random = rand();
return random;
}
int main()
{
// To get a unique sequence the random number generator should only be
// seeded once during the life of the application.
// As long as you don't try and start the application mulitple times a second
// you can use time() to get a ever changing seed point that only repeats every
// 60 or so years (assuming 32 bit clock).
srand(time(NULL));
// Comment the above line out if you need to debug with deterministic behavior.
char input = 0;
cout << "Press any character and enter to generate a random number." << endl;
while (cin >> input)
{
cout << randint() << endl;
}
keep_window_open();
}
通常用当前时间播种随机数生成器。 尝试:
srand(time(NULL));
问题是,如果不对生成器进行种子设置,则它将自身以0
种子设置(就像srand(0)
一样)。 PRNG被设计为在播种相同时生成相同的序列(由于PNRG并不是真正随机的,因此它们是确定性算法,也许有点,因为它对于测试非常有用)。
当您尝试使用随机数播种时
srand(rand());
您实际上是在做:
srand(0);
x = rand(); // x will always be the same.
srand(x);
正如FigBug所提到的 ,通常使用时间为生成器添加种子。
我认为这些文章的重点是着手实现rand()中的算法,而不是如何有效播种它。
产生(伪)随机数并非无关紧要,值得研究产生它们的不同技术。 我认为作者不打算仅仅使用rand()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.