随机生成两个正态分布之和并拟合

题目

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()

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值