2009-07-13 89 views
7

我正在做一個書的練習,說要寫一個程序,生成psuedorandom數字。我從簡單開始。在C++中使用rand()函數的正確方法是什麼?

#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()); 

這基本上只是做了作爲程序首先沒有,但輸出的不同組數字(它有道理的,因爲由蘭特()生成所述第一數總是41)

相同我能想到的唯一的事情,使這個更隨機是:

  1. 讓用戶輸入一個號碼,設置爲種子(這將是很容易實現,但這是不得已而爲之) OR
  2. 以某種方式將種子設置爲計算機時鐘或其他不斷變化的數字。

上午我在我的頭,我現在應該停下來?選項2難以實施?任何其他想法?

在此先感謝。

回答

27

選項2並不難,在這裏你去:

srand(time(NULL)); 

你需要包括time()stdlib.hsrand()time.h

+8

+1,這是標準做法。 – SingleNegationElimination 2009-07-13 00:37:05

+0

如果您處於* nix環境中,您還可以讀取/ dev/random;但我同意令牌,這是一個標準的做法,用時間函數設置srand。 – Suroot 2009-07-13 00:42:20

+2

另外,由於您只需調用一次,因此請在主頂部附近調用srand()。不要每次生成新號碼時都調用它。 – MahlerFive 2009-07-13 00:52:00

6

這是常見與當前時間的種子的隨機數發生器。嘗試:

函數srand(時間(NULL));

8

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(); 
} 
4

的問題是,如果你不播種發生器將種子本身0(好像srand(0)被稱爲)。 PRNG被設計爲當接種相同時產生相同的序列(由於PNRG不是真的隨機的,它們是確定性算法,可能有點因爲它對於測試非常有用)。

當你試圖

srand(rand()); 

你在做的效果與使用隨機數種子吧:

srand(0); 
x = rand(); // x will always be the same. 
srand(x); 

由於FigBug mentioned,採用播種發電機通常是用過的。

0

我認爲這些文章的重點是要實現在rand()中的算法,而不是如何有效地對其進行種子處理。產生(僞)隨機數不是微不足道的,值得研究不同的技術來產生它們。我不認爲簡單地使用rand()是作者想到的。

相關問題