16

我正在尝试创建一个一维数组并使用随机数生成器(生成平均值为 70 且标准差为 10 的随机数的高斯生成器)用至少 100 个介于 0 和 100 之间的数字填充数组。

我将如何在C++中执行此操作?

4

4 回答 4

28

C++11中,使用随机标头std::normal_distribution现场示例)相对简单:

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

int main()
{
    std::random_device rd;

    std::mt19937 e2(rd());

    std::normal_distribution<> dist(70, 10);

    std::map<int, int> hist;
    for (int n = 0; n < 100000; ++n) {
        ++hist[std::round(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不是一个选项,那么boost还提供了一个库(现场示例):

#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
#include <boost/random.hpp>
#include <boost/random/normal_distribution.hpp>

int main()
{

  boost::mt19937 *rng = new boost::mt19937();
  rng->seed(time(NULL));

  boost::normal_distribution<> distribution(70, 10);
  boost::variate_generator< boost::mt19937, boost::normal_distribution<> > dist(*rng, distribution);

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

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

如果由于某种原因这些选项都不可能,那么您可以滚动自己的Box-Muller 变换,链接中提供的代码看起来很合理。

于 2013-11-13T02:34:51.290 回答
11

使用 Box Muller 分布(从这里):

double rand_normal(double mean, double stddev)
{//Box muller method
    static double n2 = 0.0;
    static int n2_cached = 0;
    if (!n2_cached)
    {
        double x, y, r;
        do
        {
            x = 2.0*rand()/RAND_MAX - 1;
            y = 2.0*rand()/RAND_MAX - 1;

            r = x*x + y*y;
        }
        while (r == 0.0 || r > 1.0);
        {
            double d = sqrt(-2.0*log(r)/r);
            double n1 = x*d;
            n2 = y*d;
            double result = n1*stddev + mean;
            n2_cached = 1;
            return result;
        }
    }
    else
    {
        n2_cached = 0;
        return n2*stddev + mean;
    }
}

您可以在以下位置阅读更多信息:wolframe 数学世界

于 2015-02-16T22:21:56.837 回答
4

在 C++11 中,您将使用<random>头文件提供的工具;创建一个随机引擎(例如std::default_random_enginestd::mt19937std::random_device必要时使用初始化)和一个std::normal_distribution使用您的参数初始化的对象;然后你可以一起使用它们来生成你的数字。在这里你可以找到一个完整的例子。

相反,在以前的 C++ 版本中,您所拥有的只是“经典” C LCG ( srand/ rand),它只生成 [0, MAX_RAND] 范围内的普通整数分布;有了它,您仍然可以使用Box-Muller 变换生成高斯随机数。(注意 C++11 GNU GCC libstdc++'sstd::normal_distribution使用Marsaglia polar 方法可能很有用,如此处所示。)。

于 2013-11-13T02:35:35.443 回答
2

#include <random>

std::default_random_engine de(time(0)); //seed
std::normal_distribution<int> nd(70, 10); //mean followed by stdiv
int rarrary [101]; // [0, 100]
for(int i = 0; i < 101; ++i){
    rarray[i] = nd(de); //Generate numbers;
}
于 2013-11-13T02:33:37.410 回答