Reputation: 5702
I am trying to get gaussian distribution with mean and sigma in C++11. I have been successful at converting Python to C++ but I have a doubt about the way I am initializing the random generator. Do I need to call random_device() and mt19937() inside the call to get a distribution or can I just call them once statically and re-use those all the time? What is the cost of leaving the code as it is?
# Python
# random.gauss(mu, sigma)
# Gaussian distribution. mu is the mean, and sigma is the standard deviation.
import random
result = random.gauss(mu, sigma)
// C++11
#include <random>
std::random_device rd;
std::mt19937 e2(rd());
float res = std::normal_distribution<float>(m, s)(e2);
Upvotes: 0
Views: 549
Reputation: 9333
There are two parts of the algorithm:
In your case, e2
is your uniform random number generator given the seed rd
, std::normal_distribution<float>(m, s)
generates an object which does the 2nd part of the algorithm.
The best way to do it is:
// call for the first time (initialization)
std::random_device rd;
std::mt19937 e2(rd());
std::normal_distribution<float> dist(m, s);
// bind the distribution generator and uniform generator
auto gen_gaussian = std::bind(dist, e2);
// call when you need to generate a random number
float gaussian = gen_gaussian();
If you don't care about which uniform random number generator to use, you can use std::default_random_engine
instead of std:mt19937
.
Upvotes: 2