In [12]:
%matplotlib inline
import numpy as np
from matplotlib.pyplot import show, plot
import matplotlib.pyplot as plt
In [2]:
# 初始化一个全0的数组来存放剩余资本
# 以参数10000调用binomial函数,进行10000轮硬币赌博游戏
cash = np.zeros(10000)
cash[0] = 1000
outcome = np.random.binomial(9, 0.5, size=len(cash))
In [3]:
# 模拟每一轮抛硬币的结果,更新cash数组
# 打印出outcome的最大最小值,检查输出中是否有异常
for i in xrange(1, len(cash)):
if outcome[i] < 5:
cash[i] = cash[i-1] - 1
elif outcome[i] < 10:
cash[i] = cash[i-1] + 1
else:
raise AssertionError("Unexpected outcome" + outcome)
print outcome.min(), outcome.max()
In [4]:
plot(np.arange(len(cash)), cash)
show
Out[4]:
In [9]:
points = np.zeros(100)
# 第一个参数是罐中普通球的个数
# 第二个参数是倒霉球的个数
# 第三个参数是每次摸球的个数(采样数)
outcomes = np.random.hypergeometric(25, 1, 3, size=len(points))
In [10]:
for i in xrange(len(points)):
if outcomes[i] == 3:
points[i] = points[i-1] + 1
elif outcomes[i] == 2:
points[i] = points[i-1] - 6
else:
print outcomes[i]
In [11]:
plot(points)
show()
In [17]:
# 产生指定数量的随机数
N = 10000
normal_values = np.random.normal(size=N)
# 绘制分布直方图
dummy, bins, dummy = plt.hist(normal_values, np.sqrt(N), normed=True, lw=1)
sigma = 1
mu = 0
plot(bins, 1/(sigma*np.sqrt(2*np.pi)) * np.exp(-(bins-mu)**2 / (2*sigma**2)), lw=2)
show()
In [24]:
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(2,2)
fig = plt.figure(figsize=(10,8))
ax = []
N = 10000
sigma = 1
mu = 0
for a in xrange(2):
for b in xrange(2):
ax.append(fig.add_subplot(gs[a,b]))
normal_values = np.random.normal(size=N)
dummy, bins, dummy = plt.hist(normal_values, np.sqrt(N), normed=True, lw=1)
ax[-1].plot(bins, 1/(sigma*np.sqrt(2*np.pi)) * np.exp(-(bins-mu)**2 / (2*sigma**2)), lw=2)
# 使得子图适应figure的间距
fig.tight_layout()
show()
In [25]:
N = 10000
lognormal_values = np.random.lognormal(size=N)
dummy, bins, dummy = plt.hist(lognormal_values, np.sqrt(N), normed=True, lw=1)
sigma = 1
mu = 0
x = np.linspace(min(bins), max(bins), len(bins))
pdf = np.exp(-(np.log(x)-mu)**2 / (2*sigma**2)) / (x*sigma*np.sqrt(2*np.pi))
plot(x, pdf, lw=3)
show()