Pardon me if this has been discussed already. I've got a template function which uses boost::uniform_int and boost::uniform_real depending on the template argument and should return the same type:
template <typename N> N getRandom(int min, int max)
{
timeval t;
gettimeofday(&t,NULL);
boost::mt19937 seed((int)t.tv_sec);
boost::uniform_int<> dist(min, max);
boost::variate_generator<boost::mt19937&, boost::uniform_int<> > random(seed, dist);
return random();
}
//! partial specialization for real numbers
template <typename N> N getRandom(N min, N max)
{
timeval t;
gettimeofday(&t,NULL);
boost::mt19937 seed( (int)t.tv_sec );
boost::uniform_real<> dist(min,max);
boost::variate_generator<boost::mt19937&, boost::uniform_real<> > random(seed,dist);
return random();
}
Now I've tested the function with int, float and doubles. It works fine with int, it works fine with double, but it does not work with floats. It's as if it either translates a float as an int, or there is some casting problem. Reason I'm saying this is because when i do:
float y = getRandom<float>(0.0,5.0);
I always get an int back. However, like I said, it works with doubles. Is there something I'm doing wrong or missing ? Thank you !
The arguments 0.0,5.0
are doubles, not floats. Make them floats:
float y = getRandom<float>(0.0f,5.0f);