I am trying to make a Gaussian distribution in visual studio C++ 2010. I want to have different results each time this is run. But when I run this code three times the result is same:
#include <iostream>
#include <random>
int roundnew(double d)
{
return floor(d + 0.5);
}
int main()
{
std::default_random_engine generator;
std::normal_distribution<double> distribution(10,1);
for (int n = 0; n < 12; ++n) {
printf("%d\n",roundnew(distribution(generator)));
}
return 0;
}
The result is
10
9
11
9
10
11
10
9
10
10
12
10
What is problem in my code? It needs seed value in my code, right? You can see the result at run code
You need to seed your random number generator.
Do something like this:
std::random_device rd;
std::default_random_engine generator;
generator.seed( rd() ); //Now this is seeded differently each time.
std::normal_distribution<double> distribution(10,1);
for (int n = 0; n < 12; ++n) {
{
printf("%d\n",roundnew(distribution(generator)));
}
std::random_device
is supposed to generate non-deterministic numbers so it should be good for your seeding purposes. Each program run should create a different seed to your RNG. See: http://en.cppreference.com/w/cpp/numeric/random/random_device (As R. Martinho Fernandes points out some implementations are lacking in this regard so if you are doing something important do check the implementation details.)
For more details about the c++ random number generation see this: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3551.pdf
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments