Correct use of s/rand or Boost::random

╄→尐↘猪︶ㄣ 提交于 2019-12-13 05:49:52

问题


I know this kind of question has been asked a few times, but alot of them answers boil down to RTFM, but I'm hoping if I can ask the right question... I can get a quasi-definitive answer for everyone else as well, regarding implementation.

I'm trying to generate a sequence of random numbers in one of the two following ways:

#include <cstdlib>
#include <ctime>
#include <cmath>

#include "Cluster.h"
#include "LatLng.h"

 srand((unsigned)time(0));
 double heightRand;
 double widthRand;
 for (int p = 0; p < this->totalNumCluster; p++) {

  Option 1.
  heightRand = myRand();
  widthRand = myRand();

  Option 2.
  heightRand = ((rand()%100)/100.0);
  widthRand = ((rand()%100)/100.0);

  LatLng startingPoint( 0, heightRand,  widthRand );
  Cluster tempCluster(&startingPoint);
  clusterStore.insert( clusterStore.begin() + p, tempCluster);
 }

Where myRand() is:

#include <boost/random.hpp>

double myRand()
{
 boost::mt19937 rng;
 boost::uniform_int<> six(1,100);

 boost::variate_generator<boost::mt19937&, boost::uniform_int<> > die(rng, six);

 int tempDie = die();
 double temp = tempDie/100.0;

 return temp;
}

Every time I run Option 1, I get the same number on each execution of each loop. But different on each run of the program.

When I run Option 2, I get 82 from the boost libraries, so 0.81999999999999 is returned. I could understand if it was 42, but 82 is leaving me scratching my head even after reading the boost random docs.

Any ideas?

DJS.


回答1:


With option 2, you shouldn't create a new instance of rng and die for each call.

I'm also not sure if I understand the problem with option 1 correctly: you are calling srand() only once, but each call to rand() gives you the same number? That's.. "unusual". Try to reduce the loop to the minimum, and print the value returned from rand().



来源:https://stackoverflow.com/questions/1718854/correct-use-of-s-rand-or-boostrandom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!