""" 概要: ランダムな取引による資産分布の統計的変化をシミュレーションします。 詳細説明: 全員が同じ資産を持つ状態からスタートし、ランダムに選ばれた相手に一定額を渡すサイクルを繰り返します。 取引の経過とともに資産の分布が指数分布に近づく様子や、エントロピーの推移を可視化します。 関連リンク: randomtrade_numpy_usage """ import sys import numpy as np from math import exp from matplotlib import pyplot as plt import matplotlib # MS Gothic フォント設定(日本語表示対応) matplotlib.rcParams['font.family'] = 'MS Gothic' """ Statistical results of random trade: Start from the uniform situation where everyone has the same money, repeat the cycle to exchange a constant dollars with a randomly selected person. """ #============================= # 大域変数の定義 #============================= npersons = 50 value = 50 vtrade = 1 niter = 500 nplotinterval = 100 nfx = 21 # Treat arguments argv = sys.argv if len(argv) == 1: print("Usage: python randomtrade_numpy.py npersons value vtrade niter nplotinterval nfx") print(" ex: python randomtrade_numpy.py 200 50 1 10000 100 21") exit() if len(argv) >= 2: npersons = int(argv[1]) if len(argv) >= 3: value = int(argv[2]) if len(argv) >= 4: vtrade = int(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]) # エントロピー計算関数(NumPyベース) def calc_entropy(fy): """ 概要: 度数分布からエントロピーを計算します。 詳細説明: 入力された度数配列を確率分布に変換し、0より大きい要素についてエントロピーを計算します。 引数: :param fy: 度数を格納した配列。 :type fy: numpy.ndarray 戻り値: :returns: 計算されたエントロピーの値。 :rtype: float """ p = fy / np.sum(fy) p = p[p > 0] return -np.sum(p * np.log(p)) def main(): """ 概要: ランダムトレードのシミュレーションを実行し結果をプロットします。 詳細説明: コマンドライン引数から大域変数に設定されたシミュレーション条件を使用し、資産のランダムな交換を繰り返します。 指定されたインターバルごとに、各人の資産、ソート済み資産、資産の度数分布、およびエントロピーの推移を描画します。 戻り値: :returns: 戻り値はありません。 :rtype: None """ xindex = np.arange(npersons) v = np.full(npersons, value, dtype=float) print("") print("Analyatical distribution:") xmax = value * 10.0 nftx = 101 xstep = xmax / (nftx - 1) b = 1.0 / value A = npersons * b print(" x range: 0 - %g" % (xmax)) print(" x step: %g" % (xstep)) print(" f(x) = %g * exp(-%g * x)" % (A, b)) ftx = np.linspace(0, xmax, nftx+1) fty = A * np.exp(-b * ftx) fig = plt.figure(figsize=(8, 10)) ax1 = fig.add_subplot(4, 1, 1) ax2 = fig.add_subplot(4, 1, 2) ax3 = fig.add_subplot(4, 1, 3) ax4 = fig.add_subplot(4, 1, 4) entropy_history = [] step_history = [] for i in range(niter): # 元のプログラムに合わせて、ipは全員を順番に処理し、渡す相手(itarget)のみランダムに決定する itargets = np.random.randint(0, npersons, size=npersons) for ip, itarget in enumerate(itargets): if v[ip] >= vtrade: v[ip] -= vtrade v[itarget] += vtrade else: v[itarget] += v[ip] v[ip] = 0 if i == 0 or (i+1) % nplotinterval == 0 or i == niter - 1: vs = np.sort(v) vmax = np.max(v) # density=Trueを使わず度数を取得し、ビン幅(vstep)で割ることで理論式とスケールを合わせる counts, bin_edges = np.histogram(vs, bins=nfx, range=(0, vmax)) vstep = bin_edges[1] - bin_edges[0] if vstep > 0: fy = counts / vstep else: fy = counts.astype(float) fx = bin_edges[:-1] # エントロピーとステップ数を記録 entropy = calc_entropy(fy) entropy_history.append(entropy) step_history.append(i + 1) ax1.cla() ax2.cla() ax3.cla() ax4.cla() ax1.bar(xindex, v, width = 1.5) ax1.plot([0, npersons], [value, value], linestyle = 'dashed', color = 'red', linewidth = 0.5) ax1.set_title('Random trade (i = %d/%d, n=%d, avg=%d)' % (i+1, niter, npersons, value)) ax1.set_xlabel("i") ax1.set_ylabel("value") ax1.set_xlim([0, npersons]) ax2.bar(xindex, vs, width = 1.5) ax2.plot([0, npersons], [value, value], linestyle = 'dashed', color = 'red', linewidth = 0.5) ax2.set_xlim([0, npersons]) ax2.set_xlabel("i") ax2.set_ylabel("value (sorted)") ax3.plot(fx, fy, label = 'distrib') ax3.plot(ftx, fty, label = 'exponential', color = "red", linewidth = 0.5, linestyle = 'dashed') ax3.set_xlim([0, vmax]) # 理論値の最大値(A)が実データより大きい場合でも見切れないように調整 ax3.set_ylim([0, max(np.max(fy), A) + 1]) ax3.set_xlabel("value") ax3.set_ylabel("frequency / value") ax3.legend() # ステップ数をX軸として描画 ax4.plot(step_history, entropy_history, color='green') ax4.set_title("エントロピーの推移 S = -ΣP log P") ax4.set_xlabel("ステップ") ax4.set_ylabel("エントロピー") ax4.set_xlim([0, niter]) # エントロピーの下限上限を適正化 ax4.set_ylim([0, max(entropy_history) * 1.2 if entropy_history else 3.0]) plt.tight_layout() plt.pause(0.1) print("Press ENTER to exit>>", end = '') input() if __name__ == '__main__': main()