Generate random numbers with a given (numerical) distribution

前端 未结 13 2289
我寻月下人不归
我寻月下人不归 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:46

    scipy.stats.rv_discrete might be what you want. You can supply your probabilities via the values parameter. You can then use the rvs() method of the distribution object to generate random numbers.

    As pointed out by Eugene Pakhomov in the comments, you can also pass a p keyword parameter to numpy.random.choice(), e.g.

    numpy.random.choice(numpy.arange(1, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2])
    

    If you are using Python 3.6 or above, you can use random.choices() from the standard library – see the answer by Mark Dickinson.

提交回复
热议问题