この記事を書いている時に、分布のグラフを描く必要がありました。そのため、pythonを用いて確率密度関数から任意の分布を描くコードを書いてみました。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import matplotlib.pyplot as plt | |
def exp_dist(lamda, x): | |
return lamda * np.exp(- lamda * x) | |
def exp_dist_d(lamda, x,delta): | |
return 1 / lamda * np.exp(-1*(x - delta) / lamda) | |
x = np.arange(0, 1, 0.01) | |
y1 = [exp_dist(1, i) for i in x] | |
y2 = [exp_dist(5, i) for i in x] | |
y3 = [exp_dist_d(1, i, 0) for i in x] | |
y4 = [exp_dist_d(1, i, 1) for i in x] | |
y5 = [exp_dist_d(1, i, 2) for i in x] | |
y6 = [exp_dist_d(5, i, 0) for i in x] | |
y7 = [exp_dist_d(5, i, 1) for i in x] | |
y8 = [exp_dist_d(5, i, 2) for i in x] | |
# y9 = [exp_dist(10,i) for i in x] | |
plt.plot(x, y1, color="red", alpha=0.5, label="exp_dist λ=1") | |
# plt.plot(x, y2, color="blue", alpha=0.5, label="exp_dist λ=5") | |
plt.plot(x, y3, color="blue", alpha=0.5, label="exp_dist_d λ=1 δ=0") | |
plt.plot(x, y4, color="green", alpha=0.5, label="exp_dist_d λ=1 δ=1") | |
plt.plot(x, y5, color="pink", alpha=0.5, label="exp_dist_d λ=1 δ=2" ) | |
# plt.plot(x, y6, color="green", alpha=0.5, label="exp_dist_d λ=5 δ=0 " ) | |
# plt.plot(x, y7, color="pink", alpha=0.5, label="exp_dist_d λ=5 δ=1 " ) | |
# plt.plot(x, y8, color="red", alpha=0.5, label="exp_dist_d λ=5 δ=2") | |
plt.legend() | |
plt.show() |
コードは殆ど指数分布を丁寧に理解してPythonで描画するのパクリです。
まず、python環境にnumpyとmatplotlibを入れていない場合はpipを使って入れます。
準備が整ったら
- 自作関数内に確率密度関数を書く
- 任意の間隔で任意の幅を持つリストを作る(xのこと)
- xリスト内の各値に対応するyの値をリストに入れる
- 2と3で作ったリストをplotさせる
これで終わりです。
殆どコピペで済むので、やることは自作関数内に確率密度関数を書くことがメインです。
これでプロットさせて、やっぱりpythonは便利だなあと思いました。