### 二.求数学期望¶

$$E_{X\sim P(X)}[f(X)]=\int_xp(x)f(x)dx\approx \frac{1}{n}\sum_{i=1}^nf(x_i)$$

### 三.求积分¶

$$\int_xh(x)dx$$

$$\int_xh(x)dx=\int_x\frac{h(x)}{p(x)}\cdot p(x)dx \approx \frac{1}{n}\sum_{i=1}^n\frac{h(x_i)}{p(x_i)}$$

### 四.案例¶

#### 4.1案例一¶

$$p(x)=1\\ x\sim U(0,1)$$

$$\frac{1}{n}\sum_{i=1}^n\frac{h(x_i)}{p(x_i)}=\frac{1}{n}\sum_{i=1}^nh(x_i)=\frac{1}{n}\sum_{i=1}^ne^{-x_i^2/2}$$

#### 均匀分布采样的简单实现：线性同余¶

$$x_{n+1}=(ax_n+c) \% m\\ y_{n+1}=x_{n+1}/m$$

(1) $c$和$m$互质；

(2) $m$的所有质因子的积能整除$a-1$；

(3) 若$m$是4的倍数，则$a-1$也是；

(4) $a,c,x_0$（初值，一般即种子）都比$m$小；

(5) $a,c$是正整数。

In [1]:
# a,c,m可以自己随意设置，只要能满足上面的约束
import numpy as np
def random(size=None,a=9,c=3,m=1024,seed=0):
rst=[]
v=seed
for _ in range(0,size):
v=(a*v+c)%m
rst.append(v/m)
return np.asarray(rst)


In [2]:
import matplotlib.pyplot as plt
%matplotlib inline
plt.figure(figsize = (18,4))
plt.subplot(1,3,1)
plt.hist(random(100))
plt.subplot(1,3,2)
plt.hist(random(500))
plt.subplot(1,3,3)
plt.hist(random(2000))
plt.show()


In [3]:
def func1(x):
return np.mean(np.exp(-0.5*x*x))

In [4]:
func1(random(10)),func1(random(100)),func1(random(500)),func1(random(1000)),func1(random(5000)),func1(random(10000))

Out[4]:
(0.9035390412404333,
0.8724010595453379,
0.8636744903733047,
0.8557742330163529,
0.8559914695948042,
0.8560096265779689)

#### 4.2 案例二¶

$$p(x)=\frac{1}{\sqrt{2\pi}}exp(\frac{-x^2}{2})$$

$$\frac{1}{n}\sum_{i=1}^n\frac{h(x_i)}{p(x_i)}=\frac{1}{n}\sum_{i=1}^nx_i$$

#### 标准正态分布采样：Box Muller¶

$$X=\sqrt{-2lnU_1}cos(2\pi U_2)\\ Y=\sqrt{-2lnU_1}sin(2\pi U_2)$$

$X,Y$相互独立，且均服从标准正态分布，下面简单实现一下

In [5]:
def randn(size=None):
u1=random(size,seed=0)
u2=random(size,seed=1)
return np.sqrt(-2*np.log(u1+1e-12))*np.cos(2*np.pi*u2)

In [6]:
plt.figure(figsize = (18,4))
plt.subplot(1,3,1)
plt.hist(randn(100))
plt.subplot(1,3,2)
plt.hist(randn(500))
plt.subplot(1,3,3)
plt.hist(randn(2000))
plt.show()


In [7]:
np.mean(randn(100)),np.mean(randn(500)),np.mean(randn(1000)),np.mean(randn(2000)),np.mean(randn(5000)),np.mean(randn(10000))

Out[7]:
(-0.18047523195450427,
-0.067597124077273,
-0.004227634117120701,
0.0027034258396782017,
0.005011583413871283,
0.004176713840559121)

### 五.分析¶

PS：另外，再补充一下，采样的分布是已知的~~~

In [ ]: