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.


The files mt.h and 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,, is included in the distribution along with more a complex example, which shows how to seed the MersenneTwister class.

// 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;

    // 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;


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