Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. import numpy as np
  2. import seaborn as sns
  3. import matplotlib.pyplot as plt
  4.  
  5. class RandomNumberGenerator:
  6. def __init__(self, num):
  7. self.num = num
  8.  
  9. def uniform_sample(self, lb=0, ub=1):
  10. return np.random.uniform(low=lb, high=ub, size=self.num)
  11.  
  12. def normal_sample(self, mu=0, sigma=1):
  13. return np.random.normal(loc=mu, scale=sigma, size=self.num)
  14.  
  15. def laplace_dist(self, mu, b, method='inverse', const=5):
  16.  
  17. def inverse(x, mu, b):
  18. return mu - b*np.sign(x-0.5)*np.log(1-2*abs(x-0.5))
  19.  
  20. def target(x, mu, b):
  21. return 1/(2*b)*np.exp(-abs(x-mu)/b)
  22.  
  23. def proposal_normal(x, mu=0, sigma=1):
  24. return 1/(np.sqrt(2*np.pi)*sigma)*np.exp(-0.5*(x-mu)**2/sigma**2)
  25.  
  26. if method is 'inverse':
  27. u = self.uniform_sample(lb=0, ub=1)
  28. sample = inverse(u, mu, b)
  29. return sample
  30.  
  31. elif method is 'reject':
  32. x = self.normal_sample(mu, b)
  33. gx = proposal_normal(x, 0, 1)
  34. U = self.uniform_sample(lb=0, ub=const*gx)
  35. fx = target(x, mu, b)
  36. sample = x[fx >= U]
  37. return sample
  38.  
  39. if __name__ == '__main__':
  40. rng = RandomNumberGenerator(num=1000000)
  41.  
  42. try_list = [[0, 1, 0.1], [0, 2, 0.1], [0, 4, 0.1], [-5, 4, 0.1], [0, 4, 0.5]]
  43. for item in try_list:
  44. mu, b, const = item[0], item[1], item[2]
  45. sample = rng.laplace_dist(mu, b, method='reject', const=const)
  46.  
  47. sns.distplot(sample)
  48.  
  49. k = ['μ = ' + str(item[0]) + ', b = ' + str(item[1]) + ', const = ' + str(item[2]) for item in try_list]
  50. plt.legend(k, fontsize=20)
  51. plt.title('Random Number Generator', fontsize=20)
  52. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement