Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

Python program that rolls a fair die counts the number of rolls before a 6 shows up

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))

Is the logic used here correct? It will repeat rolling a die till a one is rolled, while keeping track of the number of rolls it took before a one showed up. It gives a value of 0.85 when I run it for high values(500+)

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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}')

One sample output:

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

Another sample output:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...