C++ 使用C+生成随机数+;TR1
我试图从正态分布生成随机数。当代码:C++ 使用C+生成随机数+;TR1,c++,random,distribution,tr1,normal-distribution,C++,Random,Distribution,Tr1,Normal Distribution,我试图从正态分布生成随机数。当代码: normal(eng) 出现在main()中,程序工作正常。但是,如果它是从另一个函数调用的,那么main的下一个调用将返回先前生成的相同值。下面是一些说明这一点的代码。输出的前几行是: -0.710449 -0.710449 0.311983 0.311983 1.72192 1.72192 0.303135 0.303135 0.456779 0.456779 有人知道为什么会这样吗 编译器是Windows上的GCC4.4.1 #include &l
normal(eng)
出现在main()中,程序工作正常。但是,如果它是从另一个函数调用的,那么main的下一个调用将返回先前生成的相同值。下面是一些说明这一点的代码。输出的前几行是:
-0.710449
-0.710449
0.311983
0.311983
1.72192
1.72192
0.303135
0.303135
0.456779
0.456779
有人知道为什么会这样吗
编译器是Windows上的GCC4.4.1
#include <iostream>
#include <cmath>
#include <ctime>
#include <tr1/random>
typedef std::tr1::ranlux64_base_01 Engine;
//typedef std::tr1::mt19937 Engine;
typedef std::tr1::normal_distribution<double> Normal;
double random_normal(Engine eng, Normal dist) {
return dist(eng);
}
int main ( int argc, char** argv ) {
Engine eng;
eng.seed((unsigned int) time(NULL));
Normal normal(0,1);
for (int i = 0; i < 100; i++)
{
std::cout << random_normal(eng, normal) << std::endl;
std::cout << normal(eng) << std::endl;
}
return 0;
}
#包括
#包括
#包括
#包括
typedef std::tr1::ranlux64_base_01发动机;
//typedef std::tr1::mt19937发动机;
typedef std::tr1::正态分布正态分布;
双随机_正常(发动机发动机,正常距离){
返回区(英语);
}
int main(int argc,字符**argv){
发动机工程;
eng.seed((无符号整数)时间(NULL));
正常(0,1);
对于(int i=0;i<100;i++)
{
std::cout之所以会发生这种情况,是因为您正在按值将引擎传递给random_normal。random_normal获取引擎的副本,因此原始引擎的状态不会被修改,直接使用该原始引擎将产生与random_normal相同的结果
如果修改random_normal以引用发动机:
double random_normal(Engine &eng, Normal Dist);
然后,原始引擎将被修改,您将不会得到重复的值。所有标准分布都参考其引擎。例如:
template<class IntType = int>
class uniform_int_distribution
{
...
// generating functions
template<class URNG>
result_type operator()(URNG& g);
模板
类均匀分布
{
...
//母函数
模板
结果类型运算符()(URNG&g);