随机数的正态分布会挂起程序



当我运行这段代码时,它只是挂在循环中,你能解释为什么吗?

#include<iostream>
#include<random>
#include<ctime>
int main()
{
    using std::cout;
    using std::endl;
    using std::cin;
    using std::mt19937;
    using std::minstd_rand;
    using std::uniform_int;
    using std::normal_distribution;
    // engines
    mt19937 rng;
    minstd_rand gen;
    // distributions
    uniform_int<int> dist(0, 37);
    normal_distribution<short> norm(4, 3);
    // initializaiton
    rng.seed(static_cast<unsigned int>(time(false)));
    gen.seed(static_cast<unsigned short>(time(false)));

    // generate numbers
    for(int i = 0; i < 10; ++i)
        std::cout << dist(rng) << "     " << norm(gen) << endl; // This is as far as this code goes
    cin.get();
    return 0;
}

std::uniform_int不是C++11。您应该使用 std::uniform_int_distribution .std::normal_distribution<T>要求T为浮点类型(C++11 标准 26.5.8.5.1)。

事实上,如果你有 gcc>= 4.5,你应该得到一个错误,如下:

/opt/local/include/gcc47/c++/bits/random.h: In instantiation of 'class std::normal_distribution<short int>':
my_random.cpp:21:36:   required from here
/opt/local/include/gcc47/c++/bits/random.h:1982:7: error: static assertion failed: template argument not a floating point type

它对我有用。

这些函数可能试图从/dev/random获取随机数据,如果没有高质量的随机数据可用,则会阻塞。我注意到这在廉价的VPS托管服务提供商上很常见。

编辑:如果我们分享开发环境的详细信息,也许会有所帮助。为我工作:

  • 乌班图10.10
  • G++ 4.4.5
  • 提升 1.40
  • 使用 g++ main.cpp -std=c++0x -o tst 编译
我想

我可以猜到。您应该为正态分布生成器提供一个引擎,该引擎生成 0..1 范围内的浮点数。相反,它被错误地喂食了整数饮食。正态分布的常用算法成对使用这些数字,并循环直到找到一对,该对被认为是 2 空间中的点,其笛卡尔范数小于 1 且不等于零。由于算法只提供整数,因此永远不会发生这种情况。但它从未放弃。

最新更新