I have multiple runs through a loop and try to create a different, but pseudo-random integer-number in every run. Unfortunately the first number created is always 0.
Interestingly this is only the case for the generation of random integers via std::uniform_int_distribution<int>. If I replace it for std::uniform_real_distribution<double> I obtain the desired behaviour.
Are there any special rules to follow when creating the seed or why is the first generated integer always 0?
Below a minimal example of my problem:
#include <iostream>
#include <random>
int main() {
int number_of_runs = 5;
for (int i = 0; i != number_of_runs; ++i) {
// create random engine
std::default_random_engine my_generator;
unsigned my_seed = i; // should be pseudo-random, but different for every run
my_generator.seed(my_seed);
// create distribution
int upper_limit = (i+1)*10; // only example, but different for every run
std::uniform_int_distribution<int> my_distribution(0, upper_limit);
// create random numbers
std::cout << "run #" << i+1 << "\n";
std::cout << "random 1: " << my_distribution(my_generator) << "\n";
std::cout << "random 2: " << my_distribution(my_generator) << "\n";
std::cout << "random 3: " << my_distribution(my_generator) << "\n";
std::cout << "random 4: " << my_distribution(my_generator) << "\n";
std::cout << "random 5: " << my_distribution(my_generator) << "\n" << std::endl;
}
return 0;
}
The result is for example:
run #1:
random 1: 0
random 2: 1
random 3: 8
random 4: 5
random 5: 5
run #2
random 1: 0
random 2: 2
random 3: 15
random 4: 9
random 5: 11
run #3
random 1: 0
random 2: 8
random 3: 15
random 4: 28
random 5: 2
run #4
random 1: 0
random 2: 16
random 3: 10
random 4: 15
random 5: 24
run #5
random 1: 0
random 2: 26
random 3: 1
random 4: 42
random 5: 6
Aucun commentaire:
Enregistrer un commentaire