📄 c++跑出1000個為normal distribution.txt
字号:
//DevC++ 4.9(g++ 3.4.2)
Source code
#include<iostream>
#include<cmath>
#include<ctime>
using namespace std;
double uniform();
double rejection();
const int MAX=1000000;
int main()
{
srand(time(NULL));
for(int i=0;i<MAX;i++)a+=rejection();
cout<<"bar_X="<<a/MAX<<endl; //sample mean
system("pause");
return 0;
}
double rejection()//generate N(0,1) by rejection method
{
double Y;//exp(1)
double U;//uniform(0,1)
do{
Y=(-1)*log(uniform());
U=uniform();
}while(U>exp((-1)*pow(Y-1,2.)/2));
return uniform()<=0.5?Y:-Y; //distribute to Z or -Z
}
double uniform()
{
int k=(int)pow(2.,15.);
return rand()%k/(double)k;
}
------------------------------
Output
bar_X=0.00025193
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -