1

I have a function that should simulate a new random exponential variable every time it is called:

 #include <boost/random.hpp> //Simulates a single exponential random variable double generateExponential(double lambda) { boost::mt19937 rng; //Mersenne Twister Generator rng.seed(time(0)); boost::variate_generator< boost::mt19937&, boost::exponential_distribution<> > rndm(rng, boost::exponenti\ al_distribution<>(lambda)); return rndm(); } 

for example,

double newExp = generateExponential(10); 

However, each time I call the function, it generates the same random number. I want it to generate a different random number each time the function is called. I thought "rng.seed(time(0))" might fix it but it hasn't. How could I get it to do this?

2
  • You keep feeding it the seed, every time you call it. So it generates the same value, every time you call it. time(0) doesn't change often between clock cycles. Commented Mar 9, 2015 at 5:32
  • note that mt19937 was added to C++11; if you have C++11 available then you can improve on this function Commented Mar 9, 2015 at 6:06

2 Answers 2

2

If you can't change the signature of your function, then you could use a static instance of your generator. No need to re-seed.

#include <boost/random.hpp> typedef boost::mt19937 G; typedef boost::exponential_distribution D; double generateExponential(double lambda) { static G rng(std::time(0)); // initialized and seeded once boost::variate_generator<G &, D<> > rndm(rng, D<>(lambda)); return rndm(); } 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! This works. Just wondering, since we're making rng a static, would it work the same to just define it outside the function?
Yes, then it would be a global. As others have mentioned, you can also pass an instance of the generator as an argument to the function.
I'd be rather suspicious of this approach if you used random number generators elsewhere in your program too.
1

Generally speaking, a source of random numbers should be a resource whose lifespan is that of your entire program, not that of an individual function call.

Consequently, you need the object representing said source of random numbers to have an appropriate lifespan. Making it a variable local to your function is a Bad Idea. It should be an object passed into your function, or maybe a global object.

(also, frequently reseeding a random number generator is another well known Bad Idea)

1 Comment

Thanks! So do you think I should do "boost::mt1937 rng;" in the main() function, specify rng.seed(time(0)) in the main function, and just leave the remaining lines for the generateExponential function?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.