生成具有给定(数字)分布的随机数 [英] Generate random numbers with a given (numerical) distribution

查看:118
本文介绍了生成具有给定(数字)分布的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,对于不同的值,例如:

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

我想使用此分布生成随机数.是否存在处理此问题的现有模块?自己编写代码是很简单的(构建累积密度函数,生成随机值[0,1]并选择相应的值),但似乎这应该是一个常见问题,可能有人为它创建了一个函数/模块它.

I would like to generate random numbers using this distribution. Does an existing module that handles this exist? It's fairly simple to code on your own (build the cumulative density function, generate a random value [0,1] and pick the corresponding value) but it seems like this should be a common problem and probably someone has created a function/module for it.

我需要这个,因为我想生成一个生日列表(不遵循标准random模块中的任何分布).

I need this because I want to generate a list of birthdays (which do not follow any distribution in the standard random module).

推荐答案

scipy.stats.rv_discrete 可能就是您想要的.您可以通过values参数提供概率.然后,您可以使用分发对象的rvs()方法生成随机数.

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.

正如Eugene Pakhomov在评论中指出的那样,您还可以将p关键字参数传递给

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])

如果您使用的是Python 3.6或更高版本,则可以使用标准库中的random.choices() –请参阅Mark Dickinson的答案.

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

这篇关于生成具有给定(数字)分布的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆