Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. import math
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. import random
  5. import scipy.stats as stats
  6.  
  7. die_e = 3.5 # expected value of an ordinary six-sided die
  8. die_var = 17.5/6 # variance of an ordinary six-sided die
  9. die_sigma = math.sqrt(die_var)
  10.  
  11. def create_statistics(repetitions, casts):
  12. clt_sum_frequencies = np.zeros(6 * casts + 1, dtype = int)
  13. total_sum = 0
  14. for repetition in range(0, repetitions):
  15. sum = 0
  16. for cast in range(0, casts):
  17. die_number = random.randint(1, 6)
  18. sum = sum + die_number
  19. clt_sum_frequencies[sum] += 1
  20. total_sum += sum
  21. return clt_sum_frequencies / repetitions
  22.  
  23. def plot_clt_chart(sum_frequencies, shift, scale, casts, ax, title):
  24. sums = np.linspace((0 - shift) / scale, (6 * casts - shift) / scale, len(sum_frequencies))
  25. width = sums[1] - sums[0]
  26. sum_densities = sum_frequencies / width
  27. mu = (casts * die_e - shift) / scale
  28. sigma = die_sigma * math.sqrt(casts) / scale
  29. normal_densities = [stats.norm.pdf(x, mu, sigma) for x in sums]
  30. plot_chart(sums, sum_densities, normal_densities, width, ax, title)
  31.  
  32. def plot_chart(x_values, y_values, y_comparison_values, width, ax, title):
  33. x_values_odd = x_values[np.mod(np.arange(x_values.size), 2) != 0]
  34. y_values_odd = y_values[np.mod(np.arange(x_values.size), 2) != 0]
  35. x_values_even = x_values[np.mod(np.arange(y_values.size), 2) == 0]
  36. y_values_even = y_values[np.mod(np.arange(y_values.size), 2) == 0]
  37. ax.bar(x_values_odd, y_values_odd, width=width, align='center', color='blue')
  38. ax.bar(x_values_even, y_values_even, width=width, align='center', color='palegreen')
  39. ax.plot(x_values, y_comparison_values, color='r')
  40. ax.set_title(title)
  41.  
  42. fig, ax = plt.subplots(2, sharex=True, sharey=True, figsize=(5, 10))
  43. plt.xlim(-0.5, 0.5)
  44. row = 0
  45. for casts in [100, 1000]:
  46. for repetitions in [10000]:
  47. title = f"{repetitions} times averages of {casts} random numbers"
  48. clt_sum_frequencies = create_statistics(repetitions, casts)
  49. plot_clt_chart(clt_sum_frequencies, die_e * casts, casts, casts, ax[row], title)
  50. row += 1
  51. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement