Advertisement
Guest User

Hitting Time of Coin

a guest
Dec 25th, 2013
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.64 KB | None | 0 0
  1. # Given a coin probability p, what is the expected hitting time of getting k trials in a row?
  2. p = 0.505
  3. k = 14
  4.  
  5. # Analytical solution
  6. failure_p = sum(p ** i * (1 - p) for i in range(k))
  7. cycle_time = sum(p ** i * (1 - p) * (i + 1) for i in range(k))
  8. expected_cycles = 1 / (1 - failure_p)
  9. print(cycle_time * expected_cycles + k)
  10.  
  11. # Stochastic verification
  12. import random
  13. trials = 100
  14. average_n = 0
  15. for i in range(trials):
  16.     in_a_row = 0
  17.     n = 0
  18.     while in_a_row != k:
  19.         n += 1
  20.         if random.random() < p:
  21.             in_a_row += 1
  22.         else:
  23.             in_a_row = 0
  24.     average_n += n
  25. print(average_n / trials)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement