Reputation: 2425
I would like to change use of rand_r method for srand/rand or with other random generator with seed.
In code there is a loop that call a train method with seed.
int nseeds = 5;
for (int seed = 0; seed < nseeds; seed ++)
{
c.train(K, reps, gradientReps, improveReps, lambda, seed, SYMMETRICDIFF);
}
In train method there are 3 calls for rand_r that I would like to change. I thought that I could call srand at the beginning with given seed and then simply call for rand() method, but I don't know if this is a proper way. What do you think?
void Cluster::train(int K, int reps, int gradientReps, int improveReps, Scalar lambda, int seed, int whichLoss)
{
unsigned int seed_ = seed;
unsigned int* sptr = &seed_;
//srand(seed);
for (int rep = 0; rep < reps; rep ++)
{
for (int k = 0; k < K; k ++)
if (rep == 0 or (int) chat[k].size() == 0 or (int) chat[k].size() == gd->nNodes)
{
for (int i = 0; i < gd->nNodes; i ++)
if (rand_r(sptr) % 2 == 0) chat[k].insert(i);
for (int i = 0; i < gd->nEdgeFeatures; i ++)
theta[k*gd->nEdgeFeatures + i] = 0;
theta[k*gd->nEdgeFeatures + rand_r(sptr)%gd->nEdgeFeatures] = 1.0;
}
for (int k = 0; k < K; k ++)
{
for (int o = 0; o < K; o ++)
{
int x1 = o;
int x2 = rand_r(sptr) % K;
// code
}
}
}
}
Link for source. The above code is in main.cpp and cluster.cpp.
Upvotes: 0
Views: 765
Reputation: 11730
If your compiler supports C++11, I would use the new random number library. If not, you should try Boost random (it's basically the same). I recommend using the mt19937
random number engine, it produces pretty good quality random numbers, and it's also fast.
Then your code will look like this:
std::mt19937 rng;
...
std::uniform_int_distribution dist(0, K - 1);
...
int x2 = dist(rng);
Upvotes: 2