3

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

shuttle87
  • 15,466
  • 11
  • 77
  • 106
user3677103
  • 195
  • 2
  • 3
  • 11
  • 1
    possible duplicate of [Random number generation in C++11 , how to generate , how do they work?](http://stackoverflow.com/questions/7114043/random-number-generation-in-c11-how-to-generate-how-do-they-work) – pdresselhaus Jun 10 '14 at 15:51

1 Answers1

4

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

shuttle87
  • 15,466
  • 11
  • 77
  • 106
  • 1
    FWIW `std::random_device` *may* generate non-deterministic numbers. Some popular implementations still don't. – R. Martinho Fernandes Jun 10 '14 at 16:01
  • @R.MartinhoFernandes I was under the impression that the standard mandated that `std::random_device` generated non-deterministic numbers if the platform could do that. Are the implementations where `std::random_device` is deterministic non-conforming or have I misunderstood something? In any case I edited the answer to mention this. – shuttle87 Jun 10 '14 at 16:13
  • @shuttle87 according to the standard, a program can test if non-deterministic numbers can be generated by testing if `entropy() > 0` (but even that is unreliable in practice... see http://en.cppreference.com/w/cpp/numeric/random/random_device/entropy). I honestly don't like it, but the standard does allow an implementation to have a PRNG behind it. – R. Martinho Fernandes Jun 10 '14 at 16:23