1
0

gambler.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #利用蒙特卡洛模拟赌徒概率
  2. '''
  3. sum : 一次模拟中累计的资金数,刚开始模拟时则是启动资金数
  4. bet:每次下注的金额(赢了则获得同等数量金额,输了则失去同等数量金额)
  5. target:期望账户累计到多少金额就不玩了,默认账户为0就不玩了
  6. trials: 模拟的次数
  7. 期望结果:
  8. 在模拟次数中,胜出的比例是多少。
  9. 每次胜出,用了多少次,平均数/最大数/最小数/中位数如何
  10. '''
  11. import random
  12. import optparse
  13. def gambler(sum_start,bet,target,trials):
  14. win_trial = []
  15. for t in range(trials):
  16. _sum = sum_start
  17. times = 0
  18. times_win = 0
  19. while _sum >0 and _sum <target:
  20. result = bet if random.randrange(0,2)>0 else -bet
  21. _sum += result
  22. times+=1
  23. if _sum >= target:
  24. win_trial.append((times,_sum))
  25. print('total {0} times win, ratio is {1}'.format(len(win_trial),len(win_trial)/trials))
  26. l1 = [t for t,s in win_trial] #获得所有胜出模拟中,投注的次数
  27. average = int(sum(l1)/len(l1)) #获得平均胜出投注次数
  28. max_num = max(l1)
  29. min_num = min(l1)
  30. mid_num = l1[int(len(l1)/2)] if (len(l1)/2)%2 == 1 else (l1[int(len(l1)/2)] + l1[int(len(l1)/2)-1])/2
  31. print('average is {0}, max_num is {1},min_num is {2},mid_num is {3}'.format(average,max_num,min_num,mid_num))
  32. def main():
  33. parser = optparse.OptionParser("""\
  34. usage: %prog [options] infile outfile
  35. simulate the gamble result: how many times you will win, what's the possibility,
  36. average, max, min & middle number of bets""")
  37. parser.add_option("-b", "--bet", dest="bet",
  38. help=("input the sum_start,bet,target,trials"))
  39. opts, args = parser.parse_args()
  40. sum_start,bet,target,trials = opts.bet.split(',')
  41. gambler(int(sum_start),int(bet),int(target),int(trials))
  42. main()