隨機(jī)數(shù)與隨機(jī)種子 調(diào)用隨機(jī)數(shù)函數(shù) rand() 的時(shí)候, 實(shí)際得到的這個(gè)隨機(jī)數(shù)并不是絕對(duì)隨機(jī)的,它是以一個(gè)初始值,通過(guò)一個(gè)算法,計(jì)算出來(lái)的“偽隨機(jī)數(shù)"數(shù)列,每次調(diào)用rand()時(shí),從這個(gè)數(shù)列依次取出一個(gè)值,做為隨機(jī)數(shù)。這個(gè)初始的值就是"隨機(jī)數(shù)種子", 也就是說(shuō),如果隨機(jī)數(shù)種子相同,計(jì)算出的隨機(jī)數(shù)數(shù)列是相同的。而srandom( x) 這個(gè)函數(shù)就是初始化隨機(jī)數(shù)產(chǎn)生器,設(shè)定隨機(jī)數(shù)種子用的。給定的x的就是隨機(jī)數(shù)種子。可以驗(yàn)證,當(dāng)你多次調(diào)用srandm(x)時(shí),如果x取值相同,則得到的隨機(jī)數(shù)數(shù)列是一樣的。所以,若我們每次運(yùn)行程序時(shí),要得到不同的隨機(jī)數(shù)序列,就應(yīng)該用不同的種子來(lái)初始化這個(gè)隨機(jī)數(shù)產(chǎn)生器。比如說(shuō),用時(shí)間初始化它,或者用getpid(),用進(jìn)程的pid號(hào)初始化,由于每次運(yùn)行程序時(shí),它的pid號(hào)一般是不同的,所以能夠產(chǎn)生不同的隨機(jī)數(shù)序列。
舉例說(shuō)明
在vc++中程序中用了srandom()和random(),頭文件為stdlib.h,但編譯出現(xiàn)錯(cuò)誤error C3861: “srandom”: 找不到標(biāo)識(shí)符。
原因是現(xiàn)在vc++編譯器的庫(kù)函數(shù)中沒(méi)有randomize()和random(),分別用srand()和rand()代替了。
#include <time.h> //定義關(guān)于時(shí)間的函數(shù)
一般在用到time(NULL)(當(dāng)前時(shí)間)函數(shù)時(shí)需要包含此頭文件
#include <stdlib.h> //定義雜項(xiàng)函數(shù)及內(nèi)存分配函數(shù)
一般在用到rand()和srand()函數(shù)時(shí)需要包含此頭文件
函數(shù)名: random 功 能: 隨機(jī)數(shù)發(fā)生器,也就是產(chǎn)生一個(gè)隨機(jī)數(shù)
用 法: int random(int num);
產(chǎn)生的隨機(jī)數(shù)范圍為0~num-1。
函數(shù)名: randomize
功 能: 初始化隨機(jī)數(shù)發(fā)生器,相當(dāng)于撥隨機(jī)種子
用 法: 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;
- }
一般情況下可以設(shè)置當(dāng)前時(shí)間為種子 srandom((int)time(0));
需要多次取隨即數(shù)時(shí),可以將上次拿到的隨即數(shù)作為種子
posted on 2012-03-29 15:15
憤怒的考拉 閱讀(1212)
評(píng)論(0) 編輯 收藏