均匀随机数在所有相同的运行
问题描述:
我发现在范围产生均匀随机数(AA,BB),如下的方法:均匀随机数在所有相同的运行
#include <random>
double randnum (double aa, double bb) //defining a function to create random numbers
{
static std::default_random_engine generator;
std::uniform_real_distribution<double> distribution (aa,bb);
return distribution(generator);
}
int main(){
for (i=1;i<50;i++){
cout<< randnum(0,1);
}
}
例如,randnum(0,1);创建一个0到1之间的随机数。问题是,在不同的运行过程中,我在for循环中创建的随机序列完全相同。如何在不同的运行过程中创建不同的随机数字?
答
使用非确定性的随机数引擎的种子更高性能的,确定性的一个,像梅森倍捻机:
#include <iostream>
#include <random>
double randnum (double aa, double bb) { //defining a function to create random numbers
static std::random_device rd; // non-deterministic, but may be slow
static std::mt19937 engine{ rd() };
std::uniform_real_distribution<double> distribution (aa,bb);
return distribution(engine);
}
int main() {
for(int i=1; i<50; i++) {
std::cout<< randnum(0,1);
}
}
+0
当然,我忘了添加它。 – Jodocus
您重新发电机每次调用,重置种子。 –
我该如何避免它? @Someprogrammerdude –
您需要一些外部熵源,因为随机引擎是随机引擎 –