【问题标题】:Python question using Monte carlo simulation and for loops使用蒙特卡洛模拟和for循环的Python问题
【发布时间】:2022-11-18 08:59:25
【问题描述】:

这就是问题: 模拟掷两个骰子的平均值。 这是我到目前为止的代码:

from random import seed, randint

def simulate():
    """
    Roll two dice and return their sum
    """


    dice_1 = randint(1,6)
    dice_2 = randint(1,6)
    sum = dice_1 + dice_2




### Main

seed(0) 

total = 0

# Use a for loop that runs for 1000 iterations
for trial in range(1000):
  simulate()

接下来的步骤是:

 # Call simulate() inside the loop to generate the sum
  # of two dice and add it into total

现在,我已经调用了 simulate() 函数,但我对如何将它添加到我拥有的 total 变量中有点困惑。

【问题讨论】:

    标签: python montecarlo


    【解决方案1】:

    我不明白您想做什么,但这对您来说足够了吗?

    from random import seed, randint
    
    def simulate():
        """
        Roll two dice and return their sum
        """
    
    
        dice_1 = randint(1,6)
        dice_2 = randint(1,6)
        sum = dice_1 + dice_2
         # Add A return statement to get your sum after calling the function
        return sum
    
    
    
    ### Main
    
    seed(0) 
    
    total = 0
    
    # Use a for loop that runs for 1000 iterations
    for trial in range(1000):
      # add each time the simulation result to the total
      total = total + simulate()
    
    
    

    【讨论】:

      猜你喜欢
      • 2021-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-02
      • 1970-01-01
      • 2019-10-10
      相关资源
      最近更新 更多