Q1

In this question, you'll work with parametric distributions.

Part A

Recall from earlier lectures when we discussed flipping a coin. There is an actual distribution for this: the Bernoulli distribution. It measures probability of success or failure, 1 or 0. The only parameter to this distribution is $p$, or the probability of success (e.g., flipping heads).

Write a function which

  • is named flip()
  • takes one argument $p$, a float between 0 and 1, indicating the probability of Heads
  • returns 1 on success, 0 otherwise.

The only outside function you can use inside flip is numpy.random.random() with no arguments. It returns a random floating-point number between 0 and 1, which you'll essentially use as a coin flip.


In [ ]:


In [ ]:
np.testing.assert_allclose(flip(1.0), 1.0, rtol = 0.01)

In [ ]:
np.testing.assert_allclose(flip(0.0), 0.0, rtol = 0.01)

In [ ]:
results = np.zeros(10000, dtype = np.int)
for i in range(10000):
    results[i] = flip(0.5)
np.testing.assert_allclose(results.mean(), 0.5, rtol = 0.1)

Part B

A generalization of the Bernoulli distribution is the Binomial distribution, which also has a probability of success $p$, but also has a number of experiments $n$. Using the coin-flip analogy, $n$ is the number of times you want to flip the coin and record its result.

Write a function which

  • is named nflips()
  • takes two arguments: $p$, the probability of Heads (same as Part A), and $n$, the number of times to flip the coin
  • returns an array of $n$ 1s and 0s, the outcome of each coin flip

Hint: you can make use of your flip() method from earlier.


In [ ]:


In [ ]:
import numpy as np
assert (np.array(nflips(1000, 1.0)) == 1).all()

In [ ]:
assert (np.array(nflips(1000, 0.0)) == 0).all()

In [ ]:
results = np.array(nflips(10000, 0.5))
np.testing.assert_allclose(results.mean(), 0.5, rtol = 0.1)

Part C

I use your nflips function from Part B, and set n = 1000. Let $X$ be the number of heads from Part B, and $Y$ the number of tails. Are $X$ and $Y$ dependent or independent random variables? Why or why not?