# Roulette Wheel for sampling user defined pdf

Following is the pdf from which I want to sample so, I used roulette wheel sampling

Code to generate pdf

pdf=np.array([1,5,1,10,1,5,1])
pdf=pdf/np.sum(pdf)
x=np.arange(0,np.size(pdf),1)
plt.bar(x,pdf)


Code to generate cdf

def pdf2cdf(tpdf):
tcdf=np.zeros_like(tpdf)
itr=0
for i in tpdf:
tcdf[itr]=tcdf[itr-1]+tpdf[itr]
itr=itr+1
return tcdf
cdf=pdf2cdf(pdf)
plt.bar(x,cdf)


CDF of the given pdf

Code to sample from pdf using roulette wheel

lst=[]
uni=[]
for j in range(100000):
tmp=np.random.uniform(0,1)
uni.append(tmp)
tmp2=np.argsort(np.abs(cdf-tmp))
lst.append(tmp2[0])


histogram of uni

histogram of samples drawn

I don't understand what's going wrong. The pdf from which I sampled(first plot) and the histogram of samples (last plot) are not the same. Can anybody please suggest the correction of any mistake I made above.

Thanks @jsk

for k in range(np.size(cdf)):
if cdf[k]>tmp:
break
tmp2=k

plt.hist(lst,bins=range(0,8), align='left', rwidth=1, normed=True)


The problem is with the command

np.argsort(np.abs(cdf-tmp)).


The command will find which element of the cdf is closest to tmp, regardless of whether or not tmp is greater than cdf.

$$P(0) = 1/24 \approx 0.04167$$
$$P(1) = 5/24 \approx 0.2083$$
so $$CDF(1) = 6/24 = 0.25$$.