用模板生成C++中随机数的高斯分布
我编写了下面的代码,使用std::normal_distribution 5.0,2.0;生成高斯分布之后的随机数;。为了检查是否得到了正确的高斯分布,我还编写了代码,以便将生成的数字存储到Gaussian.dat文件中。但是,我在文件中看到的是常量值,如下所示:用模板生成C++中随机数的高斯分布,c++,gaussian,C++,Gaussian,我编写了下面的代码,使用std::normal_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 . . . .
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 ;
}
我想你有两个问题 取默认的随机引擎生成器;在gasdev之外,这样它们就不会在循环内重置相同的种子。
正如其他人所建议的那样,ii的循环为-250;我不使用本地生成器,在main中创建一个并将其传递给函数。与当前在循环中调用srand类似。请不要使用术语C/C++,因为没有这样的语言。特别是在同一句话中,你提到了两种截然不同的语言中没有的功能;二,