题目:
产生N个服从高斯分布的随机数,计算这些随机数的均值和方差,并与高斯分布的均值和方差比较,N=100,1000,10000,100000
import matplotlib.pyplot as plt
import scipy.stats as sta
import numpy as npmu_True = 5 #设置高斯分布的均值mu
sigma_True = 2 #设置高斯分布的标准差sigma
pillar = 50 #图像里面画条形图的个数
NumList = [100, 1000, 10000, 100000] #随机数个数的设置plt.figure(figsize=(15, 15))
index = 221
for iNum in NumList:normal = sta.norm.rvs(mu_True, sigma_True, iNum) #产生服从高斯分布的随机数mu_Prec = np.mean(normal) #计算随机数的均值musigma_Prec = np.std(normal) #计算随机数的标准差sigmaloss_mu = np.abs(mu_Prec - mu_True)/mu_True #将随机数的均值与真实的均值相比较loss_sigma = np.abs(sigma_Prec - sigma_True)/sigma_True #将随机数的标准差与真实的sigma相比较print("When the random numbers are %d, the loss of mu: %f" % (iNum, loss_mu))print("When the random numbers are %d, the loss os sigma: %f" % (iNum, loss_sigma))#画图plt.subplot(index)plt.title('Num = %d' % iNum)n, bins, patches = plt.hist(normal, pillar, density=1, facecolor="green", alpha=0.5) #画随机数y_True = sta.norm.pdf(bins, mu_True, sigma_True) y_Prec = sta.norm.pdf(bins, mu_Prec, sigma_Prec) plt.plot(bins, y_True, color='r', label='True') #画实际的分布曲线plt.plot(bins, y_Prec, color='b', label='Predicted') #画预测的分布曲线plt.legend() #显示标注index += 1
plt.show()
结果:
When the random numbers are 100, the loss of mu: 0.014612
When the random numbers are 100, the loss os sigma: 0.009874
When the random numbers are 1000, the loss of mu: 0.023765
When the random numbers are 1000, the loss os sigma: 0.033875
When the random numbers are 10000, the loss of mu: 0.001330
When the random numbers are 10000, the loss os sigma: 0.006001
When the random numbers are 100000, the loss of mu: 0.001013
When the random numbers are 100000, the loss os sigma: 0.001101