Ccmmutty logo
Commutty IT
5 min read

【Pythonで図解】大数の法則と中心極限定理の実装

https://cdn.magicode.io/media/notebox/badea538-e3d3-4da1-ab8c-225aa2141a62.jpeg

目次

  • はじめに
  • 大数の法則の実装
  • 中心極限定理の実装
  • おわりに
  • 参考文献・サイト

はじめに

以前投稿させていただきました、
「【Rで図解】大数の法則と中心極限定理の理解が曖昧になりやすいのはなぜか」
では、大数の法則と中心極限定理についてRでの実装と解説を記載させていただきました。
同様にPythonでも実装してみます。
実行環境については、Google Colaboratory上で実装と実行を行いました。

大数の法則の実装

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random

#試行回数を引数に取る関数を定義
def loln (num1):
  #num1回数分、1~6の整数値をランダムで生成
  dice = [random.randint(1, 6) for p in range(0, num1)]
  #結果格納用のリストを用意
  result = []
  for i in range(1, 7):
    #1~6の出た回数をカウントして、リストの末尾に追加していく
    result.append(dice.count(i))
  return result

#figure()でグラフを表示する領域をつくり,figというオブジェクトにする.
fig = plt.figure(figsize=[10,7])

#add_subplot()でグラフを描画する領域を追加する.引数は行,列,場所
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
ax4 = fig.add_subplot(2, 2, 4)

#ラベルの設定
l1, l2, l3, l4 = 'n=10', 'n=100', '1000', 'n=10000'
labels = ['1', '2', '3', '4', '5', '6']
left = [1, 2, 3, 4, 5, 6]

#描画
ax1.bar(left, height = loln(10),  width=0.5, label=l1, alpha=0.5, ec='black')
ax2.bar(left, height = loln(100),  width=0.5, label=l2, alpha=0.5,  ec='black')
ax3.bar(left, height = loln(1000),  width=0.5, label=l3, alpha=0.5, ec='black')
ax4.bar(left, height = loln(10000),  width=0.5, label=l4, alpha=0.5,  ec='black')

#レイアウトの設定
ax1.legend(loc = 'upper right')
ax2.legend(loc = 'upper right')
ax3.legend(loc = 'upper right')
ax4.legend(loc = 'upper right')
fig.tight_layout
plt.show()
実行結果は、以下のようになりました。
以下のコードで実行してみて下さい
python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random

def loln (num1):
  dice = [random.randint(1, 6) for p in range(0, num1)]
  result = []
  for i in range(1, 7):
    result.append(dice.count(i))
  return result

中心極限定理の実装

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random

#num1は試行回数、num2は変数の数
def clt (num1, num2):
  result = []
  for i in range(0, num1):
    dice = [random.randint(1, 6) for p in range(0, num2)]
    total = sum(dice)
    result.append(total)
  return result

#figure()でグラフを表示する領域をつくり,figというオブジェクトにする.
fig = plt.figure(figsize=[10,7])

#add_subplot()でグラフを描画する領域を追加する.引数は行,列,場所
ax1 = fig.add_subplot(3, 1, 1)
ax2 = fig.add_subplot(3, 1, 2)
ax3 = fig.add_subplot(3, 1, 3)
#ax4 = fig.add_subplot(2, 2, 4)

#ラベルの設定
l1, l2, l3, l4 = 'n=2', 'n=5', 'n=10'

#ヒストグラムの描画
ax1.hist(clt(100000, 2), bins='auto', density=True, histtype='barstacked', ec='black', label=l1)
ax2.hist(clt(100000, 5), bins='auto', density=True, histtype='barstacked', ec='black', label=l2)
ax3.hist(clt(100000, 10), bins='auto', density=True, histtype='barstacked', ec='black', label=l3)

#レイアウトの設定
ax1.legend(loc = 'upper right')
ax2.legend(loc = 'upper right')
ax3.legend(loc = 'upper right')
fig.tight_layout
plt.show()
実行結果は以下のようになりました
(本当は棒グラフで描画したかったのですが、縦軸の値の合計が1になるように設定(density = Trueで指定)して、ヒストグラムとして描画しています)
以下のコードで実行してみて下さい。
python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random

def clt (num1, num2):
  result = []
  for i in range(0, num1):
    dice = [random.randint(1, 6) for p in range(0, num2)]
    total = sum(dice)
    result.append(total)
  return result

おわりに

大数の法則、中心極限定理についてPythonで実装してみました。
個人的には、RとPythonの実装手法が異なる点もあり、良い経験になったと思います。
本記事が皆様の理解の一助になれば幸いです。

参考文献・リスト

[1]「Pythonでリスト(配列)に要素を追加するappend, extend, insert」https://note.nkmk.me/python-list-append-extend-insert/
[2]「【matplotlib基礎】複数のグラフを並べて表示する」https://qiita.com/trami/items/bd54f22ee4449421f2bc

Discussion

コメントにはログインが必要です。