monte carlo 个预先存在的程序

monte carlo of a preexisting program

diceGame.py(下方)中的 python 代码包含我们在 class 中讨论的骰子游戏的 python 实现。假设我们 运行 代码 N 次,并根据 A 发生的次数除以 N 来估计某个事件 A 的概率 P r{A}。然后我们重复这个过程 M 次,收集概率 pi , 我 = 1, . . . , M. 假设两个骰子都是公平的,修改diceGame.py的主程序,使用N=10,100,1000和M=100,概率如下:

在第一次掷骰子时赢得游戏的概率。

第一次掷出 4 时赢得游戏的概率。

赢得比赛的概率。

一场比赛需要掷骰子超过 5 次的概率。

我知道所有这些答案都可以通过代码本身轻松提供。我的问题是我不知道如何编辑 python 代码来提供这些所需的输出。

代码如下:

# ===============================
# IMPORTS RANDOM NUMBER GENERATOR
# ===============================
import random

# ================================================================
# GENERATES RANDOMLY THE SUM OF TWO INTEGERS IN THE [1,6] INTERVAL
# ================================================================
def rollDices():
  return int(random.randint(1,6) + random.randint(1,6))

# ================================================
# RETURN THE OUTCOME STRING GIVEN AN INTEGER STATE
# ================================================
def getOutcome(outcome):  
  if(outcome == 0):
    result = "Lost at first roll."
  elif(outcome == 1):
    result = "Won at first roll."
  elif(outcome == 2):
    result = "Won on [4,5,6,8,9,10]"
  elif(outcome == 3):
    result = "Lost on [4,5,6,8,9,10]"
  return result

# ==============
# PLAYS THE GAME
# ==============
def playGame():

  # Define Variables
  gameFinished = False
  wonGame = False
  totRolls = 0

  while (not(gameFinished)):

    # ROLL DICES
    totScore = rollDices()
    totRolls += 1;

    # GAME IS LOST
    if(totScore in [2,3,12]):
      gameFinished = True
      wonGame = False
      return 0,wonGame,totRolls,totScore

    # GAME IS WON
    if(totScore in [7,11]):
      gameFinished = True
      wonGame = True
      return 1,wonGame,totRolls,totScore

    # JUST CONTINUE PLAYING
    if(totScore in [4,5,6,8,9,10]):      

      # REPEAT UNTIL YOU FIND THE SCORE AGAIN OR 7
      newScore = 0
      while((newScore != totScore)and(newScore != 7)):

        newScore = rollDices()
        totRolls += 1;

        # CHECK IF YOU WIN OR LOOSE
        if(newScore == totScore):
          gameFinished = True
          wonGame = True
          return 2,wonGame,totRolls,totScore

        if(newScore == 7):
          gameFinished = True
          wonGame = False
          return 3,wonGame,totRolls,totScore

# ============
# MAIN PROGRAM
# ============
if __name__ == "__main__":

  intVal,wonGame,numRolls,lastScore = playGame()

  print("Outcome: %s" % (getOutcome(intVal)))
  if(wonGame):
    print("You have won the game.")
  else:
    print("You have lost the game.")
  print("Total rolls needed for this game: %d" % (numRolls))
  print("Last outcome: %d" % (lastScore))

尝试问题时的新主要功能:

if __name__ == "__main__":
    m = 100
    n = 10
    FRwins = 0
    for i in range(m):
        for j in range(n):
            intVal,wonGame,numRolls,lastScore = playGame()
            if getOutcome(intVal) == 1:
                FRwins += 1
        FRwins = FRwins/float(n)
        print(FRwins)

目前本程序正在玩游戏一次。如果您查看最后 10 行代码,那就是您要进行调整以执行此操作的内容。重要的一行是:

intVal,wonGame,numRolls,lastScore = playGame()

它只被调用一次,所以你只能从中得到一个结果。由于您需要进行 Monte Carlo 模拟(即一遍又一遍地播放并跟踪概率),您只需多次重播此行,并每次都跟踪结果。

从那里开始,您将需要设置一些 for 循环,例如:

for i in range(m):

并跟踪每次模拟的结果。由于您正在使用 m 和 n,因此您需要围绕 playGame() 的嵌套循环。然后你只需要边走边计算结果,然后除以总尝试次数就可以得到你的概率。

希望这对您有所帮助。请随时提出更多问题 - 我试图让它足够笼统,以至于我实际上并没有为你的作业编写代码!