作为 C++ 的完全初学者,我想从正态分布生成一个随机数。
使用以下代码(源自这篇文章),我可以做到这一点:
#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;
}
Run Code Online (Sandbox Code Playgroud)
由于代码非常复杂(在我看来),我认为可能有一个更简单的解决方案:
#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;
}
Run Code Online (Sandbox Code Playgroud)
虽然我可以生成一个随机数,但它始终是相同的数字。这引出了两个问题:
(1) 为什么会发生这种情况以及如何解决这个问题?
(2) 还有其他更简单的方法来生成随机数吗?
使用种子来初始化您的generator. 这里我使用的是基于时间的种子。
#include <iostream>
#include <random>
#include <chrono>
using namespace std;
int main()
{
unsigned seed = chrono::system_clock::now().time_since_epoch().count();
default_random_engine generator(seed);
normal_distribution<double> distribution(0.0, 1.0);
cout << distribution(generator);
return 0;
}
Run Code Online (Sandbox Code Playgroud)