在网上看到一篇文章:穷人和富人就差1%的努力——python模拟社会财富分配游戏,里面有用python来实现这个游戏模拟。
游戏规则是这样的:房间里有100个人,每人都有100元钱,他们在玩一个游戏。每轮游戏中,每个人都要拿出一元钱随机给另一个人,最后这100个人的财富分布是怎样的?
我用python的list来模拟的人-财富:list的下标表示人物id,list的值表示财富值。为啥我每次的结果都是,下标值越靠前,最终的财富越少呢??
源码如下:
import numpy as np
import matplotlib.pyplot as plt
import os
import datetime
'''
房间里有100个人,每人都有100元钱。
他们在玩一个游戏:每轮游戏中,每个人都要拿出一元钱随机给另一个人。
最后这100个人的财富分布是怎样的?
'''
def init_wealthy(person_total, init_money):
wealthy = []
for i in range(0, person_total):
wealthy.append(init_money)
return wealthy
def get_id_to(id_from, total_person):
id_to = np.random.randint(0, total_person)
if id_to == id_from: # 假设不能把钱给自己
id_to = get_id_to(id_from, total_person)
# print("%d give id_to %d" % (owner, id_to))
return id_to
def plot_save(data, save_path, file_name, ith_distribution, dpi=200 ):
plt.clf()
plt.title('round: %d' % ith_distribution)
plt.xlabel('person ID')
plt.ylabel('money')
plt.ylim((-100, 300))
plt.bar(range(len(data)), data)
plt.savefig(os.path.join(save_path, file_name), dpi=dpi)
def check_dir(dir):
if not os.path.exists(dir):
os.mkdir(dir)
print('mkdir: [%s]' % dir)
total_person = 100 # 总人数
init_money = 100 # 初始money数
total_round = 2001 # 分配轮数
save_per_round = 10 # 每多少轮保存一次结果
tt = str(datetime.datetime.now())
t = tt.split('.')[0].replace('-', '').replace(':', '').replace(' ', '')
root_path = os.path.join('./money_data', t) # 存放结果的根目录
check_dir(root_path)
save_path_origin = os.path.join(root_path, 'origin_data') # 原始数据目录
check_dir(save_path_origin)
save_path_sorted = os.path.join(root_path, 'sorted_data') # 排序数据目录
check_dir(save_path_sorted)
list_money = init_wealthy(total_person, init_money)
# 保存初始状态
file_name = '0.png'
plot_save(list_money, save_path_origin, file_name, 0)
list_money.sort()
plot_save(list_money, save_path_sorted, file_name, 0)
for i_round in range(1, total_round): # 分配
for id_from in range(0, total_person): # 对每个人进行操作
id_to = get_id_to(id_from, total_person)
# id_to = np.random.randint(0, total_person)
list_money[id_from] -= 1
list_money[id_to] += 1
if i_round % save_per_round == 0:
file_name = '%d.png' % i_round
plot_save(list_money, save_path_origin, file_name, i_round)
list_money.sort()
plot_save(list_money, save_path_sorted, file_name, i_round)
print('%d/%d' % (i_round, total_round))
print('finished')