python中的硬币翻转模拟

2024-05-23 19:18:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想模拟抛一枚硬币500次。然后,我必须创建一个图表来显示在x轴上有倒装号码的硬币和在y轴上有倒装号码的硬币时头部的运行比例。我编写了Python代码,得到了以下错误:

Traceback (most recent call last):
File "E:\ProgramsPython\My\bayes\Coin Flip.py", line 22, in <module>
ylist = [coinFlip(x) for x in xlist]
File "E:\ProgramsPython\My\bayes\Coin Flip.py", line 16, in coinFlip
return heads / x
ZeroDivisionError: integer division or modulo by zero

我做错了什么?

# -*- coding: cp1251 -*-
import random
import pylab
from matplotlib import mlab
def coinFlip(size):
    heads = 0
    tails = 0

    for x in xrange(size):
        flip = random.randint(0,1)
        if flip == 1: heads += 1
        else: tails += 1



    return heads / x

xmin = 1
xmax = 500
dx = 1
xlist = mlab.frange (xmin, xmax, dx)
ylist = [coinFlip(x) for x in xlist]
pylab.plot(xlist, ylist)
pylab.show()

Tags: inimportformy硬币号码filecoin
3条回答
import numpy as np
from matplotlib import pyplot as plt

flips = np.random.binomial(1, 0.5, 500) # flip 1 coin with 0.5 prob of heads 500 times
heads_so_far = flips.cumsum() * 1.0 #lets use float to avoid truncations later
heads_to_count = [heads_so_far[i-1]/i for i in range(1,len(flips)+1)]
x = range(1,len(flips)+1)
plt.plot(x,heads_to_count)
plt.show()
In [53]: [x for x in xrange(1)]
Out[53]: [0]

x可以等于零。当这种情况发生时(特别是当coinFlip(1)被调用时)

heads / x

引发零分区错误。


顺便说一下,因为您使用的是matplotlib,所以必须安装NumPy。因此,您可以像这样使用expresscoinFlip

import matplotlib.pyplot as plt
import numpy as np

def coinFlip(size):
    flips = np.random.randint(0, 2, size=size)
    return flips.mean()
coinFlip = np.frompyfunc(coinFlip, 1, 1)

xmin, xmax, dx = 1, 500, 1
x = np.arange(xmin, xmax, dx)
y = coinFlip(x)
plt.plot(x, y)
plt.show()

enter image description here


或者(使用@pjs的注释),查看在一次500个硬币的投掷中头部的比例是如何变化的:

def coinFlip(size):
    xmin, xmax, dx = 1, size, 1
    x = np.arange(xmin, xmax, dx)
    flips = np.random.randint(0, 2, size=size)
    return x, [flips[:i].mean() for i in x]

x, y = coinFlip(500)
plt.plot(x, y)

enter image description here


要在对数刻度上绘制x轴:

fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xscale('log')

enter image description here

嗯,错误是说你除以零。所以有一条线,可能在那里。

试着把你的回报改成这个(在我看来还是更有意义的):

return heads / size

相关问题 更多 >