LoginSignup
0
0

More than 3 years have passed since last update.

サイコロ2個の場合の分散をpython3で解く

Last updated at Posted at 2019-09-04

実行環境

python3.4.3

分散とは

分布の広がりを表します。今回のサイコロ2つの例で言えば、2つのサイコロの目の合計2~12がどれくらいの確率で表れるのか、その分布広がり具合を示す指標です。

再現したい数式

V(X) = E(X^2) - E^2(X)

サイコロが2つなので確率変数は2~12まで、確率の幅は1/36~6/36までです。

コード例

#SXOEはSquared X of Expectation(Xの2乗の期待値の頭文字SXOEをとりました)
def sxoe():
  xi = [2**2,3**2,4**2,5**2,6**2,7**2,8**2,9**2,10**2,11**2,12**2]
  pi = [1/36,2/36,3/36,4/36,5/36,6/36,5/36,4/36,3/36,2/36,1/36]
  expectation = 0
  for x,p in zip(xi,pi):
    expectation += x*p
  return(expectation)

#SEはSquared E(Xの期待値の2乗の頭文字SEをとりました)
def se():
  xi = [2,3,4,5,6,7,8,9,10,11,12]
  pi = [1/36,2/36,3/36,4/36,5/36,6/36,5/36,4/36,3/36,2/36,1/36]
  expectation = 0
  for x,p in zip(xi,pi):
    expectation += (x*p)
  return(expectation**2)

def dispersion():
  return(sxoe() - se())

print(dispersion())

出力結果

5.833333333333336

終わりに

numpyを使えば一瞬ですが、今回は自分で実装しました。
もっと効率のよい書き方や分かりやすい変数名があるよという方はコメントで是非ご意見ください。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0