I am writing a fairly large research based tool in C++ (which I am not too familar with). I have a static member function which looks similar to:
void SomeClass::get_n_rand_nums(int n, int nums[], double weights[]);
The purpose of this function is to choose n numbers between a closed interval [a, b]. These numbers should be put in the array nums. However, these numbers should be chosen randomly according to a set of weights.
Essentially the purpose is to choose an index to a different array at random, but elements with higher values stored in their array should be chosen with a higher probability. Similar to how a game drop table would be implemented. The only different is I want this to be done n times.
This is achieved by choosing a random double from a uniform distribution over the range from 0 to the sum of the weights, e.g.:
std::random_device rd;
std::mt19937 rng(rd());
std::uniform_real_distribution<double> uni(0, weights_sum);
double doub = uni(rng);
And then iterating through from 0 to the length of the array, and subtracting the weight at the index until the sum is <= 0. Once this condition is satisfied it returns the loop iteration to get a random index.
The function works as expected when it is first called. However, when it is called for a second time the double doub is always -nan. And I can't figure out why!
Any help would be much appreciated.
Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire