首页 > 解决方案 > 使用模板在 C++ 中生成随机数的高斯分布

问题描述

我编写了下面的代码来生成遵循高斯分布的随机数,使用std::normal_distribution<double> distribution(5.0,2.0);. 为了检查我是否得到了正确的高斯分布,我还编写了代码,以便将生成的数字分箱到文件gaussian.dat中。但是,我在文件中看到的是常量值:

ith_bin   number_of_counts 
-0.12   0
-0.12   0
-0.12   0
-0.12   0
-0.12   0
-0.12   0
-0.12   0
  .     .
  .     .
  .     .

谁能告诉我问题出在哪里?这是代码:

// normal_distribution
#include <iostream>
#include <string>
#include <random>
#include <math.h>
#include <fstream>

using namespace std ;

void gasdev(double& number);

int main(){

    double number,delta;
    int npts=100,ii,i,ibin,maxbin=500 ;
    double histog [250]{} ;

    delta = 10.0/maxbin ;
    for (i=1 ; i<=npts ; ++i) {

        gasdev(number) ;
        ibin = round(number/delta) ;
        if (abs(ibin) < maxbin/2.0) {
            histog[ibin] = histog[ibin] + 1 ;
        }
    }

    ofstream myfile1;
    myfile1.open("gaussian.dat", ios:: trunc) ;

    for (ii=-250; ii<=250; ++ii){
        myfile1 << ibin*delta << "\t" << histog[ibin]/(npts*delta) << "\n";}

    myfile1.close();

 }

void gasdev(double& number){

    double rnd ;

    default_random_engine generator;
    normal_distribution<double> distribution(0.0,1.0);

    rnd = distribution(generator);

    number=rnd ;

}

标签: c++gaussian

解决方案


I think you have two problems

  1. Take the default_random_engine generator; outside of gasdev so that they do not reset the same seed inside the loop.
  2. As others have suggested the loop for (ii=-250; ii<=250; ++ii) is writing the same line all the time.

推荐阅读