1

I am trying to write a function that takes in a min and a max and returns a random double between them. I was trying to use Boost::variate_generator to get a random number between two doubles, but the issue is that I can't change the distribution on it, so I would have to make a new seed each call. It defeats the purpose of a Pseudo Random Number Generator if I make a new seed every time I call it.

Is there a way to get something like this below, Boost isn't necessary, it just seems to give good results.

double getRandom(double min, double max);
{
    return randomNumberBetweenMinAndMax;
}
user947871
  • 339
  • 6
  • 17

1 Answers1

0

There are a lot of ways to do it. You could have an argument with a default parameter that defaults to some globally available object. You could have a locally scoped static variable that stores the generator. You could have a file scope static variable (similar to a class static if this were in a class) that stores the generator. You could have a singleton generator that the function acquires.

I am partial to default parameters with a globally available object as the default. Its generally thread-safe as long the generator is thread safe and you initialize is before any threads are created.

frankc
  • 11,290
  • 4
  • 32
  • 49
  • How does this solve the issue of needing to change the min and max of the generator? – user947871 May 16 '13 at 19:30
  • I'm not that familiar with the boost generators specifically, but if you have the generator generate a [0,1] uniform, you can scale that into whatever range you want. – frankc May 22 '13 at 13:33