The Mersenne Twister in C++

The Mersenne Twister is a very fast random number generator of period 219937–1 introduced by Makoto Matsumoto and Takuji Nishimura. This is a C++ version of the Mersenne Twister based on the original C code written by the authors of the algorithm.

Note: A faster variant, the SIMD-oriented Fast Mersenne Twister (SFMT) was introduced by Mutsuo Saito and Makoto Matsumoto in 2006.

Usage

The files mt.h and mt.cc define the MersenneTwister class. Below is a simple example illustrating the usage of the class which takes 1,000,000 draws from the Uniform(0,1) distribution and calculates the mean. This file, mtex.cc, is included in the distribution along with more a complex example, mttest.cc which shows how to seed the MersenneTwister class.

// mtex.cc: Calculates the sample mean of 1,000,000 draws from U(0,1).

#include <iostream>
#include "mt.h"

using namespace std;

int main (int argc, char** argv) {
    int N = 1000000;
    double ran[N];
    double mean = 0.0;

    // Initialize a Mersenne Twister
    MersenneTwister mt;
    mt.print();

    // Take N draws from Uniform(0,1)
    for (int i = 0; i < N; i++) {
        ran[i] = mt.random();
    }

    // Calculate the mean
    for (int i = 0; i < N; i++) {
        mean += ran[i];
    }
    mean /= N;

    cout << "Sample mean of " << N << "draws:" << mean << endl;

    return EXIT_SUCCESS;
}

Download

The entire distribution can be downloaded as a tarball: mt.tar.gz.