Generate A Weighted Random Number

前端 未结 11 2308
予麋鹿
予麋鹿 2020-11-22 12:40

I\'m trying to devise a (good) way to choose a random number from a range of possible numbers where each number in the range is given a weight. To put it simply: given the

11条回答
  •  孤城傲影
    2020-11-22 12:55

    Generate a random number R between 0 and 1.

    If R in [0, 0.1) -> 1

    If R in [0.1, 0.2) -> 2

    If R in [0.2, 1] -> 3

    If you can't directly get a number between 0 and 1, generate a number in a range that will produce as much precision as you want. For example, if you have the weights for

    (1, 83.7%) and (2, 16.3%), roll a number from 1 to 1000. 1-837 is a 1. 838-1000 is 2.

提交回复
热议问题