我在代码中使用random()来计算获胜的时间,但结果是预期的

时间:2015-08-03 04:01:05

标签: python random

def simNGame(probA, probB, n):
# simulate n games 
# prob is the chance to win of person A or person B, n is the times of games
# return the number of wins of A and B
winsA = 0
winsB = 0
for i in range(n):
    scoreA, scoreB = simOneGame(probA, probB)
    if scoreA > scoreB:
        winsA += 1
    else:
        winsB += 1
return winsA, winsB

def simOneGame(probA, probB):
    # simulate 1 game
    # return the score of A and B
    scoreA = 0
    scoreB = 0
    serving = 'A'
    while not gameOver(scoreA, scoreB):
        if serving == 'A':
            if probA > random():
                scoreA += 1
            else:
                serving = 'B'
        else:
            if probB > random():
                scoreB += 1
            else:
                serving = 'A'
    return scoreA, scoreB

def gameOver(scoreA, scoreB):
    # check the game is over or not
    return scoreA == 15 or scoreB == 15

此代码用于模拟racquetaball。 当我和两个人一起跑来赢得比赛时,我注意到winsB总是4700+而且winsA总是5200+,所以我试试这个:

while True:
    a, b = simNGame(0.5, 0.5, 10000)
    print a > b

所有结果都是True,但我无法检查代码中的任何错误。为什么,谢谢

1 个答案:

答案 0 :(得分:2)

最初的服务总是'A',这是不公平的。 您只需要应用此修改

patches()