c++ - 创建具有均值和标准差的高斯随机发生器

标签 c++ random gaussian normal-distribution

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

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

最佳答案

C++11 中,使用 random header 相对简单。和 std::normal_distribution ( live example ):

#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 也提供了一个库( live example ):

#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 transform ,链接中提供的代码看起来很合理。

关于c++ - 创建具有均值和标准差的高斯随机发生器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19944111/

相关文章:

java - 如何比较两个具有随机构造函数的对象

c# - XNA + HLSL 高斯模糊产生偏移伪影

c# - 高斯平滑公式应用

c++ - 简单的 constexpr 函数无法用 GCC 编译(clang 没问题)

c++ - 检查磁盘是否插入到保留分区

algorithm - 寻找一种更智能的方法来随机拆分一维值范围

python - 使用 matplotlib 绘制缩放和旋转的二元分布

c++ - 为什么代码以线性方式比以循环方式运行得慢?

c++ - 检查初始化列表中的空 vector

Python:将随机数添加到文件名(不重复数字)