質問

私はこの種の質問が数回尋ねられたことを知っていますが、彼らの回答の多くはRTFMに要約されますが、私は正しい質問をすることができるかどうかを望んでいます...私は他のすべての人のために準定義的な答えを得ることができますまあ、実装に関して。

次の2つの方法のいずれかで一連の乱数を生成しようとしています。

#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を使用すると、の新しいインスタンスを作成しないでください rngdie 通話ごとに。

また、オプション1の問題を正しく理解しているかどうかはわかりません。Srand()を1回だけ呼び出していますが、RAND()への各呼び出しは同じ番号を与えますか?それは..「珍しい」。ループを最小限に抑え、Rand()から返された値を印刷してください。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top