In [53]: [x for x in xrange(1)]
Out[53]: [0]
x
can equal zero. When that happens, (in particular, when coinFlip(1)
is called),
heads / x
raises a ZeroDivisionError.
By the way, since you are using matplotlib
, you must have NumPy
installed. Therefore, you could use express coinFlip
like this:
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()
Or (using @pjs's comment), to see how the proportion of heads changes during a single run of 500 coin flips:
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)
To plot the x-axis on a log scale:
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xscale('log')