Problems with C ++ 11 class mersenne_twister_engine

I am trying to use the C ++ 11 class mersenne_twister_engine ( http://www.cplusplus.com/reference/random/mersenne_twister_engine/ ) to generate numbers in the interval [0,1], however I constantly get 0 on every number.

Here is my code snippet

unsigned seed1 = std::chrono::system_clock::now().time_since_epoch().count(); std::mt19937 generator(seed1); for (int i=0; i < WIDTH * HEIGHT; i++) //GENERATES THE MATRIX OF CONNECTIVITY { double random = generator()/generator.max(); if ( random > VERT_CONNECTIVITY ) vert_con[i] = 0; else vert_con[i] = 1; } 

generator () and generator.max () seem to be working ... This is just random, which gives me 0!

Thanks!

+1
source share
4 answers

In C ++ / for integers, an integer is obtained. For example, 11/2 leads to 5, not 5.5. Similarly, a / b always zero if a < b .

Your problem is here:

 generator()/generator.max() 

generator() and generator.max() both return integers and, of course, generator.max() >= generator() , so the result is zero (if you are not very lucky to get the max number, in which case the result will be one) .

To fix this, you can simply do this:

 (double)generator()/generator.max() 
0
source

Using one of the distributions provided in a random header probably makes more sense. As Cubby points out, std :: bernoulli_distribution looks like it matches your problem. It will generate true or false according to the distribution parameter you pass in:

 #include <iostream> #include <random> #include <vector> #include <algorithm> const int WIDTH = 5 ; const int HEIGHT = 5 ; const double VERT_CONNECTIVITY = 0.25 ; int main() { std::random_device rd; std::mt19937 gen(rd()); // give "true" 1/4 of the time // give "false" 3/4 of the time std::bernoulli_distribution d(VERT_CONNECTIVITY); std::vector<int> vert_con( WIDTH * HEIGHT ) ; std::generate( std::begin(vert_con), std::end( vert_con ), [&] () { return d(gen) ; } ) ; for (int i=0; i < WIDTH * HEIGHT; i++) { std::cout << vert_con[i] << " " ; } std::cout << std::endl ; return 0 ; } 
+5
source

Perhaps you are looking for generate_canonical<double, bits>(gen) ? This will generate a decimal value evenly distributed in the interval [0,1) with bits bits of randomness (53 is the standard maximum available for a double).

+2
source

mersenne_twister_engine returns results of type UIntType . If you want the result to be double, you need to make it double.

double random = (double) generator () / generator.max ();

0
source

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


All Articles