【发布时间】:2019-07-24 16:25:01
【问题描述】:
我正在尝试从平均值为 170 和 st.deviation 2 的正态总体中模拟样本平均值的抽样分布。根据数学,大小为 20 的样本将具有平均值为 170 和 st.deviation 的正态抽样平均值分布2/(20^0.5)。
我正在绘制 n=20 的经验抽样均值分布,进行了 50000 次实验。然后我使用a.hist(sample_means1, bins = 100),获取高度并将每个除以 50000 ,然后使用ax.plot 再次绘制以获得经验抽样均值分布。但结果似乎并不一致。代码如下:
import math
import statistics
import random
import matplotlib.pyplot as plt
def normal_pdf(m, s, x):
coeff = 1/(s*math.sqrt(2*math.pi))
expn = math.exp( -0.5*((x - m)/s)**2 );
return coeff*expn
n_exp = 50000
fig, ax = plt.subplots()
sample_means1 = []
for i in range(n_exp):
sample = [random.gauss(170, 2) for i in range(20)]
smean = statistics.mean(sample)
sample_means1.append(smean)
f,a = plt.subplots()
h = a.hist(sample_means1, bins = 100)
probs = [i/n_exp for i in h[0]]
xl = min(h[1])
xr = max(h[1])
x = [xl + (xr-xl)*i/1000 for i in range(1001)]
ax.plot(h[1][0: 100], probs, '-', color = "black")
ax.plot(x, [normal_pdf(170, 2/math.sqrt(20), i) for i in x], '-', color = "blue")
fig.savefig("tes.png")
绘制结果:
【问题讨论】:
标签: python matplotlib