好的,這是一個非常奇怪的結果。不同的rand()序列在表達式中產生相同的結果
我有一個MPI程序,其中每個進程必須在固定範圍內生成隨機數(範圍從文件中讀取)。會發生什麼情況是即使我爲每個進程使用不同的值,並且每個進程中生成的數字都不相同,但生成隨機數的表達式仍然會在它們之間產生相同的序列。
這裏的所有相關的代碼:
// 'rank' will be unique for each process
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// seed the RNG with a different value for each process
srand(time(NULL) + rank);
// print some random numbers to see if we get a unique sequence in each process
// 'log' is a uniquely named file, each process has its own
log << rand() << " " << rand() << " " << rand() << std::endl;
// do boring deterministic stuff
while (true)
{
// waitTimeMin and waitTimeMax are integers, Max is always greater than Min
waitSecs = waitTimeMin + rand() % (waitTimeMax - waitTimeMin);
log << "waiting " << waitSecs << " seconds" << std::endl;
sleep(waitSecs);
// do more boring deterministic stuff
}
這裏的每個過程的輸出,用3個過程在範圍[1,9]產生的數字。
過程1:
15190 28284 3149
waiting 6 seconds
waiting 8 seconds
waiting 9 seconds
waiting 4 seconds
過程2:
286 6264 3153
waiting 6 seconds
waiting 8 seconds
waiting 9 seconds
waiting 4 seconds
過程3:
18151 17013 3156
waiting 6 seconds
waiting 8 seconds
waiting 9 seconds
waiting 4 seconds
因此,儘管rand()
清楚地生成不同的數字,表達式來計算waitSecs
仍評估爲所有進程的序列相同。更奇怪的是:如果我再次運行帶有相同參數的程序,只有前3個隨機數字會改變,其餘的「隨機」序列在每次運行中將完全相同!更改數字範圍顯然會產生與此不同的結果,但執行過程中的進程和之間的相同參數始終產生相同的序列:除前3個數字外。
這到底是怎麼回事?
編輯:所以只是爲了看看它的簡單隨機生成和/或低的範圍內,我取代了隨機生成這一行:
waitSecs = waitTimeMin + (int)((double)rand()/((double)RAND_MAX + 1) * (waitTimeMax - waitTimeMin));
而且在範圍內開始產生數[1,99]。這裏的結果:
過程1:
7833 3798 10977
waiting 1 seconds
waiting 20 seconds
waiting 58 seconds
waiting 35 seconds
waiting 82 seconds
waiting 18 seconds
過程2:
25697 14547 10980
waiting 1 seconds
waiting 20 seconds
waiting 58 seconds
waiting 35 seconds
waiting 82 seconds
waiting 18 seconds
過程3:
10794 25295 10984
waiting 1 seconds
waiting 20 seconds
waiting 58 seconds
waiting 35 seconds
waiting 82 seconds
waiting 18 seconds
同樣的事情。這仍然只是rand()
真的很糟糕?
EDIT2:1生成號碼10000
檢查是否真的是rand()問題: log <<「min」<< waitTimeMin <<「max」<< waitTimeMax << endl; – 2010-04-04 17:43:21
在每種情況下打印您正在播種srand()的值。 – 2010-04-04 18:15:12
做了那個Neil:過程1爲X,過程2爲X + 1,過程3爲X + 2等。 – suszterpatt 2010-04-04 18:22:21