標題說明了一切,我正在尋找一些最好是獨立的東西,因爲我不想添加更多的庫。因爲我需要它在緊張的高性能環路C/C++算法從不同平臺上的相同種子生成相同的僞隨機數序列?
性能應該不錯。我想這是以隨機程度爲代價的。
標題說明了一切,我正在尋找一些最好是獨立的東西,因爲我不想添加更多的庫。因爲我需要它在緊張的高性能環路C/C++算法從不同平臺上的相同種子生成相同的僞隨機數序列?
性能應該不錯。我想這是以隨機程度爲代價的。
任何特定的僞隨機數生成算法將這樣的表現。 rand
的問題在於沒有說明它是如何實現的。不同的實現將以不同的方式表現,甚至具有不同的品質。
然而,C++ 11提供了新的<random>
標準庫頭包含很多偉大的隨機數生成設施。在內部定義的隨機數引擎是明確定義的,並且在給定相同種子的情況下,將始終產生相同的一組數字。
例如,流行的高質量隨機數引擎是std::mt19937
,這是在一個特定的方式配置的梅森捻線機算法。無論哪臺機器,你在,下面總是會產生相同的一組實數的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;
}
謝謝,我們馬上測試一下。 – dtech 2013-03-19 13:25:31
修復你的代碼std :: mt19337 std :: mt19937 – jonaprieto 2014-11-10 19:07:51
這是真的嗎?像mt19937這樣的東西可以保證在所有平臺上產生相同的結果嗎? – 2016-01-20 11:11:56
這裏有一個Mersenne Twister
這裏is another another PRNG implementation in C。
您可能會發現一個collection of PRNG here。
這裏的簡約經典的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;
}
}
看一看C++ 11 [隨機](http://en.cppreference.com/w/cpp/numeric/random)庫。 – Antoine 2013-03-19 13:21:53
可能DUP http://stackoverflow.com/questions/922358/consistent-pseudo-random-numbers-across-platforms – 2013-03-19 13:22:25
@Antoine - 將它產生在不同的實施方式中相同的序列? – dtech 2013-03-19 13:22:36