Distributed probability random number generator

前端 未结 7 1065
挽巷
挽巷 2020-12-05 10:47

I want to generate a number based on a distributed probability. For example, just say there are the following occurences of each numbers:

Number| Count               


        
7条回答
  •  被撕碎了的回忆
    2020-12-05 11:00

    Do this only once:

    • Write a function that calculates a cdf array given a pdf array. In your example pdf array is [150,40,15,3], cdf array will be [150,190,205,208].

    Do this every time:

    • Get a random number in [0,1) , multiply with 208, truncate up (or down: I leave it to you to think about the corner cases) You'll have an integer in 1..208. Name it r.
    • Perform a binary search on cdf array for r. Return the index of the cell that contains r.

    The running time will be proportional to log of the size of the given pdf array. Which is good. However, if your array size will always be so small (4 in your example) then performing a linear search is easier and also will perform better.

提交回复
热议问题