我想知道如何使用我的个人计算机和集群生成完全相同的随机数。
下面是一个简单的代码。
#include <iostream>
#include <random>
int main()
{
int N = 10;
for (int j = 0; j < N; j++) std::cout << rand() % 10 << " ";;
}我的个人电脑的输出结果是:1 7 4 0 9 4 8 8 2 4
集群的输出为:3 6 7 5 3 5 6 2 9 1
这些随机数的差异将严重影响我的计算。此外,我的问题非常灵活,我不能使用从我的个人计算机生成的随机数,并将其用作集群上的输入。我希望在不同的平台上生成相同的随机数。
/新尝试:我尝试了链接中的解决方案:If we seed c++11 mt19937 as the same on different machines, will we get the same sequence of random numbers
我使用了以下代码:
#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;
}在我的PC上,我得到了输出:5 10 4 1 4 10 8 4 8 4 4
在集群上,我得到了:6 6 8 9 7 9 6 9 5 7
尽管如此,它还是不同的。
谁能给我一个代码的例子?
非常感谢。
发布于 2020-06-09 17:12:49
This question解释说,你从下面得到的数字序列
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 ...。对于相同的reason why,这些数字不是均匀分布的,而rand() % 10产生的数字则不是。如果你不太关心随机数的质量,这可能是一个可以接受的解决方案。
发布于 2020-06-09 02:47:19
你可以很容易地为随机函数使用一个固定的种子。这样做,您将始终在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++随机机器生成伪随机序列。您可以使用它们获得相同的结果,但分布更精确,无论如何,这不是什么大问题。
https://stackoverflow.com/questions/62268894
复制相似问题