fork(1) download
  1. import random
  2.  
  3. # for readability
  4. HEADS = 0
  5. TAILS = 1
  6.  
  7. # just defined to get input
  8. yes = 1
  9. no = 0
  10.  
  11. # determine how many iterations
  12. n = input("How many samples do you wish to compute?: ")
  13. # should we generate a p value for the coin every iteration?
  14. generate_p_every_iteration = input('Should we generate p every iteration? (yes/no): ')
  15.  
  16. # if we should...
  17. if not generate_p_every_iteration:
  18. p = random.random()
  19. print "probability of getting heads is:", p
  20.  
  21. correctGuesses = 0
  22. wrongGuesses = 0
  23.  
  24. for i in range(0, n):
  25.  
  26. if generate_p_every_iteration:
  27. p = random.random()
  28.  
  29. # the choice for either heads
  30. choice = random.randint(HEADS, TAILS)
  31.  
  32. # actual coin flip
  33. coinFlip = random.random()
  34.  
  35. # if we get a heads
  36. if coinFlip < p:
  37. # if we guessed heads
  38. if choice == HEADS:
  39. # then we guessed correctly
  40. correctGuesses += 1
  41. else:
  42. # otherwise, we guessed wrong
  43. wrongGuesses += + 1
  44.  
  45. # otherwise if we got a tails
  46. else:
  47. # if we guessed tails
  48. if choice == TAILS:
  49. # then we guessed correctly
  50. correctGuesses += 1
  51. else:
  52. # otherwise we got the guess wrong
  53. wrongGuesses += 1
  54.  
  55.  
  56. percentageCorrect = float(correctGuesses) / n
  57. print "correct guesses:", correctGuesses, "(" + str(percentageCorrect) + ")"
  58. print "wrong guesses:", wrongGuesses, "(" + str(1 - percentageCorrect) + ")"
Success #stdin #stdout 3.4s 10440KB
stdin
1000000
no
stdout
How many samples do you wish to compute?: Should we generate p every iteration? (yes/no): probability of getting heads is: 0.171318334604
correct guesses: 500390 (0.50039)
wrong guesses: 499610 (0.49961)