[英]How to generate the same random number on personal computer and cluster (c++)
我想知道如何使用我的個人計算機和集群生成完全相同的隨機數。
這是一個簡單的代碼。
#include <iostream>
#include <random>
int main()
{
int N = 10;
for (int j = 0; j < N; j++) std::cout << rand() % 10 << " ";;
}
我個人電腦上的 output 是:1 7 4 0 9 4 8 8 2 4
集群中的 output 為:3 6 7 5 3 5 6 2 9 1
這些隨機數的差異將強烈影響我的計算。 此外,我的問題非常靈活,我不能使用從我的個人計算機生成的隨機數並將其用作集群的輸入。 我希望在不同的平台上生成相同的隨機數。
/////////新嘗試:我嘗試了鏈接中的解決方案: 如果我們在不同的機器上將c++11 mt19937播種為相同,我們會得到相同的隨機數序列
我使用了代碼:
#include <random>
#include <iostream>
int main()
{
/* seed the PRNG (MT19937) using a fixed value (in our case, 0) */
std::mt19937 generator(0);
std::uniform_int_distribution<int> distribution(1, 10);
/* generate ten numbers in [1,10] (always the same sequence!) */
for (size_t i = 0; i < 10; ++i)
{
std::cout << distribution(generator) << ' ';
}
std::cout << std::endl;
return 0;
}
在我的電腦上,我得到了 output:5 10 4 1 4 10 8 4 8 4
在集群上,我得到:6 6 8 9 7 9 6 9 5 7
盡管如此,它還是不同的。
誰能給我一個代碼示例?
非常感謝。
這個問題解釋了您從中獲得的一系列數字
std::uniform_int_distribution<int> distribution(1, 10);
即使您使用具有相同種子的相同 PRNG,也已定義實現。 相比之下,PRNG std::mersenne_twister_engine
產生的隨機數序列在任何符合標准的實現中都是明確定義的。
因此,在不使用外部庫的情況下獲得定義良好的偽隨機數序列的最簡單方法是:
#include <iostream>
#include <random>
int main() {
std::mt19937 generator(0);
while (true) {
const auto rand = generator() % 10;
std::cout << rand << ' ';
}
}
保證此代碼始終產生相同的序列4 9 3 0 3 9 7 3 7 3...
。 這些數字不是均勻分布的,原因與rand() % 10
生成的數字不是均勻分布的原因相同。 如果您不太關心隨機數的質量,這可能是一個可以接受的解決方案。
您可以很容易地為隨機 function 使用固定種子。 這樣做,您將始終在 PC 和集群上得到相同的序列。
#include <iostream>
#include <random>
#define FIXED_SEED 12345 // It can be any integer
int main()
{
int N = 10;
srand(FIXED_SEED)
for (int j = 0; j < N; j++)
std::cout << rand() % 10 << " ";;
}
此外,由於您使用的是 C++,您可以使用 C++ 隨機機來生成偽隨機序列。 您可以使用它們獲得相同的結果,但分布更精確,反正沒什么大不了的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.