s/rand 또는 boost의 올바른 사용 :: 랜덤
문제
나는 이런 종류의 질문이 몇 번 묻는 것을 알고 있지만, 그들 중 많은 사람들이 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를 실행하면 부스트 라이브러리에서 82를 얻으므로 0.81999999999999가 반환됩니다. 42 세인지 이해할 수 있었지만 82 명이 부스트 임의의 문서를 읽은 후에도 머리를 긁어 내고 있습니다.
어떤 아이디어?
DJ.
해결책
옵션 2를 사용하면 새 인스턴스를 만들어서는 안됩니다. rng
그리고 die
각 호출에 대해.
또한 옵션 1의 문제를 올바르게 이해하는지 확실하지 않습니다. SRAND ()에게 한 번만 호출하지만 Rand ()에 대한 각 호출은 동일한 번호를 제공합니까? 그건 .. "비정상적". 루프를 최소값으로 줄이고 rand ()에서 반환 된 값을 인쇄하십시오.
제휴하지 않습니다 StackOverflow