正确使用S /兰特或增强::随机 [英] Correct use of s/rand or Boost::random

查看:120
本文介绍了正确使用S /兰特或增强::随机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这样的问题已经被问了几次,但很多人答案归结为RTFM,但我希望如果我能提出正确的问题...我能得到一个准确切的答案其他人还有,关于执行

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

在哪里myRand()是:

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

我每次运行选项1,我得到每个循环的每次执行相同的号码。但在节目的每次运行不同的。

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.

当我运行选项2,我从Boost库82,所以返回0.81999999999999。我能理解,如果它是42,但82离开我抓我的头,甚至阅读升压随机文档后。

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.

任何想法?

DJS。

推荐答案

通过选项2,你不应该创建 RNG 模具为每次调用。

With option 2, you shouldn't create a new instance of rng and die for each call.

我也不能肯定我的理解与选择正确1问题:您呼叫srand()函数只有一次,但每次调用RAND()给你相同数量?这是...不寻常。尽量减少循环到最小,并打印()从兰特的返回值。

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

这篇关于正确使用S /兰特或增强::随机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆