#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import random from math import exp from matplotlib import pyplot as plt """ Modified Boltzmann money game: Instead of conserving total money, each person randomly gains or loses money from an external source (the organizer) each cycle. The change is uniform random in [-1, 1]. """ #============================= # Default parameters #============================= npersons = 200 value = 1000 vtrade = 1 niter = 10000 nplotinterval = 100 nfx = 21 #============================= # Parse arguments #============================= argv = sys.argv if len(argv) == 1: print("Usage: python randomgain.py npersons value n(maxiteration) n(plotinterval) n(distribution func)") print(" ex: python randomgain.py 200 50 10000 100 21") else: if len(argv) >= 2: npersons = int(argv[1]) if len(argv) >= 3: value = float(argv[2]) if len(argv) >= 4: vtrade = float(argv[3]) if len(argv) >= 5: niter = int(argv[4]) if len(argv) >= 6: nplotinterval = int(argv[5]) if len(argv) >= 7: nfx = int(argv[6]) #============================= # Main routine #============================= def main(): xindex = range(npersons) v = [value for _ in range(npersons)] print("") print("Random external fluctuation model:") print("Each person gains or loses money Δv ~ Uniform(-1,1) each iteration.") print("Money cannot go below 0.") print(f"{npersons=}") print(f"{vtrade=}") print(f"{niter=}") print(f"{nplotinterval=}") print(f"{nfx=}") print("") fig = plt.figure(figsize=(6,8)) ax1 = fig.add_subplot(3, 1, 1) ax2 = fig.add_subplot(3, 1, 2) ax3 = fig.add_subplot(3, 1, 3) plt.subplots_adjust(wspace=0.2, hspace=0.3) for i in range(niter): # --- 外部ノイズによる増減 --- for j in range(npersons): v[j] += vtrade * random.uniform(-1, 1) # お金が負にならない条件。このため、初期値のvalueが小さいときは、高額側にガウス関数の裾となる非対称分布になる if v[j] < 0: v[j] = 0.0 vs = sorted(v) # --- 一定ステップでグラフ更新 --- if i == 0 or (i+1) % nplotinterval == 0 or i == niter - 1: avg = sum(v)/npersons vmax = max(v) vstep = vmax / (nfx - 1) if vmax > 0 else 1.0 fx, fy = [], [] for ifx in range(nfx): vlim0 = ifx * vstep vlim1 = (ifx + 1) * vstep fx.append(vlim0) fy.append(sum(1.0/vstep for vi in v if vlim0 < vi <= vlim1)) ax1.cla() ax2.cla() ax3.cla() ax1.bar(xindex, v, width=1.5) ax1.plot([0, npersons], [avg, avg], linestyle='dashed', color='red', linewidth=0.5) ax1.set_title(f'External random exchange (i={i+1}/{niter}, avg={avg:.2f})') ax1.set_xlabel("person index") ax1.set_ylabel("money") ax1.set_xlim([0, npersons]) ax2.bar(xindex, vs, width=1.5) ax2.plot([0, npersons], [avg, avg], linestyle='dashed', color='red', linewidth=0.5) ax2.set_xlim([0, npersons]) ax2.set_xlabel("sorted index") ax2.set_ylabel("money (sorted)") ax3.plot(fx, fy, label='distribution') ax3.set_xlim([0, vmax]) ax3.set_ylim([0, max(fy) + 1]) ax3.set_xlabel("money") ax3.set_ylabel("frequency / value") ax3.legend() plt.pause(0.1) print("Press ENTER to exit>>", end='') input() if __name__ == '__main__': main()