Python中给定PDF的随机数 [英] Random number with given PDF in Python

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

问题描述

我想生成一个整数随机数,其概率分布函数以列表形式给出.例如,如果 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屋!

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