1. ホーム
  2. python

pythonで確率による乱数生成

2022-02-16 13:02:43
<パス

口は災いの元、コードを見せよ。

random_demo.pyのコードは以下の通りです。

# coding: utf-8
import random

def random_index(rate):
    """Probability function of a random variable"""
	#
    # The parameter rate is the list

    # Returns the subscript index of the probability event
    start = 0
    index = 0
    randnum = random.randint(1, sum(rate))

    for index, scope in enumerate(rate):
        start += scope
        if randnum <= start:
            break
    return index

def main():
    arr = ['red', 'green', 'blue']
    rate = [45, 30, 25]

    red_times = 0
    green_times = 0
    blue_times = 0
    for i in xrange(10000):
        if arr[random_index(rate)] == 'red':
            red_times += 1
        if arr[random_index(rate)] == 'green':
            green_times += 1
        if arr[random_index(rate)] == 'blue':
            blue_times += 1

    print red_times, green_times, blue_times

if __name__ == '__main__':
    main()


結果を表示します。

$ python random_demo.py 
4507 3009 2537
$ python random_demo.py 
4586 3055 2485
$ python random_demo.py 
4483 2996 2506
$ python random_demo.py 
4586 3015 2480
$ python random_demo.py 
4513 3057 2415
$ python random_demo.py 
4494 3014 2456
$ python random_demo.py 
4502 2978 2505
$ python random_demo.py 
4475 3041 2528
$ python random_demo.py 
4561 3043 2520
$ python random_demo.py 
4558 2923 2474
$ python random_demo.py 
4536 2957 2535
$ python random_demo.py 
4526 2985 2576
$ python random_demo.py 
4532 2936 2547
$ python random_demo.py 
4420 2908 2447



注:上記のコード例はPython2.7で、以下のpython3のサンプルコードに置き換えられ、確率事象の数が合計数に加算されることが保証されています。

import random


def random_index(rate):
    """The probability function of a random variable """
    #
    # The parameter rate is the list

    # Returns the subscript index of the probability event
    start = 0
    index = 0
    randnum = random.randint(1, sum(rate))

    for index, scope in enumerate(rate):
        start += scope
        if randnum <= start:
            break
    return index


def main():
    arr = ['red', 'green', 'blue']
    rate = [45, 30, 25]

    red_times = 0
    green_times = 0
    blue_times = 0
    count = 0
    for i in range(10000):
        count += 1
        index = random_index(rate)
        if arr[index] == 'red':
            red_times += 1
        elif arr[index] == 'green':
            green_times += 1
        elif arr[index] == 'blue':
            blue_times += 1

    print(count, red_times, green_times, blue_times)


if __name__ == '__main__':
    main()



ご覧の通り、赤、緑、青のヒット数はその45:30:25の比率に非常に近く、random_index(rate)関数がコアコードとなっていることがわかります。

OK、お楽しみに〜。