mercredi 14 février 2018

Generating a re-producible sample of random numbers from a Gaussian distribution in c++

I'm simply trying to generate a sample of random numbers that are chosen from a Gaussian distribution which has a mean m and variance v. What I'm doing is:

#include <iostream>
#include <math.h>
#include <random>

using namespace std;

int main()
{
    double m;
    double v;
    double s; //seed
    int samplesize=10;
    double ls [samplesize]; //to store as a list

    m = 0.0;
    v = 0.05;
    random_device rd;
    s = rd();
    mt19937 e2(s);

    normal_distribution<float> dist(m, sqrt(v));
    for (int i=0; i<samplesize; i++){
        ls[i] = dist(e2);
        cout << ls[i] << endl;
    }

    return 0;
}

This works fine, but the problem is even when I use the same seed s instead of randomizing it with random_device, I still do not get the same sample set (or simply the same list ls).

  1. How can I make my routine reproducible? Should I save the whole mt19937 e2(s) state?

  2. If instead of single scalars, we want to generate 3D vectors chosen from a Gaussian distribution (so each element of ls contains now 3 components), would it be correct to simply loop 3 times over dist(e2) in order to generate the 3 components? And in doing so generate all the random vectors.




Aucun commentaire:

Enregistrer un commentaire