generate random numbers within a range with different probabilities

前端 未结 6 1073
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  爱一瞬间的悲伤
    2020-12-06 07:29

    Assuming that you have a function p(n) that gives you the desired probability for a random number:

    r = rand()  // a random number between 0 and 1
    for i in A to B do
        if r < p(i) 
          return i
        r = r - p(i)    
    done
    

    A faster way is to create an array of (B - A) * 100 elements and populate it with numbers from A to B such that the ratio of the number of each item occurs in the array to the size of the array is its probability. You can then generate a uniform random number to get an index to the array and directly access the array to get your random number.

提交回复
热议问题