2

We can use std::uniform_int_distribution to generate random numbers in a specific interval. However, for my simulation I need a uniformly distributed random integer at each iteration, and the interval is dependent on the outcome of the previous iteration. I'm already aware of some of the tricks (like these) that can be used to produce a uniform / near-uniform distribution of integers from a larger interval, but is there a standard or recommended "post-c++11ish" way to do this?

I know it's possible to just create a new uniform_int_distribution object at each iteration. Are there any hidden caveats or gotchas to this approach? It seems that distribution objects do hold some internal state, so I'm slightly concerned that using a fresh distribution object to generate a single random number might have some drawbacks or undesirable characteristics that are not obvious to me.

  • 2
    I don't know if there is any overhead for creating a new distribution. You can change bounds of existing distribution though, see this answer: https://stackoverflow.com/a/28328983/12463032 –  Jul 11 '20 at 10:07
  • @TedLyngmo - your comment would work as an answer if you want to do that - I'd completely missed the overload – jaymmer - Reinstate Monica Jul 11 '20 at 11:45

1 Answers1

4

A uniform_int_distribution is supposed to be cheap to create but if you are concerned you can supply temporary distribution parameters when calling it using the overload:

result_type operator()( Generator& g, const param_type& params );

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108