Python中给定PDF的随机数 [英] Random number with given PDF in Python
问题描述
我想生成一个整数随机数,其概率分布函数以列表形式给出.例如,如果 pdf=[3,2,1] 那么我喜欢rndWDist(pdf)返回 0,1 和 2,概率为 3/6、2/6 和 1/6.我为此编写了自己的函数,因为我在 random 模块中找不到它.
I want to generate an integer random number with a probability distribution function given as a list. For example if pdf=[3,2,1] then I like rndWDist(pdf) to return 0,1, and 2, with probabilities of 3/6, 2/6, and 1/6. I wrote my own function for that since I couldn't find it in the random module.
def randintWDist(pdf):
cdf=[]
for x in pdf:
if cdf:
cdf.append(cdf[-1]+x)
else:
cdf.append(x)
a=random.randint(1,cdf[-1])
i=0
while cdf[i]<a:
i=i+1
return i
有没有更短的方法来达到同样的结果?
Is there any shorter method to achieve the same result?
推荐答案
这是一个重复的问题:Generate random numbers with a given (数值)分布
正如第一个答案所建议的那样,您可能想要使用 scipy.stats.rv_discrete
.
As the first answer there suggest, you might want to use scipy.stats.rv_discrete
.
你可以这样使用它:
from scipy.stats import rv_discrete
numbers = (1,2,3)
distribution = (1./6, 2./6, 3./6)
random_variable = rv_discrete(values=(numbers,distribution))
random_variable.rvs(size=10)
这将返回一个包含 10 个随机值的 numpy 数组.
This returns a numpy array with 10 random values.
这篇关于Python中给定PDF的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!