c++ - 使用模板在 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 ;
}
解决方案
I think you have two problems
- Take the
default_random_engine generator;
outside ofgasdev
so that they do not reset the same seed inside the loop. - As others have suggested the loop
for (ii=-250; ii<=250; ++ii)
is writing the same line all the time.
推荐阅读
- github - 我想使用 github 操作测试我的工具功能
- python - Dask - 大型合并和 map_partitions/apply - 挂在最后几个任务上
- jwt - 使用 Cognito 的用户池作为 API 网关的授权方时验证了哪些声明
- android - 始终授予位置返回许可
- javascript - 无法更改 this.state 属性:无法读取未定义的属性“setState”
- angular - 有人可以用 Angular 形式解释我的这种语法吗#name="ngModel"
- c# - 将彩色非 ASCII 字符打印到 CLI
- monitoring - 使用 java datadog 代理发送 KafkaStreams jmx 指标
- python - 照片转换 2d 黑白到 3d rgb 照片
- spring-boot - 是否对 Integer 字段进行任何验证以检查 rest api 的确切值?@Min 和 @Max 不起作用