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?
Using the inverse function is how we will get our set of normally distributed random values. We will use the RAND() function to generate a random value between 0 and 1 on our Y-axis and then get the inverse of it with the NORM. INV function which will result in our random normal value on the X-axis.
NORMINV Function You can use the RAND() function to establish probability and create a random variable with normal distribution.
C library function - rand() The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX. RAND_MAX is a constant whose default value may vary between implementations but it is granted to be at least 32767.
Use a seed to initialize your generator
. Here I am using a time-based seed.
#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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With