Python:如何得到两个连续分布的卷积? [英] Python: How to get the convolution of two continuous distributions?

查看:66
本文介绍了Python:如何得到两个连续分布的卷积?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设 X, Y 为 2 个随机变量,概率密度函数为 pdf1 和 pdf2.

Let X, Y be 2 random variables, with probability density functions pdf1 and pdf2.

Z = X + Y

那么Z的概率密度函数由pdf1和pdf2的卷积给出.由于我们无法处理连续分布,我们描述了连续分布并处理它们.

Then the probability density function of Z is given by the convolution of pdf1 and pdf2. Since we can't deal with continuous distributions, we descritize the continuous distributions and deal with them.

为了找到均匀分布和正态分布的卷积,我想出了以下代码.

To find the convolution of uniform distribution and normal distribution, I came up with following code.

import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
from scipy import signal


uniform_dist = stats.uniform(loc=2, scale=3)
std = 0.25
normal_dist = stats.norm(loc=0, scale=std)

delta = 1e-4
big_grid = np.arange(-10,10,delta)

pdf1 = uniform_dist.pdf(big_grid)
print("Integral over uniform pdf: "+str(np.trapz(pdf1, big_grid)))

pdf2 = normal_dist.pdf(big_grid)
print("Integral over normal pdf: "+str(np.trapz(pdf2, big_grid)))


conv_pdf = signal.fftconvolve(pdf1,pdf2,'same')
print("Integral over convoluted pdf: "+str(np.trapz(conv_pdf, big_grid)))

plt.plot(big_grid,pdf1, label='Tophat')
plt.plot(big_grid,pdf2, label='Gaussian error')
plt.plot(big_grid,conv_pdf, label='Sum')
plt.legend(loc='best'), plt.suptitle('PDFs')
plt.show() 

这是我得到的输出.

均匀上的积分pdf:0.9999999999976696

Integral over uniform pdf: 0.9999999999976696

对普通 pdf 的积分:1.0

Integral over normal pdf: 1.0

积分过卷积 pdf: 10000.0

Integral over convoluted pdf: 10000.0

如果卷积是正确的,我应该得到一个接近于 1 的积分超过卷积 pdf"的值.那么这里出了什么问题呢?有没有更好的方法来解决这个问题?

If the convolution was correct, I should get a value close to 1 for "Integral over convoluted pdf". So what is going wrong here? Is there a better approach to solve this problem?

谢谢

推荐答案

你应该在卷积之前将你的 pdf 描述为概率质量函数.

You should descritize your pdf into probability mass function before the convolution.

import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
from scipy import signal


uniform_dist = stats.uniform(loc=2, scale=3)
std = 0.25
normal_dist = stats.norm(loc=0, scale=std)

delta = 1e-4
big_grid = np.arange(-10,10,delta)

pmf1 = uniform_dist.pdf(big_grid)*delta
print("Sum of uniform pmf: "+str(sum(pmf1)))

pmf2 = normal_dist.pdf(big_grid)*delta
print("Sum of normal pmf: "+str(sum(pmf2)))


conv_pmf = signal.fftconvolve(pmf1,pmf2,'same')
print("Sum of convoluted pmf: "+str(sum(conv_pmf)))

pdf1 = pmf1/delta
pdf2 = pmf2/delta
conv_pdf = conv_pmf/delta
print("Integration of convoluted pdf: " + str(np.trapz(conv_pdf, big_grid)))


plt.plot(big_grid,pdf1, label='Uniform')
plt.plot(big_grid,pdf2, label='Gaussian')
plt.plot(big_grid,conv_pdf, label='Sum')
plt.legend(loc='best'), plt.suptitle('PDFs')
plt.show()

这篇关于Python:如何得到两个连续分布的卷积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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