Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- import seaborn as sns
- import matplotlib.pyplot as plt
- class RandomNumberGenerator:
- def __init__(self, num):
- self.num = num
- def uniform_sample(self, lb=0, ub=1):
- return np.random.uniform(low=lb, high=ub, size=self.num)
- def normal_sample(self, mu=0, sigma=1):
- return np.random.normal(loc=mu, scale=sigma, size=self.num)
- def laplace_dist(self, mu, b, method='inverse', const=5):
- def inverse(x, mu, b):
- return mu - b*np.sign(x-0.5)*np.log(1-2*abs(x-0.5))
- def target(x, mu, b):
- return 1/(2*b)*np.exp(-abs(x-mu)/b)
- def proposal_normal(x, mu=0, sigma=1):
- return 1/(np.sqrt(2*np.pi)*sigma)*np.exp(-0.5*(x-mu)**2/sigma**2)
- if method is 'inverse':
- u = self.uniform_sample(lb=0, ub=1)
- sample = inverse(u, mu, b)
- return sample
- elif method is 'reject':
- x = self.normal_sample(mu, b)
- gx = proposal_normal(x, 0, 1)
- U = self.uniform_sample(lb=0, ub=const*gx)
- fx = target(x, mu, b)
- sample = x[fx >= U]
- return sample
- if __name__ == '__main__':
- rng = RandomNumberGenerator(num=1000000)
- try_list = [[0, 1, 0.1], [0, 2, 0.1], [0, 4, 0.1], [-5, 4, 0.1], [0, 4, 0.5]]
- for item in try_list:
- mu, b, const = item[0], item[1], item[2]
- sample = rng.laplace_dist(mu, b, method='reject', const=const)
- sns.distplot(sample)
- k = ['μ = ' + str(item[0]) + ', b = ' + str(item[1]) + ', const = ' + str(item[2]) for item in try_list]
- plt.legend(k, fontsize=20)
- plt.title('Random Number Generator', fontsize=20)
- plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement