0

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?

12
  • plus1 to counter the anonymous neg1 Commented Jun 27, 2017 at 19:01
  • 1
    Can you give us a minimal reproducible example? Right from the start I see your not seeding the PRNG so you will always get the same sequence. Commented Jun 27, 2017 at 19:03
  • @NathanOliver I am actually, it's just not shown here. I seed it with gettimeofday's tv_sec Commented Jun 27, 2017 at 19:04
  • 1
    note that there's no need to use boost here, C++ bascially has exactly the same random functions Commented Jun 27, 2017 at 19:04
  • 1
    @Riptyde4 Still waiting for you to fix the missing parameter type and missing : in boost:mt19937. Why are you doing this? Commented Jun 27, 2017 at 19:27

1 Answer 1

4

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().

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.