Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) GetRandomNormal

 

STLQt CreatorLubuntu

 

GetRandomNormal is a random code snippet to draw a value from a normal distribution with average 'mean' and a standard deviation of 'sigma'.

Technical facts

 

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: ./CppGetRandomNormal/CppGetRandomNormal.pro

 

include("../../ConsoleApplication.pri")
SOURCES += main.cpp

 

 

 

 

 

./CppGetRandomNormal/main.cpp

 

#include <iostream>
#include <random>


///GetRandomNormal draws a random number from a normal distribution
///with average mean and standard deviation of sigmal.
///From http://www.richelbilderbeek.nl/CppGetRandomNormal.htm
double GetRandomNormal(const double mean = 0.0, const double sigma = 1.0)
{
  //rd is used only to initialize mt with a truly random seed
  static std::random_device rd;
  //mt generates random numbers
  static std::mt19937 mt(rd());
  //d puts these random numbers in the correct distribution
  std::normal_distribution<double> d(mean,sigma);
  //The random value x gets drawn here
  const double x{d(mt)};
  return x;
}

int main()
{
  for (int i=0; i!=10; ++i)
  {
    const double x{GetRandomNormal()};
    std::cout << x << '\n';
  }
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml