使用模板在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 ;

}

解决方法

我认为您有两个问题

  1. default_random_engine generator;放在gasdev之外,以免它们在循环内重置相同的种子。
  2. 正如其他人所建议的那样,循环for (ii=-250; ii<=250; ++ii)一直在写同一行。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...