Advertisement
Guest User

Untitled

a guest
Jun 27th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. import random
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. import time
  5. import scipy.stats as ss
  6.  
  7. a=0 # xmin
  8. b=1 # xmax
  9.  
  10. m=3/2 # ymax
  11. variables = [] #list for variables
  12.  
  13. def f(x):
  14. return 3/2 * (1 - x**2) #probability density function
  15.  
  16. reject = 0 # number of rejections
  17. start = time.time()
  18. while len(variables) < 100000: #I want to generate 100 000 variables
  19. u1 = random.uniform(a,b)
  20. u2 = random.uniform(0,m)
  21.  
  22. if u2 <= f(u1):
  23. variables.append(u1)
  24. else:
  25. reject +=1
  26. end = time.time()
  27.  
  28. print("Time: ", end-start)
  29. print("Rejection: ", reject)
  30. x = np.linspace(a,b,1000)
  31. plt.hist(variables,50, density=1)
  32. plt.plot(x, f(x))
  33. plt.show()
  34.  
  35. ss.probplot(variables, plot=plt)
  36. plt.show()
  37.  
  38. import numpy as np
  39. import scipy.stats as ss
  40. import matplotlib.pyplot as plt
  41. import time
  42.  
  43. a = 0. # xmin
  44. b = 1. # xmax
  45.  
  46. m = 3.0/2.0 # ymax
  47.  
  48. def f(x):
  49. return 1.5 * (1.0 - x*x) # probability density function
  50.  
  51. start = time.time()
  52.  
  53. N = 100000
  54. u1 = np.random.uniform(a, b, N)
  55. u2 = np.random.uniform(0.0, m, N)
  56.  
  57. negs = np.empty(N)
  58. negs.fill(-1)
  59. variables = np.where(u2 <= f(u1), u1, negs) # accepted samples are positive or 0, rejected are -1
  60.  
  61. end = time.time()
  62.  
  63. accept = np.extract(variables>=0.0, variables)
  64. reject = N - len(accept)
  65.  
  66. print("Time: ", end-start)
  67. print("Rejection: ", reject)
  68.  
  69. x = np.linspace(a, b, 1000)
  70. plt.hist(accept, 50, density=True)
  71. plt.plot(x, f(x))
  72. plt.show()
  73.  
  74. ss.probplot(accept, plot=plt) # against normal distribution
  75. plt.show()
  76.  
  77. class my_pdf(ss.rv_continuous):
  78. def _pdf(self, x):
  79. return 1.5 * (1.0 - x*x)
  80.  
  81. ss.probplot(accept, dist=my_pdf(a=a, b=b, name='my_pdf'), plot=plt)
  82.  
  83. n_before_accept_reject = 150000
  84. u1 = np.random.uniform(a, b, size=n_before_accept_reject)
  85. u2 = np.random.uniform(0, m, size=n_before_accept_reject)
  86. variables = u1[u2 <= f(u1)]
  87. reject = n_before_accept_reject - len(variables)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement