Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Thu Oct 17 12:34:11 2019
  5.  
  6. @author: gullholm
  7. """
  8.  
  9. import random
  10. import numpy as np
  11. import matplotlib.pyplot as plt
  12.  
  13. theta = 0
  14. M = 10000
  15.  
  16. #question 2
  17.  
  18. for i in range((M-1)):
  19. U = random.uniform(0,1)
  20. theta += U**2
  21. print(2*theta/M, "question 2")
  22. # Question 3
  23.  
  24. theta = 0
  25. count = 0
  26.  
  27. for i in range((M-1)):
  28. U_1 = random.uniform(0,1)
  29. U_2 = random.uniform(0,1)
  30. if U_2 < (U_1**2):
  31. count += 1
  32.  
  33. print(float(2*count)/float(M),"Question 3")
  34.  
  35. # Question 5
  36.  
  37. theta = 0
  38. N = 1000
  39. theta_2 = 0
  40. crude = [0]*N
  41. HM = [0]*N
  42.  
  43. for j in range((N-1)):
  44. theta_2=0
  45. count = 0
  46. for i in range((M-1)):
  47. U_1 = np.random.uniform(0,1)
  48. U_2 = np.random.uniform(0,1)
  49. theta_2 += U_1**2
  50. if U_2 <= (U_1**2):
  51. count += 1
  52. crude[j+1] = 2*(theta_2/M)
  53. HM[j+1] = 2*(float(count)/M)
  54.  
  55. #crude
  56. print(float(16)/float(45))
  57. print(np.var(crude), "var Crude")
  58. #HM
  59. print(np.sqrt(np.var(HM)), "RMSE HM")
  60.  
  61. # question 6
  62.  
  63. N = 20
  64. sample_size = np.zeros(N)
  65. err_HM = np.zeros(N)
  66. err_crude = np.zeros(N)
  67.  
  68. for n in range(N):
  69. sample_size[n] = 2**(n+1)
  70.  
  71.  
  72. for i in range((N)):
  73. M = 2**(i+1)
  74. theta_2 = 0
  75. count = 0
  76. for m in range((M-1)):
  77. U_1 = np.random.uniform(0,1)
  78. U_2 = np.random.uniform(0,1)
  79. theta_2 += U_1**2
  80. if U_2 <= (U_1**2):
  81. count += 1
  82. err_crude[i] = np.abs((2*(theta_2)/M)-(2/3))
  83. err_HM[i] = np.abs((2*(float(count)/M))-(2/3))
  84.  
  85. plt.loglog(sample_size, (sample_size)**(-0.5))
  86. plt.loglog(sample_size,err_crude)
  87. plt.loglog(sample_size, err_HM)
  88.  
  89.  
  90.  
  91.  
  92. #err_HM = np.zeros(N)
  93. #err_crude = np.zeros(N)
  94.  
  95. #average_1 = 0
  96.  
  97. #for m in range(int(sample_size[N-1])):
  98. # U_1 = np.random.uniform(0,1)
  99. # U_2 = np.random.uniform(0,1)
  100. # theta_2 += U_1**2
  101. # if U_2 <= (U_1**2):
  102. # count += 1
  103. # for n in range(N):
  104. # if m==(int(sample_size[n])-1):
  105. ## err_crude[n] = np.abs(2*(theta_2/sample_size[n])-(2/3))
  106. # err_HM[n] = np.abs(2*(float(count)/sample_size[n])-(2/3))
  107. # theta_2=0
  108. # count=0
  109.  
  110. #print(err_HM)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement