在一系列值之间生成随机双精度

时间:2013-02-01 02:22:31

标签: c++ algorithm random prng genetic

我目前无法在-32.768和32.768之间生成随机数。它不断给我相同的值,但十进制字段的变化很小。例如:27.xxx。

继承我的代码,任何帮助都将不胜感激。

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main()
{
    srand( time(NULL) );
    double r = (68.556*rand()/RAND_MAX - 32.768);
    cout << r << endl;
    return 0;
}

5 个答案:

答案 0 :(得分:7)

我应该提一下,如果你使用的是C ++ 11编译器,你可以使用这样的东西,这实际上更容易阅读,更难搞乱:

#include <random>
#include <iostream>
#include <ctime>


int main()
{
    //Type of random number distribution
    std::uniform_real_distribution<double> dist(-32.768, 32.768);  //(min, max)

    //Mersenne Twister: Good quality random number generator
    std::mt19937 rng; 
    //Initialize with non-deterministic seeds
    rng.seed(std::random_device{}()); 

    // generate 10 random numbers.
    for (int i=0; i<10; i++)
    {
      std::cout << dist(rng) << std::endl;
    }
    return 0;
}

正如bames53所指出的,如果你充分利用c ++ 11,上面的代码可以更短:

#include <random>
#include <iostream>
#include <ctime>
#include <algorithm>
#include <iterator>

int main()
{
    std::mt19937 rng; 
    std::uniform_real_distribution<double> dist(-32.768, 32.768);  //(min, max)
    rng.seed(std::random_device{}()); //non-deterministic seed
    std::generate_n( 
         std::ostream_iterator<double>(std::cout, "\n"),
         10, 
         [&]{ return dist(rng);} ); 
    return 0;
}

答案 1 :(得分:0)

我已在您的计划中添加了for循环:

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main () {
    srand(time (NULL));

    for (int i = 0; i < 10; ++i) {
        double r = ((68.556 * rand () / RAND_MAX) - 32.768);

        cout << r << endl;
    }

    return 0;
}

示例输出:

 31.6779 
-28.2096
 31.5672
 18.9916 
-1.57149 
-0.993889
-32.4737
 24.6982
 25.936 
 26.4152

对我来说似乎没关系。我已经为您Ideone添加了代码。

以下是四次运行:

 Run 1:
    -29.0863
    -22.3973
     34.1034
    -1.41155
    -2.60232
    -30.5257
     31.9254
    -17.0673
     31.7522
     28.227

Run 2:
    -14.2872
    -0.185124
    -27.3674
     8.12921
     22.4611
    -0.414546
    -21.4944
    -11.0871
     4.87673
     5.4545

Run 3:
    -23.9083
    -6.04738
    -6.54314
     30.1767
    -16.2224
    -19.4619
     3.37444
     9.28014
     25.9318
    -22.8807

Run 4:
     25.1364
     16.3011
     0.596151
     5.3953
    -25.2851
     10.7301
     18.4541
    -18.8511
    -0.828694
     22.8335

也许你不会在两次跑步之间等待至少一秒钟?

答案 2 :(得分:0)

所以,我认为这是一个典型的例子,“使用时间(NULL)不是为一起开始的运行播种随机数的好方法”。 time(NULL)从一个调用到下一个调用的位数没有那么多,因此随机数非常相似。这不是一个新现象 - 如果你谷歌“我的随机数字不是很随机”,你会发现很多这个。

有一些不同的解决方案 - 获得微秒或纳秒时间将是最简单的选择 - 在Linux gettimeofday中将为您提供一个微秒时间作为结构的一部分。

答案 3 :(得分:0)

它接缝显然很明显,但有些例子说不然......但我想当你将1 int与另一个分开时你总是得到一个int?并且你需要在分割它们之前键入cast each int to double / float。

ie:double r =(68.556 *(double)rand()/(double)RAND_MAX - 32.768);

如果你每次调用rand()时都调用srand(),你重置种子会导致每次返回类似的值,而不是''random''。

答案 4 :(得分:0)

此外,如果您不使用c ++ 11,则可以改用以下功能:

template< class U = T >
optional& operator=( U&& value );