mardi 21 avril 2020

Create a vector of user defined type that has uniform random distribution as private member with reproducible results

Hard to resume in the title. I have got the following situation:

#include <random>

class classRng{

public:

    classRng(){
    }
    classRng(int aSeed){
        Rng.seed(aSeed);
    }

    void setSeed(int seed){
        Rng.seed(seed);
    }

    std::vector<int>& getResults(){
        return extractedNum;
    }

    void run(int low, int up);

private:

    std::vector<int> extractedNum;

    mutable std::mt19937 Rng;

    std::uniform_int_distribution<> randomUniformGenerator;


};

void classRng::run(int low,int up){

    decltype(randomUniformGenerator.param()) range(low, up);
    randomUniformGenerator.param(range);
    extractedNum.clear();

    for(int i=0;i<10;i++){
        extractedNum.push_back(randomUniformGenerator(Rng));
    }

}

This class extracts numbers from a distribution initiliazed with a seed for reproducibility. I want to underline that feed the RNG with a fixed and static seed is in my case mandatory in order to reproduce results.

Another class, say targetClass is parameterized with classRng in this way:

template<class stochaticClass>
class targetClass{

public:

    targetClass(){}
    targetClass(stochaticClass _extr){
        extr=_extr;
    }

    void foo();

    stochaticClass& stochasticClassAccess(){
        return extr;
    }

private:

    stochaticClass extr;
    std::vector<int> storedResults;

};

template<class stochasticClass>
void targetClass<stochasticClass>::foo(){

    extr.run(1,30);
    storedResults = extr.getResults();

}

I want then create a vector of targetClass objects whose class method foo() produces different results. In the main() function I proceed as follow:

#include "classRng.cpp"
#include "targetClass.cpp"

int main(int argc, char *argv[])
{

    int N=10;

    typedef targetClass<classRng> targetType;

    std::vector<targetType> objects(N);
    int seed=0;
    classRng instatiatedObj(seed);

    for(int i=0;i < N; i++){
        targetType thisObject(instatiatedObj);
        objects[i]=thisObject;
        objects[i].foo();
    }

}

I would like to achieve the situation where each object in the vector produces different results ( store different results in storedResults) but produce the very same results with another run of the executable. I show my last approach after try to firstly set with a setter function the classRng and later I tried simply to build each targetClass with the default constructor without explicitly use the custom constructor with classRng instatiatedObj as argument.




Aucun commentaire:

Enregistrer un commentaire