使用Box–Muller算法生成符合正态分布(高斯分布)的随机数,C++代码如下:
#include
#include
#include
#include
#include
using namespace std;
double generateGaussianNoise(double mu, double sigma)
{
static const double epsilon = std::numeric_limits::min();
static const double two_pi = 2.0*3.14159265358979323846;
double u1, u2;
do
{
u1 = rand() * (1.0 / RAND_MAX);
u2 = rand() * (1.0 / RAND_MAX);
}
while (u1 <= epsilon);
double z0,z1;
z0 = sqrt(-2.0 * log(u1)) * cos(two_pi * u2);
z1 = sqrt(-2.0 * log(u1)) * sin(two_pi * u2);
return z0 * sigma + mu;
}
void main()
{
srand((unsigned)time(NULL));
unsigned int con=10000;
FILE *fp;
fp=fopen("C:\\Users\\Administrator\\Desktop\\data.txt","w");
for(int i=0;i
验证代码(Mathematica)如下:
SetDirectory[NotebookDirectory[]];
data = Flatten@Import["data.txt", "Data"];
Show[Histogram[data, 50, "ProbabilityDensity"],Plot[PDF[NormalDistribution[0, 8], x], {x, -30, 30},
PlotStyle -> Thick, PlotRange -> All]]
计算结果如下,黄色直方图为C++程序生成的数据,蓝色曲线为正态分布曲线,二者吻合,证明C++程序正确。