3

I'm kinda new to python and I would appreciate your help :) I have the following code :

import random
x = 1
def round():
    return random.randint(1,6)
for i in range(8):
    result = round()
    if result > x:
        x = result
if x == 5:
print "True"

The goal is to calculate the probability of the program to print "True", The probability should be 0.193. What would be the most effective way with maximum efficiency to do it? I thought about something related to bernoulli distribution and tried but my result was wrong. Thanks!

4
  • 3
    I dont know why people are down-voting without at least giving some explanation. Obviously this person is new and doesnt know the best way to formulate the question, but we should be here to help people learn, not to punish them for being new. Commented Jan 23, 2016 at 20:56
  • 2
    Sunz, it would make it easier for people to help you if you clarified something. What is it you are trying to acomplish here? Are you trying to print out "True" every time you randomly get the number 5? Print out "True" if the number 5 was randomly sampled at least once? Calculate the empirical probability of getting at least one 5 after running an sampling experiment? Or get the true probability of getting at least one 5? Commented Jan 23, 2016 at 21:00
  • I'm glad the downvotes have been counteracted now :) Commented Jan 23, 2016 at 21:02
  • Thanks ronrest :) I try to calculate the chance to print "True" in one-time run of the program. Hugh Bothwell gave me the answer I looked for. Commented Jan 23, 2016 at 21:11

2 Answers 2

5

The first step is to realize that your program simplifies to

x = max(randint(1,6) for _ in range(8))

then the odds that x == 5 is

prob(nothing higher than 5) - prob(nothing higher than 4)

which is

(5/6)**8 - (4/6)**8   # => 0.19354959705075458
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks mate, now it looks so easy to understand ! I had to calculate it in order to use it for more complicated code I'm working on.
2

If I got your question right, you want to understand how randomint actually generates the numbers (the distribution). It looks that it generates them in an uniform way (you have approximately the same chance of getting any number in the interval).

More details can be found here, here and even more "nerdish" here.

Thus, Hugh Bothwell's answer is correct (it is based on the uniform distribution of numbers you get).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.