Generating a number (0,1) using mersenne twister C ++

I am working on implementing R code in C ++, so it works faster, but I am having difficulty implementing mersenne twister. I only want to generate values ​​between (0,1). Here is what I have that relates to this issue.

#include <random>

std::mt19937 generator (123);

std::cout << "Random value: " << generator() << std:: endl;

I tried to divide by RAND_MAX, but this did not lead to the values ​​I was looking for.

Thanks in advance.

+4
source share
3 answers

In C ++ 11, the concepts of a (pseudo) random generator and a probability distribution are separated for valid reasons.

What you want can be achieved with the following lines:

  std::mt19937 generator (123);
  std::uniform_real_distribution<double> dis(0.0, 1.0);

  double randomRealBetweenZeroAndOne = dis(generator);

, , / , .

+9

, :

// For pseudo-random number generators and distributions
#include <random> 

...

// Use random_device to generate a seed for Mersenne twister engine.
std::random_device rd{};    

// Use Mersenne twister engine to generate pseudo-random numbers.
std::mt19937 engine{rd()};

// "Filter" MT engine output to generate pseudo-random double values,
// **uniformly distributed** on the closed interval [0, 1].
// (Note that the range is [inclusive, inclusive].)
std::uniform_real_distribution<double> dist{0.0, 1.0};

// Generate pseudo-random number.
double x = dist(engine);

++ ( , rand() ), . Stephan T. Lavavej ( Going Native 2013):

rand()

+4

std:: mt19937 0 RAND_MAX, rand(), 0 2 ^ 32-1

, , min() max()!

double, substract min() max() - min()

uint32_t val;
val << generator;
double doubleval = ((double)val - generator::min())/(generator::max()-generator::min());

( )

uint32_t val;
val << generator;
double doubleval = (double)val * (1.0 / std::numeric_limits<std::uint32_t>::max());
+1

Source: https://habr.com/ru/post/1535440/


All Articles