硬币翻转模拟在python中

时间:2013-11-11 20:24:36

标签: python simulate coin-flipping

我想模拟翻转一枚公平的硬币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()

4 个答案:

答案 0 :(得分:5)

In [53]: [x for x in xrange(1)]
Out[53]: [0]

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

heads / x

引发ZeroDivisionError。


顺便说一下,由于您使用的是matplotlib,因此必须安装NumPy。因此,您可以像这样使用快递coinFlip

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

答案 1 :(得分:3)

嗯,错误说你要除以零。所以你可以分开一条线,它可能就在那里。

尝试改变你的回报(在我看来更有意义):

return heads / size

答案 2 :(得分:0)

您需要将heads除以size

为了避免截断,它应该是

     return heads / float(size)

答案 3 :(得分:0)

当行 返回头/ x 最后一次运行,然后x为0,从而创建除零错误。