fork download
  1. import random
  2. import statistics
  3.  
  4. def reflected_walk_hits(num_steps=100_000, trials=40):
  5. counts = []
  6. for _ in range(trials):
  7. x = 0
  8. hits = 1 # start at 0
  9. for _ in range(num_steps):
  10. step = random.choice([-1, 1])
  11. if x == 0 and step == -1:
  12. x = 0
  13. else:
  14. x += step
  15. if x == 0:
  16. hits += 1
  17. counts.append(hits)
  18. return statistics.mean(counts), statistics.stdev(counts)
  19.  
  20. mean_hits, stdev_hits = reflected_walk_hits()
  21. print(f"Average hits to 0: {mean_hits:.2f} ± {stdev_hits:.2f}")
Success #stdin #stdout 2.98s 16576KB
stdin
Standard input is empty
stdout
Average hits to 0: 582.08 ± 401.03