0

我知道这种问题已经被问过几次了,但其中很多答案都归结为 RTFM,但我希望如果我能提出正确的问题......我可以为其他人得到一个准明确的答案好吧,关于实施。

我正在尝试通过以下两种方式之一生成随机数序列:

#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);
 }

myRand() 在哪里:

#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;
}

每次我运行选项 1 时,每次执行每个循环都会得到相同的数字。但在每次运行程序时都不同。

当我运行选项 2 时,我从 boost 库中得到 82,因此返回 0.81999999999999。我可以理解它是否是 42,但即使在阅读了 boost random 文档之后,82 也让我摸不着头脑。

有任何想法吗?

DJ。

4

1 回答 1

3

使用选项 2,您不应该为每个调用创建一个新实例rngdie

我也不确定我是否正确理解选项 1 的问题:您只调用 srand() 一次,但每次调用 rand() 都会给您相同的号码?那是..“不寻常”。尝试将循环减少到最小,并打印从 rand() 返回的值。

于 2009-11-11T23:50:37.760 回答