生成不同的正态分布的随机数序列

Generation of different sequence of random numbers that are normally distributed in c++

本文关键字:正态分布 随机数序列      更新时间:2023-10-16

我试图生成正态分布的随机数。我在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<<"nn"<<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;

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

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

当你想要一个不同的序列时,你需要找到一种方法来设置不同的种子。如何做到这一点取决于代码的预期行为。您可以从命令行、配置文件中读取它,或者如果您不关心再现性(参见例如std::random_device),则可以从非确定性随机设备中生成它。