import numpy as np
import random
import os
import math
import matplotlib.pyplot as plt
seed=11
random.seed(seed)
np.random.seed(seed)
os.environ['PYTHONHASHSEED']=str(seed)
def acceptreject_():
sum_=(math.pow(1-0.4,5)-math.pow(0-0.4,5))/5
max_fx=math.pow(1-0.4,4)/sum_
samplesinx=[]
samplesoutx=[]
samplesiny=[]
samplesouty=[]
for i in range(2000):
x=random.uniform(0,1)
y=random.uniform(0,max_fx)
if y<=math.pow(x-0.4,4)/sum_:
samplesinx.append(x)
samplesiny.append(y)
else:
samplesoutx.append(x)
samplesouty.append(y)
return (samplesinx,samplesiny,samplesoutx,samplesouty)
sum_=(math.pow(1-0.4,5)-math.pow(0-0.4,5))/5
max_fx=math.pow(1-0.4,4)/sum_
x=np.linspace(0,1,100)
max_fx_=[max_fx for i in x]
fx=[math.pow(xi-0.4,4)/sum_ for xi in x]
samplesinx,samplesiny,samplesoutx,samplesouty=acceptreject_()
plt.figure(figsize=(16,4))
plt.subplot(1,2,1)
plt.plot(x,fx,color='green',label='f(x)=(x-0.4)^4/f_0_1(x-0.4)^4')
plt.plot(x,max_fx_,'--',label='maxf(x)')
plt.scatter(samplesinx,samplesiny,c='red', s=2,label='samplesin')
plt.scatter(samplesoutx,samplesouty,c='blue', s=2,label='samplesout')
plt.legend(loc="upper left")
plt.xlim(0,1)
plt.ylim(0,8)
plt.subplot(1,2,2)
plt.plot(x,fx,color='green',label='f(x)=(x-0.4)^4/f_0_1(x-0.4)^4')
plt.plot(x,max_fx_,'--',label='maxf(x)')
plt.hist(samples,bins=100,density=True,color='yellow',label="the distribution of samples")
plt.legend(loc="upper left")
plt.show()