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

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

性能应该很好,因为我需要一个紧凑的高性能循环。 我想这将以随机程度为代价。

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

但是,C ++ 11提供了新的标准库头,其中包含许多优秀的随机数生成工具。 其中定义的随机数引擎是明确定义的,并且在给定相同种子的情况下,将始终产生相同的数字集。

例如,流行的高质量随机数引擎是std::mt19937 ,它是以特定方式配置的Mersenne twister算法。 无论您使用哪台机器,以下内容始终会生成介于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; } 

这是一个Mersenne Twister

这是C中的另一个PRNG实现 。

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

这是简单的经典PRNG:

 #include  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; } }