jeudi 22 février 2018

Using a header file to define mt19937 and normal_distribution

I am using the following routine to generate random numbers chosen from a Gaussian/Normal distribution:

When everything is in a single file to compile it's rather straightforward:

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

using namespace std;

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

    m = 0.0;
    v = 0.05;
    mt19937 e2(seed);

    normal_distribution<float> dist(m, sqrt(v));

  for (int i=0; i<samplesize; i++){
        ls[i] = dist(e2);
        cout << ls[i] << endl;
    }

    return 0;
}

Now I am trying to do something similar but I'd like to be able to define e2 and the dist globally, or simply first in a hearder file .h and then call them in various .C files of my program. My attempts keep running into error: invalid use of non-static member function ‘std::mt19937 e2(int)’ kind of errors.

The aim is to:

  • Define e2 and dist in a header file.
  • Seed the e2 in a .C file that loads a file of parameters containing where the seed is given.
  • Use dist(e2) in my .C files whereever I have to generate such number.

My attempt:

In the header file I have written:

#include <random>

std::mt19937 e2(int sd); //sd for seed to be read from file later.
std::normal_distribution<float> dist(double meanNormal, double varNormal); //define generally, mean and var to be read from file.

Then in my setup.C file where I read the parameters I try to generate an instance of e2 and dist:

e2(seed); //seed read from file before.
dist(mean,sqrt(var)); //mean and var are double variables defined in this file. 

Now in my main program file, when I try to generate a number from dist using dist(e2) I get a non-static member function error as shown above. Any help in how to achieve this would be much appreciated.




Aucun commentaire:

Enregistrer un commentaire