# 以指数分布为例,进行接受拒绝采样
# 指数分布PDF = e^(-x) x >= 0
# 我们选取x的范围为0-5,首先在x上随机生成100000个均匀分布的随机数,计算f(xi)
# 然后在指数分布最大值与最小值之间生成100000个均匀分布的随机数yi
# 比较f(xi)与yi,如果f(xi) <= yi则接受,否则不接受
import numpy as np
from matplotlib import pyplot as plt
def accept_reject_sampling():
x = np.random.uniform(low=0, high=5, size=100000)
x = np.power(np.e, -x)
y = np.random.uniform(low=0, high=1, size=100000)
return [i[0] for i in zip(x, y) if i[0] <= i[1]]
def plot(x):
plt.hist(x, bins=30, color='skyblue', alpha=0.8)
plt.show()
if __name__ == '__main__':
plot(accept_reject_sampling())
标签:采样,yi,抽样,xi,均匀分布,100000,指数分布,拒绝接受
From: https://www.cnblogs.com/crazypigf/p/18263916