中心极限定理生成正态分布

In [2]:
import matplotlib.pyplot as plt
import numpy as np

#  计算SampleSize次n个相互独立同分布的随机变量之和
def getNormal(SampleSize,n):
    result = []
    for i in range(SampleSize):
        # 利用中心极限定理,[0,1)均匀分布期望为0.5,方差为1/12
        iid = (np.mean(np.random.uniform(0,1,n))-0.5)*np.sqrt(12*n)
        result.append(iid)
    return result

# 生成10000个数,观察它们的分布情况
SampleSize = 1000
# 观察n选不同值时,对最终结果的影响
N = [1,2,10,1000] 
fig, axes = plt.subplots(2, 2, figsize=(8, 8))
aslist = axes.ravel()

for index,n in enumerate(N):
    normal = getNormal(SampleSize, n)
    aslist[index].hist(normal,np.linspace(-4,4,81),facecolor="green",label="n={0}".format(n))
    aslist[index].legend()
plt.show()

Box–Muller算法生成正态分布

In [3]:
import matplotlib.pyplot as plt
import numpy as np

def getNormal(SampleSize):
    iid = np.random.uniform(0,1,SampleSize)
    normal1 = np.cos(2*np.pi*iid[0:int(SampleSize/2-1)])*np.sqrt(-2*np.log(iid[int(SampleSize/2):SampleSize-1]))
    normal2 = np.sin(2*np.pi*iid[0:int(SampleSize/2-1)])*np.sqrt(-2*np.log(iid[int(SampleSize/2):SampleSize-1]))
    return np.hstack((normal1,normal2))

# 生成10000000个数,观察它们的分布情况
SampleSize = 10000000
normal = getNormal(SampleSize)
plt.hist(normal,np.linspace(-4,4,81),facecolor="green")
plt.show()
posted @ 2019-01-09 14:53:14
评论加载中...

发表评论