In [1]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import *
In [2]:
outcomes=np.arange(1,5)
#probabilities corresponding to the target distribution
dist_target=np.array([0.3,0.1,0.2,0.4])
#probabilities corresponding to the proposal distribution
dist_proposal=np.repeat(0.25,4)
In [3]:
#compute c value
c=np.max(dist_target/dist_proposal)
dist_target/dist_proposal/c
Out[3]:
array([0.75, 0.25, 0.5 , 1. ])
In [5]:
#rejection sampling
a=1
b=4
def sampling():
#generate a proposal a+int((b-a+1)*u)
u=np.random.rand()
x=a+int((b-a+1)*u)
#check if accepted
while np.random.rand()>=dist_target[x-1]/dist_proposal[x-1]/c :
u=np.random.rand()
x=a+int((b-a+1)*u)
return x
sampling()
Out[5]:
4
In [0]:
In [0]:
In [0]:
In [0]:
In [0]:
In [0]: