Generate random numbers following a normal distribution in C/C++

C++CServer Side ProgrammingProgramming

Here we will see how to generate random numbers, which are following in a normal distribution. For the normal random, the formula is like below.

𝑧 = √−2 ln 𝑥1 cos (2𝜋𝑥2)

Here x1 and x2 are chosen randomly.

Example

#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;
   }
}

Output

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
raja
Published on 03-May-2019 06:55:51
Advertisements