8
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Python】randomってどのくらいrandomなの

Posted at

はじめに

randomモジュールを使っていて、ふと「このrandomって、どのくらいランダムなんだろう」と思ったのでmatplotlibを使って棒グラフで表してみました。
因みに、どのくらいランダムなんだろうというのはどの程度のばらつきや偏りがあるのかという話です。
大したものではないので、コードの簡単な説明と結果のベタ張りだけにします。気になった方はコピペして動かしてみてください。

コード

0~9の乱数を10,000個生成してそれぞれの乱数が何個ずつ出たかを数えます。
それを4回繰り返して結果を見ます。
4回繰り返したのは、結果を4分割にして表示させたかっただけで他意はありません。

rangene.py
import random
import matplotlib.pyplot as plt


def gener(min_v, max_v, length, sort=False, sortType=False):
    '''
    gener(min_v, max_v, length, sort=False,sortType=False):
    min_v ~ max_vの乱数をlength個生成する。
    default: sort=False デフォルトはソートは行わない。
    default: sortType=False ソートの順。デフォルトは小さい順(昇順)

    exit: q
    '''
    rand = []
    keys = [i for i in range(min_v, max_v+1)]
    values = []
    for i in range(length):
        rand.append(random.randint(min_v, max_v))
    for i in range(max_v+1):
        values.append(rand.count(i))
    dic = dict(zip(keys, values))
    if sort is True:
        occurrence_num = sorted(
                dic.items(),
                key=lambda x: x[1],
                reverse=sortType)
        dic.clear()
        dic.update(occurrence_num)
        return dic
    return dic


# title:     Generate [length] random numbers from [min_v] to [max_v]
# xlabel:    randint()
# ylabel:    count()
for i in range(1, 5):
    dic = gener(0, 9, 10000, sort=True, sortType=True)
    left = [str(k) for k, v in dic.items()]
    height = [v for k, v in dic.items()]
    label = left
    print('------------------------------------------------------------------')
    print(i, '回目の実行結果')
    print(dic)
    plt.subplot(2, 2, i)
    plt.bar(left, height, tick_label=label)
    plt.grid(True, axis='y', linestyle='dashed', zorder=1)
plt.show()
print('------------------------------------------------------------------')

結果

Figure_1.png

考察

多少の誤差はありましたが、ほぼ偏りはないと言えます。
以上のことを踏まえて、乃木坂のくじを引きに行きました。
くじを箱から引く時は奥の方から取ろうなどは考えずに上から適当に取ったところ、一等のポスター賞が当たりました。つまり、そういうことだと思います。(どういうこと)

8
2
0

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
8
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?