Reputation: 5460
WITHOUT USING C++ 11 RANDOM
Looking for a boost random expert... I need to generate random numbers in between many, many different ranges. I've written the below functions:
#include <iostream>
#include <boost/random.hpp>
#include <boost/generator_iterator.hpp>
boost::mt19937 g_oRng;
int generateIntVariate(int p_iMin, int p_iMax){
boost::uniform_int<> min_to_max(p_iMin, p_iMax);
boost::variate_generator< boost::mt19937, boost::uniform_int<> > oGen(g_oRng, min_to_max);
return oGen();
}
float generateFloatVariate(int p_fMin, p_fMax){
boost::uniform_real<> min_to_max(p_fMin, p_fMax);
boost::variate_generator< boost::mt19937, boost::uniform_real<> > oGen(m_oRng, min_to_max);
return oGen();
}
int main(){
struct timeval tp;
gettimeofday(&tp, NULL);
g_oRng = boost::mt19937((int)tp.tv_sec);
for(int i = 0 ; i < 10 ; ++i){
std::cout << generateIntVariate(0, 10) << ", " << generateFloatVariate(0.0f, 10.0f) << std::endl;
}
}
The problem is that both functions return the same exact number for a given range, every time it's executed.
(gdb) p generateIntVariate(0, 10)
$40 = 8
(gdb) p generateIntVariate(0, 10)
$41 = 8
(gdb) p generateIntVariate(0, 10)
$42 = 8
(gdb) p generateIntVariate(0, 10)
$43 = 8
The same thing as above happens with the float function. Is there any way I can accomplish what I'm trying to do using the boost random distros?
Upvotes: 0
Views: 109
Reputation: 19607
boost::variate_generator
's constructor looks like this:
variate_generator(Engine e, Distribution d);
- meaning it won't change the state of passed-in m_oRng
and makes a copy of it instead.
I suggest omitting variate_generator
and just using boost::uniform_int<>::operator()
.
Upvotes: 4