本ページでは、Python の数値計算ライブラリである、Numpy を用いて各種の乱数を出力する方法を紹介します。
一様乱数を出力する
一様乱数 (0.0 – 1.0) の間のランダムな数値を出力するには、numpy.random.rand(出力する件数) を用います。
>>> import numpy as np
>>> # 一様乱数 を 1 件出力する
>>> np.random.rand()
0.5880118049738298
>>> # 一様乱数 を 3 件出力する
>>> np.random.rand(3)
array([ 0.44895901, 0.39833764, 0.99688209])
>>> # 一様乱数 を 3 x 4 の行列で出力する
>>> np.random.rand(3, 4)
array([[ 0.0526965 , 0.01470381, 0.33005156, 0.14598275],
[ 0.41548295, 0.69093009, 0.78780918, 0.4854191 ],
[ 0.89098149, 0.23846317, 0.49385737, 0.54687586]])
正規乱数を出力する
正規分布に従う乱数を出力するには、numpy.random.normal(平均, 標準偏差, 出力する件数) を用います。引数を省略した場合、平均=0.0, 標準偏差=1.0, 出力する件数= 1 件 で出力されます。
>>> # 標準正規乱数 (平均:0.0, 標準偏差:1.0) に従う乱数を 1 件出力
>>> np.random.normal()
0.12890432430863327
>>> # 平均:50, 標準偏差:10 の正規分布に従う乱数を 1 件出力
>>> np.random.normal(50, 10)
55.23859599943137
>>> # 平均:50, 標準偏差:10 の正規分布に従う乱数を 10 件出力
>>> np.random.normal(50, 10, 10)
array([ 41.47842808, 55.36697519, 55.41006179, 60.46076945,
47.02306476, 46.17782061, 48.31107382, 74.0148896 ,
51.92453455, 52.87749175])
>>> # 平均:50, 標準偏差:10 の正規分布に従う乱数を 3 x 4 の行列で出力する
>>> np.random.normal(50, 10, (3, 4))
array([[ 57.94314009, 46.10303583, 44.18268309, 49.67259448],
[ 53.14574004, 68.02533654, 48.31198285, 41.4084188 ],
[ 44.09861297, 36.2995853 , 50.52124654, 51.25787869]])
特定の区間の整数をランダムに出力する
特定の区間の乱数を出力するには、numpy.random.randint(下限[, 上限,[, 出力する件数]]) を用います。
>>> # 0-10 の間の整数を 1 件出力する >>> np.random.randint(10) 0 >>> # 10-15 の間の整数を 1 件出力する >>> np.random.randint(10, 15) 11 >>> # 1-100 の間の整数を 10 件出力する >>> np.random.randint(1, 100, 10) array([10, 18, 59, 62, 98, 61, 60, 1, 90, 59])
配列をランダムにシャッフルする
配列の順番をランダムに並び替えるには、numpy.random.shuffle(シャッフル対象の配列) を用います。
>>> arr1 = ['A', 'B', 'C', 'D', 'E'] >>> np.random.shuffle(arr1) >>> arr1 ['B', 'A', 'C', 'D', 'E']
乱数のシードを設定する
numpy.random.seed(seed=シードに用いる値) をシード (種) を指定することで、発生する乱数をあらかじめ固定することが可能です。乱数を用いる分析や処理で、再現性が必要な場合などに用いられます。
>>> # シードを 32 に設定して乱数を出力 >>> np.random.seed(seed=32) >>> np.random.rand() 0.8588892672930397 >>> # シードを 32 に設定して乱数を出力 (同じ乱数が出力されます) >>> np.random.seed(seed=32) >>> np.random.rand() 0.8588892672930397