mardi 3 mars 2020

Random Number Sequence in C++ [duplicate]

I am trying to generate a random number sequence. I have the following function

//Returns a random number between lb and hb
double rand_num(double lb, double hb){

    mt19937 gen(time(nullptr));

    uniform_real_distribution<> dis(lb, hb);

    return dis(gen);
}

If I call this function for the same bounds over and over again, I get a different value so it seems to work. However, when I put it in this loop to generate the sequence it just returns the same value

for(int i = 0; i<10000; i++){
    myfile << i << " " << rand_num(0,1) << endl;
}

I do acknowledged that I am getting the warning random number generator seeded with a disallowed source of seed, but I don't understand this since time(nullptr) is different every time I call it. If anyone could help me understand what is going on and/or tell me how successfully generate the sequence, that would be much appreciated. Thanks in advanced!

Edit: Now I know that "if you run your function in a loop they will be executed faster than the time resolution interval so all the seeds are the same and therefore the numbers." However, I still don't know how to generate a sequence instead of a single random number.




Aucun commentaire:

Enregistrer un commentaire