読者です 読者をやめる 読者になる 読者になる

bekkou68の日記

開発しているサービス, IT技術, 英語など。

random モジュールの expovariate について - About expovariate of random Module

Python

expovariate とは - What is expovariate?

指数分布の値を返します。詳しくは以下をご参照ください。
expovariate returns value of exponential distribution. More detail, please refer the following page.

6.4 random -- 擬似乱数を生成する


引数 lambd に (1.0 / MEAN) を渡した際、ちゃんと MEAN に近い値が取得できるのかをテストしてみました。
I tested whether I can get a value close to MEAN when I give (1.0 / MEAN) to argument lamdb.

実装 - Implementation

"""
FileName:
    testRandomExpovariate.py
Abstract:
    Test of expovariate of random.
Purpose:
    Test that "Is expovariate really return value closed mean?".
Author:
    bekkou68
"""
import sys
from decimal import *
from random import expovariate

INFINITY = Decimal('Infinity')

if (len(sys.argv) != 3):
    print "Usage: python testRandomExpovariate.py [mean] [execute num]"
    print "[mean] ... get value close to mean by expovariate."
    print "[execute num] ... num of execution of expovariate."
    quit()

mean = float(sys.argv[1])  # Mean, you'd like to get by expovariate.
exe_num = int(sys.argv[2]) # How many expovariate executed.

sum, avg, max, value = 0, 0, 0, 0
min = INFINITY
for i in range(0, exe_num):
    value = expovariate(1.0 / mean)
    sum += value

    if max < value:
        max = value

    if (min > value) or (min == INFINITY):
        min = value

avg = sum / exe_num

print "I'd like to get value by expovariate, expecting close to %f." % mean
print "I executed expovariate %d time. That of average was %f." % (exe_num, avg)
print "Max was %f and min was %f." % (max, min)

テスト - Test

引数なし - No argument

エラー。
Error.

$ python testRandomExpovariate.py
Usage: python testRandomExpovariate.py [mean] [execute num]
[mean] ... get value close to mean by expovariate.
[execute num] ... num of execution of expovariate.
平均 5.0, 実行回数 10 - mean 5.0, execution number 10
$ python testRandomExpovariate.py 5.0 10
I'd like to get value by expovariate, expecting close to 5.000000.
I executed expovariate 10 time. That of average was 6.544561.
Max was 26.171193 and min was 0.883463.
平均 5.0, 実行回数 1000 - mean 5.0, execution number 1000
$ python testRandomExpovariate.py 5.0 1000
I'd like to get value by expovariate, expecting close to 5.000000.
I executed expovariate 1000 time. That of average was 5.115725.
Max was 33.455686 and min was 0.001715.
平均 5.0, 実行回数 100000 - mean 5.0, execution number 100000
$ python testRandomExpovariate.py 5.0 100000
I'd like to get value by expovariate, expecting close to 5.000000.
I executed expovariate 100000 time. That of average was 4.978045.
Max was 61.635366 and min was 0.000019.


おお、実行回数を増やすほど、expovariate の戻り値の平均が MEAN に近くなります。
Wow, the more a number of execution, the closer value of expovariate by comparing to MEAN.


また、指数分布らしく、最大値と最小値の差も増えますね。
And, the larger difference between max and min, like exponential distribution.


−ω−