randomtrade.py ダウンロード/コピー

randomtrade.py をダウンロード

randomtrade.py
randomtrade.py
  1import sys
  2import random
  3from math import exp
  4from matplotlib import pyplot as plt
  5
  6"""
  7Statistical results of random trade:
  8Start from the uniform situation where everyone has the same money,
  9repeat the cycle to exchange a constant dollars with a randomly selected person.
 10"""
 11
 12#=============================
 13# 大域変数の定義
 14#=============================
 15# Number of persons
 16npersons = 50
 17# The initial money that the persons have, equal to the average money
 18value    = 50
 19# The money traded at each cycle
 20vtrade   =  1
 21# The number of maximum iteration
 22niter    = 500
 23# The cycle to update graph
 24nplotinterval = 100
 25
 26# The number of x mesh for distribution function
 27nfx = 21
 28
 29
 30# Treat argments
 31argv = sys.argv
 32if len(argv) == 1:
 33    print("Usage: python randomtrade.py npersons value(average) vtrade n(maxiteration) n(plotinterval) n(distribution func)")
 34    print("   ex: python randomtrade.py 200 50 1 10000 100 21")
 35    exit()
 36
 37if len(argv) >= 2:
 38    npersons = int(argv[1])
 39if len(argv) >= 3:
 40    value = int(argv[2])
 41if len(argv) >= 4:
 42    vtrade = int(argv[3])
 43if len(argv) >= 5:
 44    niter = int(argv[4])
 45if len(argv) >= 6:
 46    nplotinterval = int(argv[5])
 47if len(argv) >= 7:
 48    nfx = int(argv[6])
 49
 50
 51def main():
 52# 初期化
 53    xindex = range(npersons)  # list of indexes of the persons to be used for x axis 
 54    v = []               # list of money the persons have
 55    for i in range(npersons):
 56        v.append(value)
 57
 58#=============================
 59# グラフの表示
 60#=============================
 61# theoretical distribution: f = A * exp(-bv)
 62# A and b are determined by the number of persons and the money average
 63    print("")
 64    print("Analyatical distribution:")
 65    xmax = value * 10.0
 66    nftx = 101
 67    xstep = xmax / (nftx - 1)
 68    b = 1.0 / value
 69    A = npersons * b
 70    print("  x range: 0 - %g" % (xmax))
 71    print("  x step: %g" % (xstep))
 72    print("  f(x) = %g * exp(-%g * x)" % (A, b))
 73    ftx = []
 74    fty = []
 75    for i in range(nftx+1):
 76        x = i * xstep
 77        ftx.append(x)
 78        fty.append(A * exp(-b * x))
 79
 80# Prepare plot
 81    fig = plt.figure(figsize=(6,8))
 82
 83    ax1 = fig.add_subplot(3, 1, 1)
 84    ax2 = fig.add_subplot(3, 1, 2)
 85    ax3 = fig.add_subplot(3, 1, 3)
 86    plt.subplots_adjust(wspace = 0.2, hspace = 0.3)
 87
 88# trade
 89    for i in range(niter):
 90        for ip in range(npersons):
 91            itarget = int(random.random() * npersons)
 92            if v[ip] >= vtrade:
 93                v[itarget] += vtrade
 94                v[ip] -= vtrade
 95            else:
 96                v[itarget] += v[ip]
 97                v[ip] = 0
 98
 99        vs = sorted(v)
100
101        if i == 0 or (i+1) % nplotinterval == 0 or i == niter - 1:
102# calculate distribution function f(x)
103            vmax = max(v)
104            vstep = vmax / (nfx - 1)
105
106            fx  = []
107            fy  = []
108            for ifx in range(nfx):
109                vlim0 = ifx * vstep
110                vlim1 = (ifx+1) * vstep
111                fx.append(vlim0)
112                fy.append(0.0)
113                for ip1 in range(npersons):
114                    if vlim0 < vs[ip1] <= vlim1:
115                        fy[ifx] += 1.0 / vstep
116
117            ax1.cla()
118            ax2.cla()
119            ax3.cla()
120
121            ax1.bar(xindex, v, width = 1.5)
122            ax1.plot([0, npersons], [value, value], linestyle = 'dashed', color = 'red', linewidth = 0.5)
123            ax1.set_title('Random trade (i = %d/%d, n=%d, avg=%d)' % (i+1, niter, npersons, value))
124            ax1.set_xlabel("i")
125            ax1.set_ylabel("value")
126            ax1.set_xlim([0, npersons])
127
128            ax2.bar(xindex, vs, width = 1.5)
129            ax2.plot([0, npersons], [value, value], linestyle = 'dashed', color = 'red', linewidth = 0.5)
130            ax2.set_xlim([0, npersons])
131            ax2.set_xlabel("i")
132            ax2.set_ylabel("value (sorted)")
133
134            ax3.plot(fx, fy, label = 'distrib')
135            ax3.plot(ftx, fty, label = 'exponential', color = "red", linewidth = 0.5, linestyle = 'dashed')
136            ax3.set_xlim([0, vmax])
137            ax3.set_ylim([0, max(fy) + 1])
138            ax3.set_xlabel("value")
139            ax3.set_ylabel("frequency / value")
140            ax3.legend()
141
142            plt.pause(0.1)
143
144    print("Press ENTER to exit>>", end = '')
145    input()
146
147
148if __name__ == '__main__':
149    main()
150