在 C/C++ 中生成服从正态分布的随机数
下面,我们将了解如何生成服从正态分布的随机数。以下是产生正态随机数的公式。
𝑧 = √−2 ln 𝑥1 cos (2𝜋𝑥2)
其中 x1 和 x2 是随机选取的。
实例
#include <cstdlib> #include <cmath> #include <ctime> #include <iostream> using namespace std; double rand_gen() { // return a uniformly distributed random value return ( (double)(rand()) + 1. )/( (double)(RAND_MAX) + 1. ); } double normalRandom() { // return a normally distributed random value double v1=rand_gen(); double v2=rand_gen(); return cos(2*3.14*v2)*sqrt(-2.*log(v1)); } main() { double sigma = 82.0; double Mi = 40.0; for(int i=0;i<20;i++) { double x = normalRandom()*sigma+Mi; cout << " x = " << x << endl; } }
输出
x = 1.91628 x = 57.0448 x = 51.4348 x = 53.5612 x = -83.8511 x = -28.9197 x = -76.0576 x = 62.1435 x = 23.9 x = -87.0663 x = 50.6942 x = 94.1685 x = -88.1597 x = 168.502 x = 40.7563 x = 90.1091 x = 16.9218 x = -36.9178 x = 135.969 x = 56.8888
广告