mardi 2 juin 2015

How to make a member function of a class in C++ generate a different random number each time it is called?

I have a class which also includes a random number engine and its distribution:

#include <iostream>
#include <cmath>
#include <random>
#include <chrono>

class C
{ 
  public:
      typedef std::mt19937_64 engine;
      typedef std::uniform_real_distribution<double> distribution;
      .
      .
      .

  protected:
      engine rng;
      distribution dist;
      void func();
      .
      .
      .
};

Since the constructor is called only once, I put the seed in it:

C::C()
{   .
    .
    .  
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    distribution dist(0.0, pow(10,12));
    engine rng(seed);
}

The following member function is supposed to generate a random number and is going to be called lots of times in a single run of the program:

void C::func()
{    .
     .
     .
     double randNum = floor(dist(rng));
     std::cout << randNum << std::endl;      
     .
     .
     .
}

However, each time it generates the number 0 as the random number. It seems that dist(rng) is not doing its job.

I really need to find the problem and correct the output. I would appreciate any help.




Aucun commentaire:

Enregistrer un commentaire