確率分布と乱数の取得


In [1]:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pandas import Series, DataFrame

練習問題

(1) 2個のサイコロを振った結果をシュミレーションします。次の例のように、1〜6の整数のペアを含むarrayを乱数で生成してください。

array([3, 5])

In [2]:
from numpy.random import randint
randint(1,7,2)


Out[2]:
array([6, 1])

(2) 2個のサイコロを振った結果を10回分用意します。次の例のように、1〜6の整数のペア(リスト)を10組含むarrayを生成して、変数 dice に保存してください。

array([[6, 5], [3, 5], [1, 4], [6, 4], [4, 3], [2, 3], [1, 5], [4, 1], [3, 4], [2, 5]])

In [3]:
dice = randint(1,7,[10,2])
dice


Out[3]:
array([[3, 4],
       [4, 5],
       [6, 1],
       [1, 1],
       [2, 3],
       [4, 5],
       [5, 1],
       [3, 5],
       [4, 5],
       [3, 3]])

(3) 変数 dice に保存されたそれぞれの結果に対して、次の例のように、2個のサイコロの目の合計を計算してください。(計算結果はリストに保存すること。)

[11, 8, 5, 10, 7, 5, 6, 5, 7, 7]

In [4]:
[a+b for (a,b) in dice]


Out[4]:
[7, 9, 7, 2, 5, 9, 6, 8, 9, 6]

(4) 2個のサイコロの目の合計を1000回分用意して、2〜12のそれぞれの回数をヒストグラムに表示してください。

ヒント:オプション bins=11, range=(1.5, 12.5) を指定するときれいに描けます。


In [5]:
dice = randint(1,7,[1000,2])
sums = [a+b for (a,b) in dice]
plt.hist(sums, bins=11, range=(1.5, 12.5))


Out[5]:
(array([  28.,   55.,   72.,   95.,  155.,  170.,  137.,  113.,   87.,
          56.,   32.]),
 array([  1.5,   2.5,   3.5,   4.5,   5.5,   6.5,   7.5,   8.5,   9.5,
         10.5,  11.5,  12.5]),
 <a list of 11 Patch objects>)

(5) 0≦x≦1 の範囲を等分した10個の点 data_x = np.linspace(0,1,10) に対して、sin(2πx) の値を格納したarrayを作成して、変数 data_y に保存しなさい。

さらに、data_y に含まれるそれぞれの値に、標準偏差 0.3 の正規分布に従う乱数を加えたarrayを作成して、変数 data_t に保存した後、(data_x, data_t) を散布図に表示しなさい。


In [6]:
from numpy.random import normal

data_x = np.linspace(0,1,10)
data_y = np.sin(2*np.pi*data_x)
data_t = data_y + normal(loc=0, scale=0.3, size=len(data_y))
plt.scatter(data_x, data_t)


Out[6]:
<matplotlib.collections.PathCollection at 0x46fa050>