首页 > 解决方案 > 掷骰子的 Python 程序计算出现 6 之前的掷骰数

问题描述

import random

sample_size = int(input("Enter the number of times you want me to roll the die: "))

if (sample_size <=0):

    print("Please enter a positive number!")

else:
    counter1 = 0

    counter2 = 0

    final = 0

    while (counter1<= sample_size):

        dice_value = random.randint(1,6)

        if ((dice_value) == 6):
            counter1 += 1

        else:
            counter2 +=1

    final = (counter2)/(sample_size)  # fixing indention 


print("Estimation of the expected number of rolls before pigging out: " + str(final))

这里使用的逻辑是否正确?它将重复掷骰子,直到掷出一个骰子,同时跟踪在出现一个骰子之前所用的掷骰数。当我运行它以获取高值(500+)时,它给出的值为 0.85

谢谢

标签: pythonpython-3.xprobabilitydice

解决方案


import random

while True:
  sample_size = int(input("Enter the number of times you want me to roll a die: "))
  if sample_size > 0:
    break

roll_with_6 = 0
roll_count = 0

while roll_count < sample_size:
  roll_count += 1
  n = random.randint(1, 6)
  #print(n)
  if n == 6:
    roll_with_6 += 1

print(f'Probability to get a 6 is = {roll_with_6/roll_count}')

一个样本输出:

Enter the number of times you want me to roll a dile: 10
Probability to get a 6 is = 0.2

另一个示例输出:

Enter the number of times you want me to roll a die: 1000000
Probability to get a 6 is = 0.167414

推荐阅读