jeudi 29 septembre 2016

uniform_real_distribution not giving uniform distribution

I am trying to generate high quality random numbers in the range (0,1) in my project and I tried testing the uniform_real_distributionfrom a sample code from here. When I ran it the code it worked fine but when I tried to modify the same with seeding the generator like:

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

using namespace std;
// obtain a seed from the system clock:
unsigned seed = static_cast<int> (chrono::system_clock::now().time_since_epoch().count());

// globally defining the generator and making it static for safety because in the
// actual project this might affect the flow.

static default_random_engine gen(seed);
uniform_real_distribution<double> distribution(0.0,1.0);

int main(){
  const int nrolls=10000;  // number of experiments
  const int nstars=95;     // maximum number of stars to distribute
  const int nintervals=10; // number of intervals

  int p[nintervals]={};

  for (int i=0; i<nrolls; ++i) {
    double number = distribution(gen);
    ++p[int(nintervals*number)];
  }

  std::cout << "uniform_real_distribution (0.0,1.0):" << std::endl;
  std::cout << std::fixed; std::cout.precision(1);

  for (int i=0; i<nintervals; ++i) {
    std::cout << float(i)/nintervals << "-" << float(i+1)/nintervals << ": ";
    std::cout << std::string(p[i]*nstars/nrolls,'*') << std::endl;
  }

  return 0;

}

The random numbers were not uniformly distributed. The output of the same when executed repeatedly is:

F:\path>randtest

uniform_real_distribution (0.0,1.0):

0.0-0.1: *********

0.1-0.2: **********

0.2-0.3: ********

0.3-0.4: *********

0.4-0.5: *********

0.5-0.6: *********

0.6-0.7: *********

0.7-0.8: *********

0.8-0.9: *********

0.9-1.0: **********

F:\path>randtest

uniform_real_distribution (0.0,1.0):

0.0-0.1: *********

0.1-0.2: *********

0.2-0.3: *********

0.3-0.4: *********

0.4-0.5: *********

0.5-0.6: *********

0.6-0.7: *********

0.7-0.8: *********

0.8-0.9: *********

0.9-1.0: *********

F:\path>randtest

uniform_real_distribution (0.0,1.0):

0.0-0.1: *********

0.1-0.2: *********

0.2-0.3: *********

0.3-0.4: *********

0.4-0.5: **********

0.5-0.6: *********

0.6-0.7: *********

0.7-0.8: *********

0.8-0.9: *********

0.9-1.0: *********

Is it because of the seeding? or is it better to use a different generator?

I use G++ 5.1.0 compiler c++11 standards.

Aucun commentaire:

Enregistrer un commentaire