RandomLib  1.10
Getting started
Back to Installing RandomLib. Forward to Code organization. Up to Contents.

Look at the code in the examples directory of the distribution for samples of code using RandomLib. In particular see RandomExample.cpp which illustrates several uses of random numbers and RandomCoverage.cpp while illustrates the calling sequence of many of the functions of RandomLib. Both these programs are compiled by default; see Installing RandomLib for details

In order to use RandomLib, you will need to

• Include the header files for RandomLib in your code. For basic random numbers, you will need If you are sampling from the normal distribution, for example, you will also need
• Include the RandomLib:: namespace prefix to the RandomLib classes, or include
using namespace RandomLib;
• Finally compile and link your code. You have two options here.
• Use cmake to build your package. If you are familiar with cmake this typically will be far the simplest option.
• Set the include paths and linking options "manually".
• Building your code with cmake. In brief, the necessary steps are:

• include in your CMakeLists.txt files
    find_package (RandomLib 1.9 REQUIRED)
include_directories (${RandomLib_INCLUDE_DIRS}) add_definitions (${RandomLib_DEFINITIONS})
target_link_libraries (program ${RandomLib_LIBRARIES})  (The add_definitions line is only needed for Windows and can be omitted if you're using cmake version 2.8.11 or later.) • configure your package, e.g., with  mkdir BUILD cd BUILD cmake -G "Visual Studio 10" \ -D CMAKE_PREFIX_PATH=C:/pkg-vc10 \ -D CMAKE_PREFIX_PATH=C:/pkg-vc10/testrandom \ ..  Note that you almost always want to configure and build your code somewhere other than the source directory (in this case, we use the BUILD subdirectory). • build your package. On Linux and MacOS this usually involves just running make. On Windows, you can load the solution file created by cmake into Visual Studio; alternatively, you can get cmake to run build your code with  cmake --build . --config Release --target ALL_BUILD  You might also want to install your package (using "make install" or build the "INSTALL" target with the command above). The most import step is the find_package command. The cmake documentation describes the locations searched by find_package (the appropriate rule for RandomLib are those for "Config" mode lookups). In brief, the locations that are searched are (from least specific to most specific, i.e., in reverse order) are • under the system paths, i.e., locations such as C:/Program Files and /usr/local); • frequently, it's necessary to search within a "package directory" (or set of directories) for external dependencies; this is given by a (semicolon separated) list of directories specified by the cmake variable CMAKE_PREFIX_PATH (illustrated above); • the package directory for RandomLib can be overridden with the environment variable RandomLib_DIR (which is the directory under which RandomLib is installed); • finally, if you need to point to a particular build of RandomLib, define the cmake variable RandomLib_DIR, which specifies the directory containing the configuration file randomlib-config.cmake (for debugging this may be the top-level build directory, as opposed to installation directory, for RandomLib). Typically, specifying nothing or CMAKE_PREFIX_PATH suffices. However the two RandomLib_DIR variables allow for a specific version to be chosen. On Windows systems (with Visual Studio), find_package will only find versions of RandomLib built with the right version of the compiler. (If you used a non-cmake method of installing RandomLib, you can try copying cmake/FindRandomLib.cmake to somewhere in your CMAKE_MODULE_PATH in order for find_package to work. However, this method has not been thoroughly tested.) If RandomLib is found, then the following cmake variables are set: • RandomLib_FOUND = 1 • RandomLib_VERSION = 1.10 • RandomLib_INCLUDE_DIRS • RandomLib_LIBRARIES = one of the following two: • RandomLib_SHARED_LIBRARIES = RandomLib • RandomLib_STATIC_LIBRARIES = RandomLib_STATIC • RandomLib_DEFINITIONS = one of the following two: • RandomLib_SHARED_DEFINITIONS = -DRANDOMLIB_SHARED_LIB=1 • RandomLib_STATIC_DEFINITIONS = -DRANDOMLIB_SHARED_LIB=0 • RandomLib_LIBRARY_DIRS • RandomLib_BINARY_DIRS Either of RandomLib_SHARED_LIBRARIES or RandomLib_STATIC_LIBRARIES may be empty, if that version of the library is unavailable. If you require a specific version, SHARED or STATIC, of the library, add a COMPONENTS clause to find_package, e.g.,  find_package (RandomLib 1.9 REQUIRED COMPONENTS SHARED)  causes only packages which include the shared library to be found. If the package includes both versions of the library, then RandomLib_LIBRARIES and RandomLib_DEFINITIONS are set to the shared versions, unless you include  set (RandomLib_USE_STATIC_LIBS ON)  before the find_package command. You can check whether RandomLib_LIBRARIES refers to the shared or static library with  get_target_property(_LIBTYPE${RandomLib_LIBRARIES} TYPE)

which results in _LIBTYPE being set to SHARED_LIBRARY or STATIC_LIBRARY. On Windows, cmake takes care of linking to the release or debug version of the library as appropriate. (This assumes that the Release and Debug versions of the libraries were built and installed. This is true for the Windows binary installer for RandomLib version 1.9 and later.)

• Here are the steps to compile and link your code using RandomLib "manually".
• Tell the compiler where to find the header files. With g++ and with /usr/local specified as the installation directory, this is accomplished with
    g++ -c -g -O3 -funroll-loops -I/usr/local/include testprogram.cpp
With Visual Studio, specify the include directory in the IDE via, e.g.,
    C/C++ -> General -> Additional Include Directories = C:\pkg-vc10\RandomLib\include
• If using the shared (or static) library with Visual Studio, define the macro RANDOMLIB_SHARED_LIB=1 (or 0), e.g.,
    C/C++ -> Preprocessor -> Preprocessor Definitions = RANDOMLIB_SHARED_LIB=1
This is only needed for Windows systems. (If you configure your package with cmake, this definition is added automatically.)
• Tell the linker the name, Random, and location of the library. Using g++ as the linker, you would use
    g++ -g -o testprogram testprogram.o -L/usr/local/lib -lRandom
With Visual Studio, you supply this information in the IDE via, e.g.,
    Linker -> Input -> Additional Dependencies = Random-i.lib (for shared library)
Linker -> General -> Additional Library Directories = C:\pkg-vc10\RandomLib\lib
Note that the library name is Random and not RandomLib. For the Debug version of your program add "_d" to the library, e.g., Random_d-i.lib or Random_d.lib.
• Tell the runtime environment where to find the shared library (assuming you compiled RandomLib as a shared library). With g++, this is accomplished by modifying the link line above to read
    g++ -g -o testprogram testprogram.o -Wl,-rpath=/usr/local/lib \
-L/usr/local/lib -lRandom
(There are two other ways to specify the location of shared libraries at runtime: (1) define the environment variable LD_LIBRARY_PATH to be a colon-separated list of directories to search; (2) as root, specify /usr/local/lib as a directory searched by ldconfig(8).) On Windows, you need to ensure that Random.dll or Random_d.dll is in the same directory as your executable or else include the directory containing the dll in your PATH.

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

unsigned u; unsigned long long l;
float f; double d; long double e; bool b;
RandomLib::Random r; // create random number object
r.Reseed(); // seed with a "unique" seed
std::cout << "Using " << r.Name() << "\n"
<< "with seed " << r.SeedString() << "\n";
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
d = g(r); // sample from normal distribution
d = x(r); // sample from exponential distribution

Here is a complete example, RandomExample.cpp.

/**
* \file RandomExample.cpp
* \brief Simple examples of use of %RandomLib
*
* g++ -I../include -O2 -funroll-loops
* -o RandomExample RandomExample.cpp ../src/Random.cpp\n
* ./RandomExample
*
* This provides a simple illustration of some of the capabilities of
* %RandomLib.
*
* http://randomlib.sourceforge.net/
**********************************************************************/
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
int main(int, char**) {
RandomLib::Random r; // Create r
r.Reseed(); // and give it a unique seed
std::cout << "Using " << r.Name() << "\n"
<< "with seed " << r.SeedString() << "\n";
{
std::cout << "Estimate pi = ";
size_t in = 0, num = 10000;
for (size_t i = 0; i < num; ++i) {
// x, y are in the interval (-1/2,1/2)
double x = r.FixedS(), y = r.FixedS();
if (x * x + y * y < 0.25) ++in; // Inside the circle
}
std::cout << (4.0 * in) / num << "\n";
}
{
std::cout << "Tossing a coin 20 times: ";
for (size_t i = 0; i < 20; ++i) std::cout << (r.Boolean() ? "H" : "T");
std::cout << "\n";
}
std::cout << "Generate 20 random bits: " << r.Bits<20>() << "\n";
{
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 << "\n";
}
{
// 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 << "A different way of throwing dice:";
for (size_t i = 0; i < 15; ++i) std::cout << " " << sel(r);
std::cout << "\n";
}
{
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 << "\n";
}
{
std::cout << "Shuffling the letters a..z: ";
std::string digits = "abcdefghijklmnopqrstuvwxyz";
std::random_shuffle(digits.begin(), digits.end(), r);
std::cout << digits << "\n";
}
{
std::cout << "Estimate mean and variance of normal distribution: ";
double m = 0, s = 0;
int k = 0;
while (k < 10000) {
double x = n(r), m1 = m + (x - m)/++k;
s += (x - m) * (x - m1); m = m1;
}
std::cout << m << ", " << s/(k - 1) << "\n";
}
{
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 << "\n";
}
std::cout << "Used " << r.Count() << " random numbers\n";
try {
// This throws an error if there's a problem
RandomLib::MRandom32::SelfTest();
std::cout << "Self test of " << RandomLib::MRandom32::Name()
<< " passed\n";
RandomLib::MRandom64::SelfTest();
std::cout << "Self test of " << RandomLib::MRandom64::Name()
<< " passed\n";
RandomLib::SRandom32::SelfTest();
std::cout << "Self test of " << RandomLib::SRandom32::Name()
<< " passed\n";
RandomLib::SRandom64::SelfTest();
std::cout << "Self test of " << RandomLib::SRandom64::Name()
<< " passed\n";
}
catch (std::out_of_range& e) {
std::cerr << "Self test FAILED: " << e.what() << "\n";
return 1;
}
return 0;
}

Typical output from this program is:

Using RandomEngine<SFMT19937<Random_u32>,MixerSFMT>
with seed [273392,1301667572,964,562213576,2011]
Estimate pi = 3.1316
Tossing a coin 20 times: HHTHHHHTHTTHTTTHHTTT
Generate 20 random bits: 10110101000101001001
Throwing a pair of dice 15 times: 3 4 6 5 3 10 8 6 7 7 3 6 12 6 9
A different way of throwing dice: 4 8 10 6 4 9 5 2 5 7 7 6 7 6 3
Draw balls from urn containing 5 red and 5 white balls: RWWWWRWRRR
Shuffling the letters a..z: ibsymngwpcakhujqvdlrtexzfo
Estimate mean and variance of normal distribution: -0.00648971, 0.981155
Some low precision reals (1/16): 0.6875 0 0.5625 0.125 0
Used 94637 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


Here is a complete CMakeList.txt files you can use to build this test code using the installed library:

project (RandomExample)
cmake_minimum_required (VERSION 2.8.4)

find_package (RandomLib 1.9 REQUIRED)

if (NOT MSVC)
endif ()

include_directories (${RandomLib_INCLUDE_DIRS}) add_definitions (${RandomLib_DEFINITIONS})
add_executable (${PROJECT_NAME} RandomExample.cpp) target_link_libraries (${PROJECT_NAME} ${RandomLib_LIBRARIES}) if (MSVC) get_target_property (_LIBTYPE${RandomLib_LIBRARIES} TYPE)
if (_LIBTYPE STREQUAL "SHARED_LIBRARY")
# On Windows systems, copy the shared library to build directory
add_custom_command (TARGET ${PROJECT_NAME} POST_BUILD COMMAND${CMAKE_COMMAND} -E
copy $<TARGET_FILE:${RandomLib_LIBRARIES}> \${CMAKE_CFG_INTDIR}
COMMENT "Copying shared library for RandomLib")
endif ()
endif () 

Certain macros can change the behavior of RandomLib. Define these before the inclusion of RandomLib/Random.hpp in your code. The macros are

• #define HAVE_BOOST_SERIALIZATION 1
allows boost serialization to be used to save and restore the random number state. See Saving and restoring the state.
• #define RANDOMLIB_DEFAULT_GENERATOR name
changes the random number generator used for Random (and RandomGenerator). name should be one of
  MRandomGenerator32
MRandomGenerator64
SRandomGenerator32 (default if unset)
SRandomGenerator64 
The SRandomGeneratorNN generators are recommended. See Selection of default generator.
Back to Installing RandomLib. Forward to Code organization. Up to Contents.