隨機數與隨機種子 調用隨機數函數 rand() 的時候, 實際得到的這個隨機數并不是絕對隨機的,它是以一個初始值,通過一個算法,計算出來的“偽隨機數"數列,每次調用rand()時,從這個數列依次取出一個值,做為隨機數。這個初始的值就是"隨機數種子", 也就是說,如果隨機數種子相同,計算出的隨機數數列是相同的。而srandom( x) 這個函數就是初始化隨機數產生器,設定隨機數種子用的。給定的x的就是隨機數種子??梢则炞C,當你多次調用srandm(x)時,如果x取值相同,則得到的隨機數數列是一樣的。所以,若我們每次運行程序時,要得到不同的隨機數序列,就應該用不同的種子來初始化這個隨機數產生器。比如說,用時間初始化它,或者用getpid(),用進程的pid號初始化,由于每次運行程序時,它的pid號一般是不同的,所以能夠產生不同的隨機數序列。
舉例說明
在vc++中程序中用了srandom()和random(),頭文件為stdlib.h,但編譯出現錯誤error C3861: “srandom”: 找不到標識符。
原因是現在vc++編譯器的庫函數中沒有randomize()和random(),分別用srand()和rand()代替了。
#include <time.h> //定義關于時間的函數
一般在用到time(NULL)(當前時間)函數時需要包含此頭文件
#include <stdlib.h> //定義雜項函數及內存分配函數
一般在用到rand()和srand()函數時需要包含此頭文件
函數名: random 功 能: 隨機數發生器,也就是產生一個隨機數
用 法: int random(int num);
產生的隨機數范圍為0~num-1。
函數名: randomize
功 能: 初始化隨機數發生器,相當于撥隨機種子
用 法: void randomize(void);
- #include <iostream>
- #include <stdlib.h> // Need random(), srandom()
- #include <time.h> // Need time()
- #include <algorithm> // Need sort(), copy()
- #include <vector> // Need vector
-
- using namespace std;
-
- void Display(vector<int>& v, const char* s);
-
- int main()
- {
- // Seed the random number generator
- srand(time(NULL));
- // Construct vector and fill with random integer values
- vector<int> collection(10);
- for (int i = 0; i < 10; i++)
- collection[i] = rand() % 10000;
-
- // Display, sort, and redisplay
- Display(collection, "Before sorting");
- sort(collection.begin(), collection.end());
- Display(collection, "After sorting");
- return 0;
- }
-
- // Display label s and contents of integer vector v
- void Display(vector<int>& v, const char* s)
- {
- cout << endl << s << endl;
- copy(v.begin(), v.end(),ostream_iterator<int>(cout, "\t"));
- cout << endl;
- }
一般情況下可以設置當前時間為種子 srandom((int)time(0));
需要多次取隨即數時,可以將上次拿到的隨即數作為種子
posted on 2012-03-29 15:15
憤怒的考拉 閱讀(1212)
評論(0) 編輯 收藏