生成通常以c ++分布的不同随机数序列

时间:2015-08-09 12:55:58

标签: c++ c++11 random

我试图生成正态分布的随机数。我使用c ++ 11的随机标题,我得到了随机数,但每当我执行程序时都会保持相同的序列。问题是我如何在执行程序的任何时候获得不同的序列?这是我的代码:

srand(time(NULL));
complex<double> finding[10];
complex<double> com_one(rand(), rand());
complex<double> com_two(rand(), rand());

mt19937 mt(1729);
normal_distribution<float>dist(0,1);
for(int i = 0; i<16; ++i){
cout << dist(mt)<<", ";
}
cout<<"\n\n"<<endl;

for(int i=0;i<10;i++){
    complex<double> com_three(rand(), rand());
    finding[i]= com_three;
}
for (int i =0; i<10;i++){
    cout <<"no "<<i<<" element of the finding array is: ";
    cout <<finding[i]<< endl;
}

cout << "The first complex number is" << endl;
cout << com_one.real() << "+" << com_one.imag()
      << "i" << endl;

1 个答案:

答案 0 :(得分:3)

你得到相同的序列,因为你在这里使用相同的种子初始化引擎:

mt19937 mt(1729); // 1729 is the seed

您需要找到一种方法来设置不同的种子,只要您想要不同的序列。如何执行此操作取决于所需的代码行为。您可以从命令行,配置文件中读取它,或者如果您不关心可重复性,则从非确定性随机设备生成它(请参阅例如std::random_device。)