python實作:連結如下:個人覺得抛硬币并不是真正的随機事件,和抛硬币時候的各種狀态參量有關系,那麼到底什麼是真正的随機?www.zhihu.com
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
# 抛硬币次數
n_flip = 100
# 硬币彈跳次數
n_jump = 4
# 是否均勻初值
is_uniform = True
# 模拟硬币彈跳
def sim_coin_jump(x):
if is_uniform:
# 均勻初值使用sin(1000x+1)
return np.sin(1000 * x + 1)
else:
# 非均勻初值使用sin(1000πx+1)
return np.sin(1000 * np.pi * x + 1)
# 模拟抛硬币
def sim_flip_coin(x, n):
for i in range(n):
x = sim_coin_jump(x)
return x
# 初值均勻的随機過程:使用等差序列模拟
def uniform(f):
# 均勻間隔
iterable = (1 + (10 ** -10) * n for n in range(f))
return np.fromiter(iterable, float)
# 生成非均勻間隔序列
def uneven(f):
# 非均勻間隔: 随着n變化間隔會變小
iterable = (1 + (10 ** -10) * np.log(n + 1) for n in range(f))
return np.fromiter(iterable, float)
# 統計并畫圖
def stat_and_draw(R):
# 統計正負數個數
pos = np.where(R > 0)
npos = len(R[pos])
neg = np.where(R < 0)
nneg = len(R[neg])
# 計算相鄰數的乘積期望
R1 = R[:-1]
R2 = R[1:]
mean = np.mean(np.multiply(R1, R2))
stat = "Statistics: pos[%d] neg[%d] mean[%s]" % (npos, nneg, mean)
plt.xlabel(stat)
# 标題
title = "Flip coin"
para = "(%s and coin_dump[%d])" % ('uniform' if is_uniform else 'uneven', n_jump)
title += para
plt.title(title)
print(title)
print(stat)
# X軸是抛硬币次數編号
X = np.arange(n_flip)
# plt.plot(X, R)
# 紅圓圈标記點
plt.plot(X, R, marker='.', markeredgecolor='red', markerfacecolor='red')
plt.show()
def flap_coin():
# 生成初值序列
S = uniform(n_flip) if is_uniform else uneven(n_flip)
# 開始模拟抛硬币
R = sim_flip_coin(S, n_jump)
# 統計并畫圖
stat_and_draw(R)
if __name__ == '__main__':
flap_coin()