vendredi 20 juillet 2018

Passing random engine through a function - why different compiler behaves differently

For your convenient to illustrate this issue, I made the minimalist codes as below. The codes look innocent but the results are surprising! I tried on different compiler on my Mac and PC. The gcc seems fine but the clang provides incorrect results. My guess is that it may be some undefined behavior. The Mac results show repeat pattern of non-random number. Why this happens?

Here are the codes

#include <iostream>
#include<random>
using namespace std;

class FillUpX{
public:
    FillUpX(default_random_engine eng):generator{eng}{};
    void printValue(){
        for(int i=0;i<10;++i){
            cout << rnorm(generator) << endl;
        }
    }

private:
    default_random_engine & generator;
    std::normal_distribution<> rnorm{0,1};
};


int main(){

    unsigned seed=10;
    std::default_random_engine gen{seed};


    FillUpX fhd(gen);
    fhd.printValue();

   return 0;
}

Here are the outputs

-0.361197
1.67039
-0.361197
1.67039
-0.361197
1.67039
-0.361197
1.67039
-0.361197
1.67039

Aucun commentaire:

Enregistrer un commentaire