views:

224

answers:

1

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.

+2  A: 

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().

peterchen