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
flip()
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)
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
nflips()
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)