我在代码中使用random()计算获胜的次数,但结果与预期一致

2024-04-26 19:13:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这个代码是用来模拟壁球的。 当我和两个变化相同的人一起跑赢时,我注意到winsB总是4700+,winsA总是5200+,所以我试着这样做:

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

所有的结果都是正确的,但我不能检查我的错误代码。为什么,谢谢


Tags: orofthereturnifisdefelse
1条回答
网友
1楼 · 发布于 2024-04-26 19:13:40

最初的服务总是“A”,这是不公平的。 你只需要应用这个修改

# not fair
serving = 'A'

# note: we assume probA + probe == 1.0

# initial serving is decided by players' skill
serving = 'A' if probA > random() else 'B'

# or, initial serving is decided by a coin
serving = 'A' if 0.5 > random() else 'B'

相关问题 更多 >