import matplotlib.pyplot as plt

%load_ext lab_black

6. Two-headed Coin*#

From Unit 3 - twoheaded.m.

Associated lecture videos: Unit 3 lesson 6.


This is a pretty simple one. I’m sure no one needed help redoing this in Python, I’m just including it for the sake of completeness!

Out of N coins only one has two heads. A coin is selected at random from the pile and flipped k times. Heads appears k times in a row. What is the probability that the coin with two heads was selected?

N = 1000000
flips = 40


def prob(k, N):
    """
    Calculate probability that we've selected a two-headed coin.

    k int: number of flips that come up as heads (consecutively)
    N int: number of coins we selected from.

    returns: probability at k flips in a row
    """
    return 2**k / (2**k + N - 1)


# create a list of probabilities for different values of k
probabilities = [prob(k, N) for k in range(flips)]

# plot using matplotlib
plt.plot(probabilities)
plt.xlabel("Flips")
plt.ylabel("Probability")
plt.suptitle("Probability that selected coin is two-headed")
plt.title("(given k flips in a row landing on heads)")
plt.show()
../_images/f993643d17400a118aab32a88f7177e38b6fa781e630244cf31de2c5cef9c06e.png
%load_ext watermark
%watermark -n -u -v -iv
Last updated: Sat Mar 18 2023

Python implementation: CPython
Python version       : 3.11.0
IPython version      : 8.9.0

matplotlib: 3.6.3