generate random numbers within a range with different probabilities

前端 未结 6 1069
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-06 07:05

How can i generate a random number between A = 1 and B = 10 where each number has a different probability?

Example: number / probability

1 - 20%

2 -

6条回答
  •  -上瘾入骨i
    2020-12-06 07:39

    Inverse Transform

    In probability speak, a cumulative distribution function F(x) returns the probability that any randomly drawn value, call it X, is <= some given value x. For instance, if I did F(4) in this case, I would get .6. because the running sum of probabilities in your example is {.2, .4, .5, .55, .6, .65, ....}. I.e. the probability of randomly getting a value less than or equal to 4 is .6. However, what I actually want to know is the inverse of the cumulative probability function, call it F_inv. I want to know what is the x value given the cumulative probability. I want to pass in F_inv(.6) and get back 4. That is why this is called the inverse transform method.

    So, in the inverse transform method, we are basically trying to find the interval in the cumulative distribution in which a random Uniform (0,1) number falls. This works out to the algorithm that perreal and icepack posted. Here is another way to state it in terms of the cumulative distribution function

    Generate a random number U
    for x in A .. B
       if U <= F(x) then return x 

    Note that it might be more efficient to have the loop go from B to A and check if U >= F(x) if the smaller probabilities come at the beginning of the distribution

提交回复
热议问题