C/ c++算法在不同平台上从相同的种子产生相同的伪随机数序列

C/C++ algorithm to produce same pseudo-random number sequences from same seed on different platforms?

本文关键字:种子 随机数序列 c++ 算法 平台      更新时间:2023-10-16

标题说明了一切,我正在寻找一些最好是独立的东西,因为我不想添加更多的库。

性能应该很好,因为我需要它在一个紧密的高性能循环中。我想这是以牺牲随机性为代价的。

任何特定的伪随机数生成算法都是这样的。rand的问题是它没有指定它是如何实现的。不同的实现将以不同的方式表现,甚至具有不同的质量。

然而,c++ 11提供了新的<random>标准库头,其中包含许多很棒的随机数生成工具。其中定义的随机数引擎是定义良好的,并且给定相同的种子,将始终产生相同的数字集。

例如,std::mt19937是一种流行的高质量随机数引擎,它是经过特定配置的Mersenne捻线算法。无论您使用的是哪台机器,下面的代码总是会生成0到1之间相同的实数集:

std::mt19937 engine(0); // Fixed seed of 0
std::uniform_real_distribution<> dist;
for (int i = 0; i < 100; i++) {
  std::cout << dist(engine) << std::endl;
}

这是一个mason Twister

这是另一个在c中实现的另一个PRNG。

你可以在这里找到PRNG的集合。

下面是简单的经典PRNG:

#include <iostream>
using namespace std;
unsigned int PRNG()
{
    // our initial starting seed is 5323
    static unsigned int nSeed = 5323;
    // Take the current seed and generate a new value from it
    // Due to our use of large constants and overflow, it would be
    // very hard for someone to predict what the next number is
    // going to be from the previous one.
    nSeed = (8253729 * nSeed + 2396403); 
    // Take the seed and return a value between 0 and 32767
    return nSeed  % 32767;
}
int main()
{
  // Print 100 random numbers
    for (int nCount=0; nCount < 100; ++nCount)
    {
        cout << PRNG() << "t";
        // If we've printed 5 numbers, start a new column
        if ((nCount+1) % 5 == 0)
            cout << endl;
    }
}