puc*_*cio 9 c++ normal-distribution tr1
我正在尝试使用C++ STD TechnicalReport1扩展来生成正常分布后的数字,但是这段代码(改编自本文):
mt19937 eng;
eng.seed(SEED);
normal_distribution<double> dist;
// XXX if I use the one below it exits the for loop
// uniform_int<int> dist(1, 52);
for (unsigned int i = 0; i < 1000; ++i) {
cout << "Generating " << i << "-th value" << endl;
cout << dist(eng) << endl;
}
Run Code Online (Sandbox Code Playgroud)
只打印1"Generating ..."日志消息,然后永远不会退出for循环!如果我使用我注释掉的发行版,它会终止,所以我想知道我做错了什么.任何的想法?
非常感谢!
小智 7
我最初发布的代码遇到了同样的问题并调查了GNU的实现
首先是一些观察结果:使用g ++ - 4.4并使用代码挂起,使用g ++ - 4.5并使用-std = c ++ 0x(即不是TR1但是真实的东西)上面的代码可以工作
恕我直言,TR1和c ++ 0x之间有关于随机数生成和随机数消耗之间的适配器的变化 - mt19937产生整数,normal_distribution消耗双精度
c ++ 0x自动使用自适应,g ++ TR1代码没有
为了让您的代码使用g ++ - 4.4和TR1,请执行以下操作
std::tr1::mt19937 prng(seed);
std::tr1::normal_distribution<double> normal;
std::tr1::variate_generator<std::tr1::mt19937, std::tr1::normal_distribution<double> > randn(prng,normal);
double r = randn();
Run Code Online (Sandbox Code Playgroud)
这绝对不会挂起程序。但是,不确定它是否真的满足您的需求。
#include <random>
#include <iostream>
using namespace std;
typedef std::tr1::ranlux64_base_01 Myeng;
typedef std::tr1::normal_distribution<double> Mydist;
int main()
{
Myeng eng;
eng.seed(1000);
Mydist dist(1,10);
dist.reset(); // discard any cached values
for (int i = 0; i < 10; i++)
{
std::cout << "a random value == " << (int)dist(eng) << std::endl;
}
return (0);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9925 次 |
| 最近记录: |