2020年5月24日日曜日

正規分布に従う独立な変数の和

講義で使える統計素材」シリーズ. 今回は,正規分布に従う独立な確率変数の和(和や差などの線形結合)は,やはり正規分布に従うということを確認するための図を作成しました.

In [1]:
import numpy as np
import matplotlib.pyplot as plt

標準正規分布に従う乱数を発生

In [2]:
n = 100000
x1 = np.random.normal(0, 1, n)
x2 = np.random.normal(1, 1, n)
y=np.arange(0, n, 1)
In [3]:
cmap = plt.get_cmap("tab10")

#透明チャネルを0.5に変更
c1 = (cmap(0)[0], cmap(0)[1], cmap(0)[2], 0.5)
c2 = (cmap(1)[0], cmap(1)[1], cmap(1)[2], 0.5)
c3 = (cmap(2)[0], cmap(2)[1], cmap(2)[2], 0.5)
In [4]:
plt.xlim(-5,5)
plt.plot(x1,y,',', color=c1)
plt.plot(x2,y,',', color=c2)

plt.savefig('plot_out.svg', transparent=True)

ヒストグラムで分布を確認

In [5]:
# ヒストグラムを出力
plt.xlim(-5,5)
n, bins, patch = plt.hist(x1, bins=100, density=True, color=c1)
plt.hist(x2, bins, density=True, color=c2)

plt.savefig('plot_out.svg', transparent=True)

正規分布に従う2変数の和の分布

In [6]:
dif = x1 + x2
hist_x1, bins_ = np.histogram(x1, bins, density=True)
hist_x2, bins_ = np.histogram(x2, bins, density=True)
hist_dif, bins_ = np.histogram(dif, bins, density=True)

plt.xlim(-5,5)
plt.plot(bins[:-1], hist_x1,color=cmap(0))
plt.plot(bins[:-1], hist_x2, color=cmap(1))
plt.plot(bins[:-1], hist_dif, color=cmap(2))
plt.fill_between(bins[:-1], hist_x1, color=c1)
plt.fill_between(bins[:-1], hist_x2, color=c2)
plt.fill_between(bins[:-1], hist_dif, color=c3)

plt.savefig('plot_out.svg', transparent=True)