[英]Correct use of s/rand or Boost::random
我知道这种问题已经问过几次了,但很多答案都归结为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;
}
每次我运行Option 1时,每个循环的每次执行都会得到相同的数字。 但是每次运行该程序都不同。
当我运行选项2时,我从boost库中得到82,因此返回0.81999999999999。 我可以理解是否是42岁,但即使在阅读了boost随机文档后,82还是让我挠头。
有任何想法吗?
DJS。
使用选项2时,您不应为每个呼叫创建rng
的新实例die
。
我也不确定我是否正确理解了选项1的问题:您只调用srand()一次,但是每次调用rand()都给您相同的号码吗? 那是..“不寻常的”。 尝试将循环减少到最小,并打印rand()返回的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.