[英]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.