p1.py 976 B

123456789101112131415161718192021222324252627282930313233
  1. #!/usr/bin/env python3
  2. """ LPC stats HW2, Problem 1
  3. Author: Caleb Fangmeier
  4. Created: Sep. 25, 2017
  5. """
  6. from numpy import sum, sqrt
  7. from numpy.random import exponential, poisson
  8. def find_relative_frequency(n_experiments, b):
  9. # First get the mean counts for each experiment
  10. a = exponential(scale=b, size=n_experiments)
  11. # Since this is a counting experiment, sample from a Poisson distribution with the
  12. # previously generated means.
  13. x = poisson(lam=a)
  14. # Finally, count for how many experiments the a lies in
  15. # the range [x-sqrt(x), x+sqrt(x)]
  16. n_pass = sum((x - sqrt(x) < a) & (a < x + sqrt(x)))
  17. relative_frequency = n_pass / n_experiments
  18. # and print the results
  19. print(f"For b={b}, {n_pass}/{n_experiments} passed, R={relative_frequency*100:4.2f}%")
  20. find_relative_frequency(10000, 5)
  21. find_relative_frequency(10000, 10)
  22. # Example output
  23. # > For b=5, 6012/10000 passed, R=60.12%
  24. # > For b=10, 6372/10000 passed, R=63.72%