Example
Back to Introduction. Forward to Code organization. Up to Contents.

The following gives a quick idea of the capabilities of the library. Note that the classes are all defined in the RandomLib namespace.

  #include "RandomLib/Random.hpp"

  unsigned u; unsigned long long l;
  float f; double d; long double e; bool b;
  RandomLib::Random r;
  std::cout << "Seed set to: " << r.SeedString() << std::endl;

  f = r.FixedU<float>();      // result in (0,1] with 24 bits of randomness
  d = r.Fixed();              // result in [0,1) with 53 bits of randomness
  e = r.FixedN<long double>(); // result in [0,1] with 64 bits of randomness
  d = r.FloatN();   // a random in [0,1] rounded to the nearest double
  u = r.Integer();            // a random unsigned in [0,2^32)
  l = r.Integer<unsigned long long>(); // a random unsigned long long
  u = r.Integer<16>();        // a random unsigned in [0,2^16)
  u = r.Integer(52U);         // a random unsigned in [0,52)
  u = r(52);     // the same, enables passing r to std::random_shuffle
  u = r.IntegerC(1,6);        // a random integer in [1,6]
  b = r.Boolean();            // true with prob 1/2
  b = r.Prob(4, 7);           // true with prob 4/7
  b = r.Prob(0.34);           // true with prob 0.34

  #include "RandomLib/NormalDistribution.hpp"

  RandomLib::NormalDistribution<> g;
  d = g(r);                   // sample from normal distribution

  #include "RandomLib/ExponentialDistribution.hpp"

  RandomLib::ExponentialDistribution<> x;
  d = x(r);                   // sample from exponential distribution

Here is a more fleshed out example. Compile, link, and run this with, for example

g++ -I.. -O2 -funroll-loops -o RandomExample RandomExample.cpp Random.cpp
./RandomExample

(Note that the -funroll-loops is important!) This example also compiles and runs under Windows with Visual C++.

/**
 * \file RandomExample.cpp
 * \brief Example of use of RandomSeed, MT19937, Random, etc.
 *
 * Compile/link with, e.g.,\n
 * g++ -I.. -O2 -funroll-loops -o RandomExample RandomExample.cpp Random.cpp\n
 * ./RandomExample
 *
 * Written by Charles Karney <charles@karney.com> and licensed under the LGPL.
 * For more information, see http://randomlib.sourceforge.net/
 **********************************************************************/
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include "RandomLib/Random.hpp"
#include "RandomLib/NormalDistribution.hpp"
#include "RandomLib/RandomSelect.hpp"

#define RANDOMEXAMPLE_CPP "$Id: RandomExample.cpp 6723 2010-01-11 14:20:10Z ckarney $"
RCSID_DECL(RANDOMEXAMPLE_CPP)
RCSID_DECL(NORMALDISTRIBUTION_HPP)
RCSID_DECL(RANDOMSELECT_HPP)

int main() {
  RandomLib::Random r;          // r created with random seed
  std::cout << "Using " << r.Name() << "\n"
            << "with seed " << r.SeedString() << std::endl;
  {
    std::cout << "Estimate pi = ";
    size_t in = 0, num = 10000;
    for (size_t i = 0; i < num; ++i) {
      const double x = r.FixedS(); // r.FixedS() is in the interval (-1/2, 1/2)
      const double y = r.FixedS();
      if (x * x + y * y < 0.25)
        ++in;                   // Inside the circle
    }
    std::cout << (4.0 * in) / num << std::endl;
  }
  {
    std::cout << "Tossing a coin 20 times: ";
    for (size_t i = 0; i < 20; ++i)
      std::cout << (r.Boolean() ? "H" : "T");
    std::cout << std::endl;
  }
  {
    std::cout << "Throwing a pair of dice 15 times:";
    for (size_t i = 0; i < 15; ++i)
      std::cout << " " << r.IntegerC(1,6) + r.IntegerC(1,6);
    std::cout << std::endl;
  }
  {
    // Weights for throwing a pair of dice
    unsigned w[] = { 0, 0, 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1 };
    // Initialize selection
    RandomLib::RandomSelect<unsigned> sel(w, w + sizeof(w)/sizeof(unsigned));

    std::cout << "Another 20 throws:";
    for (size_t i = 0; i < 20; ++i)
      std::cout << " " << sel(r);
    std::cout << std::endl;
  }
  {
    std::cout << "Draw balls from urn containing 5 red and 5 white balls: ";
    int t = 10, w = 5;
    while (t)
      std::cout << (r.Prob(w, t--) ? w--, "W" : "R");
    std::cout << std::endl;
  }
  {
    std::cout << "Shuffling the digits 0..9: ";
    std::string digits = "0123456789";
    std::random_shuffle(digits.begin(), digits.end(), r);
    std::cout << digits << std::endl;
  }
  {
    std::cout << "Estimate mean and variance of normal distribution: ";
    double m = 0;
    double s = 0;
    int k = 0;
    RandomLib::NormalDistribution<> n;
    while (k++ < 10000) {
      double x = n(r);
      double m1 = m + (x - m)/k;
      s += (x - m) * (x - m1);
      m = m1;
    }
    std::cout << m << ", " << s/(k - 1) << std::endl;
  }
  {
    typedef float real;
    enum { prec = 4 };
    std::cout << "Some low precision reals (1/"
              << (1<<prec) << "): ";
    for (size_t i = 0; i < 5; ++i)
      std::cout << " " << r.Fixed<real, prec>();
    std::cout << std::endl;
  }
  std::cout << "Used " << r.Count() << " random numbers" << std::endl;
  try {
    // This throws an error if there's a problem
    RandomLib::MRandomGenerator32::SelfTest();
    std::cout << "Self test of " << RandomLib::MRandomGenerator32::Name()
              << " passed" << std::endl;
    RandomLib::MRandomGenerator64::SelfTest();
    std::cout << "Self test of " << RandomLib::MRandomGenerator64::Name()
              << " passed" << std::endl;
    RandomLib::SRandomGenerator32::SelfTest();
    std::cout << "Self test of " << RandomLib::SRandomGenerator32::Name()
              << " passed" << std::endl;
    RandomLib::SRandomGenerator64::SelfTest();
    std::cout << "Self test of " << RandomLib::SRandomGenerator64::Name()
              << " passed" << std::endl;
  }
  catch (std::out_of_range& e) {
    std::cerr << "Self test FAILED: " << e.what() << std::endl;
    return 1;
  }
  return 0;
}

Typical output from this program is:

Using RandomEngine<SFMT19937<Random_u32>,MixerSFMT>
with seed [360536,1209342001,31919,562196172,2008]
Estimate pi = 3.1384
Tossing a coin 20 times: HTHTTHHHHHHHHTTHTTTH
Throwing a pair of dice 15 times: 8 5 2 11 5 10 8 3 5 2 9 6 11 7 12
Another 20 throws: 7 7 8 8 9 10 8 9 10 11 9 4 5 4 9 4 11 6 5 8
Draw balls from urn containing 5 red and 5 white balls: RWWWWRRWRR
Shuffling the digits 0..9: 3804916527
Estimate mean and variance of normal distribution: 0.00602807, 0.975485
Some low precision reals (1/16):  0.1875 0.75 0.4375 0.4375 0.9375
Used 94943 random numbers
Self test of RandomEngine<MT19937<Random_u32>,MixerSFMT> passed
Self test of RandomEngine<MT19937<Random_u64>,MixerSFMT> passed
Self test of RandomEngine<SFMT19937<Random_u32>,MixerSFMT> passed
Self test of RandomEngine<SFMT19937<Random_u64>,MixerSFMT> passed
Back to Introduction. Forward to Code organization. Up to Contents.