Loading [MathJax]/extensions/tex2jax.js
ExRandom  3.0
All Classes Namespaces Files Functions Variables Typedefs Friends Macros Pages
Simple examples
Forward to Getting started. Up to Contents.

Here is how to sample exactly from the normal distribution. The code is simple_normal.cpp

#include <iostream>
#include <random>
int main() {
unsigned s = std::random_device()(); // Set seed from random_device
std::mt19937 g(s); // Initialize URNG
std::cout << "Seed set to " << s << "\n\n";
std::cout
<< "Sampling doubles exactly from the unit normal distribution:\n";
for (int i = 0; i < 48; ++i)
std::cout << N(g) << ((i + 1) % 8 ? ' ' : '\n');
std::cout << "\n";
}

Compile this code with a C++11 compliant compiler setting the include path to the parent of the exrandom directory, e.g.,

g++ -o simple_normal -O3 -std=c++11 -I../include simple_normal.cpp

Running the resulting program gives, for example,

Seed set to 1930225588

Sampling doubles exactly from the unit normal distribution:
-0.86918 -2.04981 1.62507 0.37086 -0.0259856 0.179536 -1.37951 2.17251
0.608488 0.700322 -1.26223 0.0148746 -1.10179 0.155343 -0.0498893 -0.298053
-1.12402 1.1431 0.355696 -0.203227 -1.35181 -0.0228599 -1.4729 -0.333065
-1.25213 1.47739 -0.159445 1.27897 -0.649038 0.915326 0.0316318 1.33156
0.135598 -1.1963 1.02445 0.195189 0.0944316 1.89514 0.928068 -0.933905
0.0120612 0.293793 1.84805 1.12541 -1.44845 0.183437 0.676166 1.68539

In this example you can substitute unit_exponential_distribution or unit_uniform_distribution for unit_normal_distribution; you can also change double, the template parameter for the constructor, to float or to long double (or even to a multi-precision floating point type, see Multi-precision floating-point types). See simple_exponential.cpp and simple_uniform.cpp.

And here is how to sample exactly from the discrete normal distribution. The code is simple_discrete_normal.cpp

#include <iostream>
#include <random>
int main() {
unsigned s = std::random_device()(); // Set seed from random_device
std::mt19937 g(s); // Initialize URNG
std::cout << "Seed set to " << s << "\n\n";
std::cout
<< "Sampling exactly from the discrete normal distribution,\n"
<< " mu = " << N.mu_num() << "/" << N.mu_den()
<< ", sigma = " << N.sigma_num() << "/" << N.sigma_den() << ":\n";
for (int i = 0; i < 100; ++i)
std::cout << N(g) << ((i + 1) % 20 ? ' ' : '\n');
std::cout << "\n";
}

Running this program gives, for example,

Seed set to 3530269933

Sampling exactly from the discrete normal distribution,
  mu = 1/3, sigma = 129/2:
66 37 -17 107 -108 34 -51 -8 29 -55 31 111 7 -122 36 -43 39 67 31 -65
-39 106 -11 91 -45 -49 -32 16 -90 53 61 56 -122 46 -37 -53 -39 10 -34 -69
39 -83 -46 -58 -5 -24 77 -65 51 -38 77 -55 -20 -24 27 -110 119 40 -2 10
42 53 69 244 -5 2 21 -9 -119 -4 -38 -86 67 -33 -21 115 -121 61 56 19
66 -30 63 37 19 -38 50 -23 122 -59 3 88 75 66 -15 -107 15 105 -38 85
Forward to Getting started. Up to Contents.