This question already has answers here:

python scipy.stats.powerlaw negative exponent
(4个答案)
我想从负指数的幂律分布(a=-2)中画出一个介于2到15之间的随机变量。我发现了以下情况:
r = scipy.stats.powerlaw.rvs(a, loc = 2, scale = 13, size = 1000)

但A不带负数。
有人知道出路吗?

最佳答案

numpy.randomscipy.stats中定义的幂律分布在数学意义上没有定义为负的a,正如this question的答案中所解释的那样:它们不可规范化,因为在零处存在奇点。所以,不幸的是,数学上说“不”。
您可以定义一个pdf与x^{g-1}g < 0成比例的分布,间隔不包含零,如果这是您所追求的。
对于pdf(x) = const * x**(g-1)对于a <= x <= b,从均匀变量(np.random.random)的转换是:

In [3]: def rndm(a, b, g, size=1):
    """Power-law gen for pdf(x)\propto x^{g-1} for a<=x<=b"""
   ...:     r = np.random.random(size=size)
   ...:     ag, bg = a**g, b**g
   ...:     return (ag + (bg - ag)*r)**(1./g)

然后你可以做,例如,
In [4]: xx = rndm(1, 2, g=-2, size=10000)

等等。
为了完整起见,以下是pdf:
In [5]: def pdf(x, a, b, g):
    ag, bg = a**g, b**g
   ....:     return g * x**(g-1) / (bg - ag)

这都假设a < bg != 0。对于numpy.powerscipy.stats.powerlawa=0,这些公式应与b=1g > 0一致。

关于python - Python:从幂律分布中生成随机数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31114330/

10-12 21:33
查看更多