![](/img/trans.png)
[英]How to generate a single random number given a continuous PDF in Python?
[英]Random number with given PDF in Python
我想生成一個整數隨機數,其概率分布函數作為列表給出。 例如,如果pdf = [3,2,1],那么我喜歡rndWDist(pdf)返回0,1和2,概率為3 / 6,2 / 6和1/6。 我為自己編寫了自己的函數,因為我在隨機模塊中找不到它。
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
有沒有更短的方法來實現相同的結果?
這是一個重復的問題: 生成具有給定(數字)分布的隨機數
作為第一個答案,您可能希望使用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數組。
根據您的輸入格式,您可以:
def randint_with_dist(pdf):
choices = []
for index, value in enumerate(pdf):
choices.extend(index for _ in range(value))
return random.choice(choices)
由於每次傳遞相同的pdf
時都會使用相同的列表,因此您可以考慮緩存列表以提高效率(以空間為代價):
def randint_with_dist(pdf, choices={}):
pdf = tuple(pdf)
if pdf not in choices:
choices[pdf] = []
for index, value in enumerate(pdf):
choices[pdf].extend(index for _ in range(value))
return random.choice(choices[pdf])
使用numpy(1.7或更新版本),您還可以使用np.random.choice :
In [27]: import numpy as np
In [28]: distribution = (1./6, 2./6, 3./6)
In [29]: np.random.choice(np.arange(len(distribution)), p=distribution)
Out[29]: 0
In [30]: np.random.choice(np.arange(len(distribution)), p=distribution, size=10)
Out[30]: array([2, 1, 1, 2, 2, 0, 1, 0, 1, 0])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.