python模拟抛硬币_python模拟抛硬币
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()
總結
以上是生活随笔為你收集整理的python模拟抛硬币_python模拟抛硬币的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一个模拟抛硬币的游戏
- 下一篇: 计算机抛硬币模拟器,GitHub - J