【问题标题】:Normal(Gaussian) Distribution Function in C++C++ 中的正态(高斯)分布函数
【发布时间】:2023-03-26 16:10:01
【问题描述】:

我需要知道一种获得 50 个数字的高斯分布的方法。我知道 Boost 库,它生成随机数。就我而言,我不需要随机数;我需要 50 个数字的正态分布。

如何在 C++ 中做到这一点?

【问题讨论】:

  • 概率密度函数(PDF)是正态分布。

标签: c++ gaussian


【解决方案1】:

从 C++11 开始,标准库中有一个正态(高斯)分布:

http://www.cplusplus.com/reference/random/normal_distribution/

平均值和标准差在创建时作为参数传递。上面的链接提供了一个很好的例子:

// normal_distribution
#include <iostream>
#include <random>

int main()
{
  const int nrolls=10000;  // number of experiments
  const int nstars=100;    // maximum number of stars to distribute

  std::default_random_engine generator;
  std::normal_distribution<double> distribution(5.0,2.0);

  int p[10]={};

  for (int i=0; i<nrolls; ++i) {
    double number = distribution(generator);
    if ((number>=0.0)&&(number<10.0)) ++p[int(number)];
  }

  std::cout << "normal_distribution (5.0,2.0):" << std::endl;

  for (int i=0; i<10; ++i) {
    std::cout << i << "-" << (i+1) << ": ";
    std::cout << std::string(p[i]*nstars/nrolls,'*') << std::endl;
  }

  return 0;
}

【讨论】:

    【解决方案2】:

    我认为 OP 要求的是随机数生成器,其中随机数不是均匀分布的(如 C 中的典型 rand() 那样),而是高斯分布的。

    这个改编自“C 中的数字食谱”(Press 等人,1992 年)的简短例程可能有用:

    double grand() {
    
      double r,v1,v2,fac;
    
      r=2;
      while (r>=1) {
        v1=(2*((double)rand()/(double)RAND_MAX)-1);
        v2=(2*((double)rand()/(double)RAND_MAX)-1);
        r=v1*v1+v2*v2;
      }
      fac=sqrt(-2*log(r)/r);
    
      return(v2*fac);
    
    }
    

    ...确保数学函数和 rand 存在相关的#include,并且已调用 srand(time(NULL)) 或类似方法来适当地为 C rand() RNG 提供种子。

    【讨论】:

    • 这个函数的正态分布的均值和标准差是多少?
    • 均值为零,标准差为一。 :-)
    【解决方案3】:

    如果我的问题是正确的,您正在寻找估计的正态分布, 即样本均值和样本方差。

    前者计算为:

    而后者为:

    在高斯分布中,样本均值可以作为期望值,样本方差可以作为:

    如果您想了解更多信息,请查看:

    我希望回答了你的问题;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-22
      • 2016-09-16
      • 2010-11-09
      • 1970-01-01
      相关资源
      最近更新 更多