Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number from normal distribution in C++

Tags:

c++

c++17

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?

like image 439
user213544 Avatar asked Mar 17 '20 11:03

user213544


People also ask

How do you find the random number in a normal distribution?

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.

How do you create a random variable in a normal distribution?

NORMINV Function You can use the RAND() function to establish probability and create a random variable with normal distribution.

What does rand () generate in C?

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.


1 Answers

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;
}
like image 129
FaisalM Avatar answered Oct 02 '22 23:10

FaisalM