找到两个直方图的卷积

时间:2011-06-29 19:09:17

标签: statistics numpy probability histogram convolution

两个随机变量x和y之和的概率分布由各个分布的卷积给出。我在数字上做这个有点麻烦。在以下示例中,x和y均匀分布,其各自的分布近似为直方图。我的理由是直方图应该进行卷积,得到x + y的分布。

from numpy.random import uniform
from numpy import ceil,convolve,histogram,sqrt
from pylab import hist,plot,show

n = 10**2

x,y = uniform(-0.5,0.5,n),uniform(-0.5,0.5,n)

bins = ceil(sqrt(n))

pdf_x = histogram(x,bins=bins,normed=True)
pdf_y = histogram(y,bins=bins,normed=True)

s = convolve(pdf_x[0],pdf_y[0])

plot(s)
show()

给出以下内容,

enter image description here

换句话说,正如预期的那样是三角形分布。但是,我不知道如何找到x值。如果有人能在这里纠正我,我将不胜感激。

1 个答案:

答案 0 :(得分:5)

为了继续前进(朝着更加模糊的细节),我进一步调整了你的代码:

from numpy.random import uniform
from numpy import convolve, cumsum, histogram, linspace

s, e, n= -0.5, 0.5, 1e3
x, y, bins= uniform(s, e, n), uniform(s, e, n), linspace(s, e, n** .75)
pdf_x= histogram(x, normed= True, bins= bins)[0]
pdf_y= histogram(y, normed= True, bins= bins)[0]
c= convolve(pdf_x, pdf_y); c= c/ c.sum()
bins= linspace(2* s, 2* e, len(c))
# a simulation
xpy= uniform(s, e, 10* n)+ uniform(s, e, 10* n)
c2= histogram(xpy, normed= True, bins= bins)[0]; c2= c2/ c2.sum()

from pylab import grid, plot, show, subplot
subplot(211), plot(bins, c)
plot(linspace(xpy.min(), xpy.max(), len(c2)), c2, 'r'), grid(True)
subplot(212), plot(bins, cumsum(c)), grid(True), show()

因此,给出这样的情节: enter image description here 其中上部代表PDF(蓝线),其实际上看起来非常三角形,而模拟(红点)则反映了三角形的形状。下半部分代表CDF,它也可以很好地跟随预期的S - 曲线。