Non-Uniform Random Number Generator Implementation?

前端 未结 8 2056
北恋
北恋 2021-01-05 19:03

I need a random number generator that picks numbers over a specified range with a programmable mean.

For example, I need to pick numbers between 2 and 14 and I need

相关标签:
8条回答
  • 2021-01-05 19:55

    You need a distributed / weighted random number generator. Here's a reference to get you started.

    0 讨论(0)
  • 2021-01-05 20:03

    You might be able to use a binomial distribution, if you're happy with the shape of that distribution. Set n=12 and p=0.25. This will give you a value between 0 and 12 with a mean of 3. Just add 2 to each result to get the range and mean you are looking for.

    Edit: As for implementation, you can probably find a library for your chosen language that supports non-uniform distributions (I've written one myself for Java).

    A binomial distribution can be approximated fairly easily using a uniform RNG. Simply perform n trials and record the number of successes. So if you have n=10 and p=0.5, it's just like flipping a coin 10 times in a row and counting the number of heads. For p=0.25 just generate uniformly-distributed values between 0 and 3 and only count zeros as successes.

    If you want a more efficient implementation, there is a clever algorithm hidden away in the exercises of volume 2 of Knuth's The Art of Computer Programming.

    0 讨论(0)
提交回复
热议问题