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

randommoney.py をダウンロード

randommoney.py
randommoney.py
  1#!/usr/bin/env python3
  2# -*- coding: utf-8 -*-
  3import sys
  4import random
  5from math import exp
  6from matplotlib import pyplot as plt
  7
  8"""
  9Modified Boltzmann money game:
 10Instead of conserving total money, each person randomly gains or loses
 11money from an external source (the organizer) each cycle.
 12The change is uniform random in [-1, 1].
 13"""
 14
 15#=============================
 16# Default parameters
 17#=============================
 18npersons = 200
 19value    = 1000
 20vtrade   = 1
 21niter    = 10000
 22nplotinterval = 100
 23nfx = 21
 24
 25#=============================
 26# Parse arguments
 27#=============================
 28argv = sys.argv
 29if len(argv) == 1:
 30    print("Usage: python randomgain.py npersons value n(maxiteration) n(plotinterval) n(distribution func)")
 31    print("   ex: python randomgain.py 200 50 10000 100 21")
 32else:
 33    if len(argv) >= 2:
 34        npersons = int(argv[1])
 35    if len(argv) >= 3:
 36        value = float(argv[2])
 37    if len(argv) >= 4:
 38        vtrade = float(argv[3])
 39    if len(argv) >= 5:
 40        niter = int(argv[4])
 41    if len(argv) >= 6:
 42        nplotinterval = int(argv[5])
 43    if len(argv) >= 7:
 44        nfx = int(argv[6])
 45
 46#=============================
 47# Main routine
 48#=============================
 49def main():
 50    xindex = range(npersons)
 51    v = [value for _ in range(npersons)]
 52
 53    print("")
 54    print("Random external fluctuation model:")
 55    print("Each person gains or loses money Δv ~ Uniform(-1,1) each iteration.")
 56    print("Money cannot go below 0.")
 57    print(f"{npersons=}")
 58    print(f"{vtrade=}")
 59    print(f"{niter=}")
 60    print(f"{nplotinterval=}")
 61    print(f"{nfx=}")
 62    print("")
 63
 64    fig = plt.figure(figsize=(6,8))
 65    ax1 = fig.add_subplot(3, 1, 1)
 66    ax2 = fig.add_subplot(3, 1, 2)
 67    ax3 = fig.add_subplot(3, 1, 3)
 68    plt.subplots_adjust(wspace=0.2, hspace=0.3)
 69
 70    for i in range(niter):
 71        # --- 外部ノイズによる増減 ---
 72        for j in range(npersons):
 73            v[j] += vtrade * random.uniform(-1, 1)
 74# お金が負にならない条件。このため、初期値のvalueが小さいときは、高額側にガウス関数の裾となる非対称分布になる
 75            if v[j] < 0: v[j] = 0.0
 76
 77        vs = sorted(v)
 78
 79        # --- 一定ステップでグラフ更新 ---
 80        if i == 0 or (i+1) % nplotinterval == 0 or i == niter - 1:
 81            avg = sum(v)/npersons
 82            vmax = max(v)
 83            vstep = vmax / (nfx - 1) if vmax > 0 else 1.0
 84
 85            fx, fy = [], []
 86            for ifx in range(nfx):
 87                vlim0 = ifx * vstep
 88                vlim1 = (ifx + 1) * vstep
 89                fx.append(vlim0)
 90                fy.append(sum(1.0/vstep for vi in v if vlim0 < vi <= vlim1))
 91
 92            ax1.cla()
 93            ax2.cla()
 94            ax3.cla()
 95
 96            ax1.bar(xindex, v, width=1.5)
 97            ax1.plot([0, npersons], [avg, avg], linestyle='dashed', color='red', linewidth=0.5)
 98            ax1.set_title(f'External random exchange (i={i+1}/{niter}, avg={avg:.2f})')
 99            ax1.set_xlabel("person index")
100            ax1.set_ylabel("money")
101            ax1.set_xlim([0, npersons])
102
103            ax2.bar(xindex, vs, width=1.5)
104            ax2.plot([0, npersons], [avg, avg], linestyle='dashed', color='red', linewidth=0.5)
105            ax2.set_xlim([0, npersons])
106            ax2.set_xlabel("sorted index")
107            ax2.set_ylabel("money (sorted)")
108
109            ax3.plot(fx, fy, label='distribution')
110            ax3.set_xlim([0, vmax])
111            ax3.set_ylim([0, max(fy) + 1])
112            ax3.set_xlabel("money")
113            ax3.set_ylabel("frequency / value")
114            ax3.legend()
115
116            plt.pause(0.1)
117
118    print("Press ENTER to exit>>", end='')
119    input()
120
121if __name__ == '__main__':
122    main()