As a complete beginner to C++, I would like to generate a random number from a normal distribution.
With the following code (derived from this post), I am able to do so:
#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;
}
Since the code is quite elaborate (in my view), I thought that there might be a more straightforward solution:
#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;
}
While I can generate a random number, it is continuously the same number. That leads to two questions:
(1) Why is that happing and how do I fix this?
(2) Is there another easier way to generate random numbers?