vendredi 24 février 2017

Using default_random_engine as a class member and without a class results in different numbers (same seed)

I want to have a separate class for random number generation in my program. I tried to use the std::default_random_engine as a class member and then generate random vectors with functions. When I compared the results to the generation of random numbers without a class, I noticed that for uneven dimensions one random number in the sequence is skipped. For example (of course not random):
1,2,3 & 5,6,7 & 9,10,11 (sequence with class) 1,2,3 & 4,5,6 & 7,8,9 (sequence without class)

For even dimensions both sequences are the same. So I tried to make a sample code to illustrate the differences.

In this example I also noticed that (in the case of 4-dim) also an additional number is sampled as the first number (for the case without a class). If I use another distribution e.g. uniform, there was not such a difference.

Has somebody an idea what I am doing wrong? Do I maybe initialize the generator to often?

I appreciate any help.

Small example code:

#include <random>
#include <iostream>

class RandomGenerator{
  public:
    RandomGenerator(int seed):generator_(seed){}
    void generateGaussian(int dim){
      std::normal_distribution<double> distribution(0.,1.);
      for(int i=0; i<dim;++i){
        std::cout<<distribution(generator_)<<std::endl;
      }
    }
  private:
    std::default_random_engine generator_;
};

int main(){
  std::normal_distribution<double> distribution(0.,1.);

  std::cout<<std::endl<<"With Class - 4dim"<<std::endl;
  RandomGenerator random_generator4=RandomGenerator(912134);

  random_generator4.generateGaussian(4);
  std::cout<<"***"<<std::endl;
  random_generator4.generateGaussian(4);
  std::cout<<"***"<<std::endl;
  random_generator4.generateGaussian(4);

  std::cout<<std::endl<<"Without Class"<<std::endl;
  std::default_random_engine generator4(912134);
  for(int i=0; i<15;++i){
    std::cout<<distribution(generator4)<<std::endl;
    if((i+1)%4==0){
        std::cout<<"***"<<std::endl;
    }
  }

  std::default_random_engine generator(912134);
  RandomGenerator random_generator=RandomGenerator(912134);
  std::cout<<"With Class - 3dim "<<std::endl;
  random_generator.generateGaussian(3);
  std::cout<<"***"<<std::endl;
  random_generator.generateGaussian(3);
  std::cout<<"***"<<std::endl;
  random_generator.generateGaussian(3);


  std::cout<<std::endl<<"Without Class"<<std::endl;
  for(int i=0; i<11;++i){
    std::cout<<distribution(generator)<<std::endl;
    if((i+1)%3==0){
        std::cout<<"***"<<std::endl;
    }
  }
  return 0;
}




Aucun commentaire:

Enregistrer un commentaire