mc采样理论的实验验证——python代码实现

9 篇文章 0 订阅
8 篇文章 0 订阅

在这里插入图片描述

import numpy as np
import random
import os
import math
import matplotlib.pyplot as plt

#step1:设置随机数种子,保证实验可以重复进行
seed=11
random.seed(seed)
np.random.seed(seed)
os.environ['PYTHONHASHSEED']=str(seed)

#step2:构造拒绝接受机制_,判断采样值是否有效,并返回
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)

#step3:生成绘图所需相关函数
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_()

#step4:绘采样结果的散点图
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)
#step5:绘采样结果的直方图
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()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值