I have been trying to use the c++ 11 mersenne_twister_engine class( http://www.cplusplus.com/reference/random/mersenne_twister_engine/) to generate numbers in the interval [0,1] however I am continually getting 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... It is just random which gives me 0!
Thanks!
In C++,
/
on integer numbers results in an integer number. For example 11 / 2 results in 5, not 5.5. In the same waya / b
is always zero ifa < b
.Your problem is here:
generator()
andgenerator.max()
both return integers and of course,generator.max() >= generator()
, so the result is zero (unless you are very lucky to get themax
number in which case the result would be one).To fix this, you can simply cast it: