作为一个完全的C++新手,我想从正态分布中生成一个随机数。
通过以下代码(源自此帖子),我可以实现这个目标:
虽然我可以生成随机数,但它总是相同的数字。 这引出了两个问题: (1) 为什么会这样,如何修复? (2) 是否有其他更简单的方法来生成随机数?
通过以下代码(源自此帖子),我可以实现这个目标:
#include <iostream>
#include <boost/random.hpp>
#include <boost/random/normal_distribution.hpp>
using namespace std;
int main()
{
boost::mt19937 rng(std::time(0)+getpid());
boost::normal_distribution<> nd(0.0, 1.0);
boost::variate_generator<boost::mt19937&,
boost::normal_distribution<> > rnorm(rng, nd);
cout<< rnorm();
return 0;
}
由于代码相当复杂(在我看来),我认为可能有更直接的解决方案:
#include <iostream>
#include <random>
using namespace std;
int main()
{
default_random_engine generator;
normal_distribution<double> distribution(0.0,1.0);
cout << distribution(generator);
return 0;
}
虽然我可以生成随机数,但它总是相同的数字。 这引出了两个问题: (1) 为什么会这样,如何修复? (2) 是否有其他更简单的方法来生成随机数?
<random>
,而不是<boost/random.hpp>
。 - Ted Lyngmo