Time for action – gambling with the binomial

The binomial distribution models the number of successes in an integer number of independent trials of an experiment, where the probability of success in each experiment is a fixed number.

Imagine a 17th-century gambling house where you can bet on flipping of pieces of eight. Nine coins are flipped. If less than five are heads, then you lose one piece of eight, otherwise you win one. Let's simulate this, starting with 1000 coins in our possession. We will use the binomial function from the random module for that purpose.

In order to understand the binomial function, go through the following steps:

  1. Initialize an array, which represents the cash balance, to zeros. Call the binomial function with a size of 10000. This represents 10,000 coin flips in our casino.
    cash = np.zeros(10000)
    cash[0] = 1000
    outcome = np.random.binomial(9, 0.5, size=len(cash))
  2. Go through the outcomes of the coin flips and update the cash array. Print the minimum and maximum of outcome, just to make sure we don't have any strange outliers.
    for i in range(1, len(cash)):
        if outcome[i] < 5:
          cash[i] = cash[i - 1] - 1
        elif outcome[i] < 10:
          cash[i] = cash[i - 1] + 1
        else:
          raise AssertionError("Unexpected outcome " + outcome)
    print outcome.min(), outcome.max()

    As expected, the values are between 0 and 9.

    0 9
    
  3. Plot the cash array with Matplotlib.
    plot(np.arange(len(cash)), cash)
    show()

    As you can see in the following screenshot, our cash balance performs a random walk:

    Time for action – gambling with the binomial

What just happened?

We did a random walk experiment using the binomial function from the NumPy random module (see headortail.py).

import numpy as np
from matplotlib.pyplot import plot, show

cash = np.zeros(10000)
cash[0] = 1000
outcome = np.random.binomial(9, 0.5, size=len(cash))

for i in range(1, len(cash)):

    if outcome[i] < 5:
      cash[i] = cash[i - 1] - 1
    elif outcome[i] < 10:
      cash[i] = cash[i - 1] + 1
    else:
      raise AssertionError("Unexpected outcome " + outcome)

print outcome.min(), outcome.max()

plot(np.arange(len(cash)), cash)
show()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset