Python蒙特卡洛模拟:如何将掷两骰子的和累加到total变量?
解决两次掷骰子模拟的累加问题
你的需求是模拟两次掷骰子的平均值计算,现有代码已经搭好了基础框架,但有两处关键问题需要修正才能实现功能:
现有代码
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()
修改步骤
- 让
simulate()函数返回结果:函数里已经算出了两个骰子的和,但没有把这个值返回出去,需要在函数末尾加上return sum。 - 将函数返回值累加到
total:循环里调用simulate()时,要把每次得到的结果加到total变量上,写成total += simulate()即可。 - 计算并输出平均值:循环结束后,用总累加值除以试验次数(1000)就能得到平均值。
修改后的完整代码
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 = dice_1 + dice_2 # 把变量名改成sum_dice,避免和Python内置的sum()函数冲突 return sum_dice ### Main seed(0) total = 0 # 循环执行1000次模拟 for trial in range(1000): total += simulate() # 计算并打印平均值 average = total / 1000 print(f"1000次模拟的平均值: {average}")
补充说明
- 把变量名
sum改成sum_dice是个编程好习惯,能避免覆盖Python内置的sum()函数,减少潜在问题。 seed(0)用来固定随机数种子,这样每次运行代码得到的结果都一致,方便测试和验证。
内容的提问来源于stack exchange,提问作者roTenshi2
相关产品推荐
相关产品推荐

