随机变量之和 - 根据数值计算/直方图检查您的派生分布

计算科学 Python 计算物理学
2021-12-10 14:51:57

考虑独立随机变量X0,X1,...每个均匀分布在支架上[0,1)

比方说Y=X0+X1, 在哪里X0X1是具有范围的独立均匀随机变量[0,1)

然后我导出了以下 PDF 来描述总和的分布Y=X0+X1使用卷积。

f(y)={yfor 0<y<12yfor 1y<20otherwise.

我想根据数值计算/直方图检查派生分布(在python中)

任何帮助表示赞赏

import numpy as np
import matplotlib.pyplot as plt

X_0 = np.random.uniform(0.0,1.0,1000)
X_1 = np.random.uniform(0.0,1.0,1000)

Y = X_0 + X_1

#Plot 3 normalised histograms
plt.hist(X_0,bins=100,density=True)
plt.hist(X_1,bins=100,density=True)
plt.hist(Y,bins=100,density=True)

#desired distribution
if 0<Y<1:
    F_Y = Y
if 1<=Y<2:
    F_Y = 2 - Y
if Y < 0:
    F_Y = 0
    
plt.plot(Y,F_Y)
plt.title('desired distibution')
plt.show()
1个回答

这是一个工作代码和下面显示的结果,只需分析它。注意概率密度函数p(x)归一化为统一,p(x)dx=1。

import numpy as np
import matplotlib.pyplot as plt

def show_histogram(vals):
    n, bins, patches = plt.hist(x=vals, bins='auto', density=True, color='#0504aa', alpha=0.7, rwidth=0.85)
    plt.grid(axis='y', alpha=0.75)
    plt.xlabel('Value')
    plt.ylabel('Frequency')
    plt.title('Distribution of calculated values')



X_0 = np.random.uniform(0.0,1.0,10000)
X_1 = np.random.uniform(0.0,1.0,10000)

Y = X_0 + X_1


#Plot normalised histograms
show_histogram(X_0+X_1)


#desired distribution
n=100
Y = 2*np.arange(n)/(n-1)
F_Y=1.0 - np.abs(Y-1)

    
plt.plot(Y,F_Y)
plt.title('desired distibution')
plt.show()

在此处输入图像描述