Generate random numbers with a given (numerical) distribution

前端 未结 13 2215
我寻月下人不归
我寻月下人不归 2020-11-22 11:18

I have a file with some probabilities for different values e.g.:

1 0.1
2 0.05
3 0.05
4 0.2
5 0.4
6 0.2

I would like to generate random numb

13条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 11:41

    (OK, I know you are asking for shrink-wrap, but maybe those home-grown solutions just weren't succinct enough for your liking. :-)

    pdf = [(1, 0.1), (2, 0.05), (3, 0.05), (4, 0.2), (5, 0.4), (6, 0.2)]
    cdf = [(i, sum(p for j,p in pdf if j < i)) for i,_ in pdf]
    R = max(i for r in [random.random()] for i,c in cdf if c <= r)
    

    I pseudo-confirmed that this works by eyeballing the output of this expression:

    sorted(max(i for r in [random.random()] for i,c in cdf if c <= r)
           for _ in range(1000))
    

提交回复
热议问题