题目
Consider three random variables X , Y , and Z=X+Y , with X and Y being independent of each other.
(a) GivenX~N (0,1) and Y~N(1,2) , show Z~N (1,3).
(b) Write a short program to generate a sequence for the random number Z according to the given PDFs of X and Y. Then fit this sequence by using the normal distribution.
Note:
PDF:Partial Distribution Function
CDF: Cumulative Distribution Function
代码
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
np.random.seed(5)
x = np.random.normal(0, 1, 100000)
y = np.random.normal(1, np.sqrt(2), 100000)
z = x+y
# the histogram of the data
plt.subplot(311)
n, bins, patches = plt.hist(x, 100,density=True, facecolor='g', alpha=0.75)
plt.xlabel('X')
plt.ylabel('Probability')
plt.title('PDF of X $\mu=0, \sigma=1$')
plt.xticks(np.arange(-15,15,2))
plt.subplot(312)
n, bins, patches = plt.hist(y, 100,density=True, facecolor='y', alpha=0.75)
plt.xlabel('Y')
plt.ylabel('Probability')
plt.title('Histogram of Y $\mu=1, \sigma=\sqrt{2}$')
plt.xticks(np.arange(-15,15,2))
plt.subplot(313)
mu, sigma = stats.norm.fit(z)
print(mu,sigma)
lnspc = np.arange(-15, 15, 0.005)
pdf_g = stats.norm.pdf(lnspc, mu, sigma)
plt.plot(lnspc,pdf_g,label="Norm",color='r')
n, bins, patches = plt.hist(z, 100,density=True, facecolor='b', alpha=0.75)
plt.xlabel('Z')
plt.ylabel('Probability')
plt.title('Histogram of Z $\mu=$'+str(np.round(mu,3))+' $\sigma=$'+str(np.round(sigma,3)))
plt.xticks(np.arange(-15,15,2))
plt.tight_layout()
plt.show()
plt.close()