简体   繁体   English

将rand_r更改为rand / rand

[英]Change rand_r to srand/rand

I would like to change use of rand_r method for srand/rand or with other random generator with seed. 我想将rand_r方法更改为srand / rand或与其他带有种子的随机生成器一起使用。

In code there is a loop that call a train method with seed. 在代码中,有一个循环调用带种子的train方法。

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. 火车方法中,我想更改rand_r的 3个调用。 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. 我以为可以先从给定的种子开始调用srand ,然后再简单地调用rand()方法,但是我不知道这是否合适。 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. 上面的代码在main.cpp和cluster.cpp中。

If your compiler supports C++11, I would use the new random number library . 如果您的编译器支持C ++ 11,我将使用新的随机数库 If not, you should try Boost random (it's basically the same). 如果不是,您应该尝试Boost Boost random (基本上是一样的)。 I recommend using the mt19937 random number engine, it produces pretty good quality random numbers, and it's also fast. 我建议使用mt19937随机数引擎,它可以产生质量很好的随机数,而且速度也很快。

Then your code will look like this: 然后您的代码将如下所示:

std::mt19937 rng;
...
std::uniform_int_distribution dist(0, K - 1);
...
int x2 = dist(rng);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM