Random number with Probabilities

前端 未结 12 2197
醉梦人生
醉梦人生 2020-11-27 02:56

I am wondering what would be the best way (e.g. in Java) to generate random numbers within a particular range where each number has a certain probability to occur or not?

12条回答
  •  抹茶落季
    2020-11-27 03:08

    Your approach is fine for the specific numbers you picked, although you could reduce storage by using an array of 10 instead of an array of 100. However, this approach doesn't generalize well to large numbers of outcomes or outcomes with probabilities such as 1/e or 1/PI.

    A potentially better solution is to use an alias table. The alias method takes O(n) work to set up the table for n outcomes, but then is constant time to generate regardless of how many outcomes there are.

提交回复
热议问题