vendredi 24 août 2018

Equivalent C++ implementation of MATLAB's rng(seed, 'twister') function

I'm trying to come up with equivalent ways to generate uniform random variables in MATLAB and C++. In MATLAB, it's straightforward to use the generator rng(0, 'twister') to use seed 0 and the Marsenne Twister engine. And then, for example, 5 uniform random numbers can be produced using rand(5,1). According to MATLAB's rand documentation, it uses the mt19937 engine.

I'm struggling to replicate this in C++. I've used the following code:

#include <iostream>
#include <cmath>
#include <random>

static std::random_device rd;
static std::tr1::mt19937 rand_mt(rd());

int main(void)
{
    rand_mt.seed(0);
    for (int i = 0;i < 5;i++)
    {
        std::cout << (double)rand_mt() / ((double)rand_mt.max() - 
        (double)rand_mt.min()) << std::endl;
    }
    return 0;
}

It's a very long shot, but I'm not getting the same outputs from MATLAB and C++. Any problems with the above code that I need to address? Or is there an alternative equivalent implementation in C++?




Aucun commentaire:

Enregistrer un commentaire