2009-07-10 212 views
8

我想知道如果在C++标准库中有任何高斯分布数字生成器,或者如果你有任何代码段传递。C++:生成高斯分布

在此先感谢。

+0

AC代码片段可用于类似的,[稍后的问题(点击这里)](http://stackoverflow.com/questions/17995894/normalgaussian-distribution-function-in-c/23609868#23609868) – jcollomosse 2014-05-12 13:46:56

回答

15

标准库没有。然而,Boost.Random的确如此。如果我是你,我会使用它。

6

GNU科学图书馆具有此功能。 GSL - Gaussian Distribution

+0

“将有“? – jalf 2009-07-10 13:55:22

+0

大声笑,我写了之前,我抬起头的答案...我想我应该改变它:) – 2009-07-10 14:37:53

13

C++技术报告1增加了对随机数生成的支持。因此,如果您使用的是相对较新的编译器(visual C++ 2008 GCC 4.3),则可能是开箱即用的。

请参阅here了解std::tr1::normal_distribution(以及更多)的样本用法。

+1

如果它还没有,你可以找到它作为Boost的一部分:http://www.boost。组织/ DOC /库/ 1_39_0/DOC/HTML/boost_tr1/subject_list.html#boost_tr1.subject_list.random – stephan 2009-07-10 14:55:15

4

此问题的答案随C++ 11更改,其中包含random header,其中包括std::normal_distribution。沃尔特布朗的文章N3551, Random Number Generation in C++11可能是这个图书馆更好的介绍之一。

下面的代码说明了如何使用该标头(see it live):

#include <iostream> 
#include <iomanip> 
#include <map> 
#include <random> 

int main() 
{ 
    std::random_device rd; 

    std::mt19937 e2(rd()); 

    std::normal_distribution<> dist(2, 2); 

    std::map<int, int> hist; 
    for (int n = 0; n < 10000; ++n) { 
     ++hist[std::floor(dist(e2))]; 
    } 

    for (auto p : hist) { 
     std::cout << std::fixed << std::setprecision(1) << std::setw(2) 
        << p.first << ' ' << std::string(p.second/200, '*') << '\n'; 
    } 
} 

我提供的实施例以随机数产生在C++ 11在回答一个更一般的设置为C++ random float number generation与例如在Boost中也使用rand()