This question already has an answer here:
I was thinking to generate random normal with a fixed seed for reproducible research. To illustrate my question well, I made the following minimalist codes. It reports error when I put the random generator in a class. What's wrong with the first code block? How can I fix it? Many thanks for your help!
#include <iostream>
#include <random>
using namespace std;
class RandNorm{
private:
unsigned seed = 12345;
std::default_random_engine generator(seed);
std::normal_distribution<> rnorm(0,1);
public:
double getrnorm(){
return rnorm(generator);
}
};
int main() {
RandNorm x;
cout << x.getrnorm() << endl;
return 0;
}
But it works well it I just put in in the main function as below
#include <iostream>
#include <random>
using namespace std;
int main() {
unsigned seed = 12345;
std::default_random_engine generator(seed);
std::normal_distribution<> rnorm(0,1);
for(int i=1; i<10; i++){
cout << rnorm(generator) << endl;
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire