Skip to content

Commit a684de9

Browse files
committed
update local
1 parent b0394c5 commit a684de9

2 files changed

Lines changed: 102 additions & 0 deletions

File tree

code_in_notes/MCMC_independent.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#!/usr/bin/python3
2+
## file: MonteCarlo.py
3+
4+
import numpy as np
5+
from numpy import random as nprd
6+
7+
##设定参数
8+
M =10000
9+
pai_cons=90*np.sqrt(2)/(2*np.pi)
10+
pai=lambda x: pai_cons* \
11+
np.exp(-90*(x[0]-0.5)**2-45*(x[1]+0.1)**2)
12+
domain=lambda x:(x[0]>=-1)*(x[1]>=-1)*(x[0]<=1)*(x[1]<=1)
13+
q=lambda y: 1/(2*np.pi)*np.exp(-1*y[0]**2/2-y[1]**2/2)
14+
h=lambda x: domain(x)
15+
h2=lambda x: np.sin(x[0])**2+np.log(abs(1+x[1]))
16+
#从均匀分布中采样
17+
def sample_q():
18+
return (nprd.normal(),nprd.normal())
19+
20+
21+
##独立的MCMC算法,输入:
22+
## N_samples : 抽样次数
23+
## pai(x) : 目标密度函数
24+
## q(y) : 工具密度函数
25+
## q_sampler : 给定x,从q中抽样的函数
26+
## x0 : 初始值
27+
def MH_independent(N_samples, pai, q, q_sampler, x0):
28+
X=[]
29+
x=x0
30+
for i in range(N_samples):
31+
y=q_sampler()
32+
rho=min(1,pai(y)*q(x)/(pai(x)*q(y)))
33+
if nprd.uniform()<rho:
34+
X.append(y)
35+
x=y
36+
else:
37+
X.append(x)
38+
return X
39+
40+
## 计算积分
41+
x=MH_independent(M, pai, q, sample_q, (0,0))
42+
## 第一个积分
43+
H=list(map(h,x))
44+
## 取h后面80%的样本
45+
subH=H[int(M*0.2):]
46+
integral=np.pi/(90*np.sqrt(2))*np.mean(subH)
47+
print("Intgral1=",integral)
48+
## 第二个积分
49+
H2=list(map(h2,x))
50+
subH2=H2[int(M*0.2):]
51+
integral2=np.pi/(90*np.sqrt(2))*np.mean(subH2)
52+
print("Intgral2=",integral2)

code_in_notes/MCMC_random_walk.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#!/usr/bin/python3
2+
## file: MonteCarlo.py
3+
4+
import numpy as np
5+
from numpy import random as nprd
6+
7+
##设定参数
8+
M =10000
9+
pai_cons=90*np.sqrt(2)/(2*np.pi)
10+
pai=lambda x: pai_cons* \
11+
np.exp(-90*(x[0]-0.5)**2-45*(x[1]+0.1)**2)
12+
domain=lambda x:(x[0]>=-1)*(x[1]>=-1)*(x[0]<=1)*(x[1]<=1)
13+
h=lambda x: domain(x)
14+
h2=lambda x: np.sin(x[0])**2+np.log(abs(1+x[1]))
15+
#从均匀分布中采样
16+
def sample_q(x):
17+
return (x[0]+0.3*nprd.normal(),x[1]+0.3*nprd.normal())
18+
19+
20+
##独立的MCMC算法,输入:
21+
## N_samples : 抽样次数
22+
## pai(x) : 目标密度函数
23+
## q_sampler(x): 给定x,从q中抽样的函数
24+
## x0 : 初始值
25+
def MH_RW(N_samples, pai, q_sampler, x0):
26+
X=[]
27+
x=x0
28+
for i in range(N_samples):
29+
y=q_sampler(x)
30+
rho=min(1,pai(y)/pai(x))
31+
if nprd.uniform()<rho:
32+
X.append(y)
33+
x=y
34+
else:
35+
X.append(x)
36+
return X
37+
38+
## 计算积分
39+
x=MH_RW(M, pai, sample_q, (0,0))
40+
## 第一个积分
41+
H=list(map(h,x))
42+
## 取h后面80%的样本
43+
subH=H[int(M*0.2):]
44+
integral=np.pi/(90*np.sqrt(2))*np.mean(subH)
45+
print("Intgral1=",integral)
46+
## 第二个积分
47+
H2=list(map(h2,x))
48+
subH2=H2[int(M*0.2):]
49+
integral2=np.pi/(90*np.sqrt(2))*np.mean(subH2)
50+
print("Intgral2=",integral2)

0 commit comments

Comments
 (0)