How to use std::normal_distribution in C++

In this tutorial, will learn about the normal distribution class in C++.

Header file used: <random.h>

We use it to generate random numbers according to the Normal random number distribution.

std::normal_distribution in C++

µ : mean or expectation of the distribution.

σ : standard deviation. The variance of the distribution is σ^2.

The result type is the real numbers.

While using normal_distubution we use parameter mean and standard deviation.

We use the following code to generate random number in C++ through std:normal_distribution:

C++ code example of std:normal_distribution

#include <iostream>
#include <string>
#include <random>
using namespace std;
int main()
{
   int n=100;  // number of experiments
   int f=10;    // maximum number to distribute

   default_random_engine generator;
   normal_distribution<double> distribution(2.0,1.0);

  int d[5];

  for (int i=0; i<n; i++) 
  {
    double number = distribution(generator);
    if ((number>=0.0)&&(number<5.0)) 
         ++d[int(number)];           //frequency distribution for randomly generated number 
  }

  cout << "normal_distribution:" << endl;

  for (int i=0; i<5; ++i) 
  {
   cout << i << "-" << (i+1) << ": ";
   cout << d[i]*f/n<< endl;
 }

  return 0;
}
OUTPUT:

normal_distribution:                                                                                                                           

0-1: 16395560                                                                                                                                  

1-2: 3280                                                                                                                                      

2-3: 419730                                                                                                                                    

3-4: 1                                                                                                                                         

4-5: 0

Leave a Reply

Your email address will not be published. Required fields are marked *