Learn

We can use the binom.cdf() method from the scipy.stats library to calculate the cumulative distribution function. This method takes 3 values:

  • x: the value of interest, looking for the probability of this value or less
  • n: the sample size
  • p: the probability of success

Calculating the probability of observing 6 or fewer heads from 10 fair coin flips (0 to 6 heads) mathematically looks like the following:

P(6orfewerheads)=P(0to6heads)P(6\; or\; fewer\; heads) = P(0\; to\; 6\; heads)

In python, we use the following code:

import scipy.stats as stats print(stats.binom.cdf(6, 10, 0.5))

Output:

0.828125

Calculating the probability of observing between 4 and 8 heads from 10 fair coin flips can be thought of as taking the difference of the value of the cumulative distribution function at 8 from the cumulative distribution function at 3:

P(4to8Heads)=P(0to8Heads)P(0to3Heads)P(4\;to\;8\;Heads) = P(0\;to\;8\;Heads) - P(0\;to\;3\;Heads)

In python, we use the following code:

import scipy.stats as stats print(stats.binom.cdf(8, 10, 0.5) - stats.binom.cdf(3, 10, 0.5))

Output:

# 0.81738

To calculate the probability of observing more than 6 heads from 10 fair coin flips we subtract the value of the cumulative distribution function at 6 from 1. Mathematically, this looks like the following:

P(morethan6heads)=1P(6orfewerheads)P(more\; than\; 6\; heads) = 1 - P(6\; or\; fewer\; heads)

Note that “more than 6 heads” does not include 6. In python, we would calculate this probability using the following code:

import scipy.stats as stats print(1 - stats.binom.cdf(6, 10, 0.5))

Output:

# 0.171875

Instructions

1.

Uncomment and assign the variable prob_1 to the probability of observing 3 or fewer heads from 10 fair coin flips using the cumulative distribution function. Then print prob_1.

Use the binom.cdf() method from the scipy.stats library.

2.

Uncomment and run the given code for the probability mass function below the following comment:

# compare to pmf code

See how the calculation using the CDF is simpler?

3.

Uncomment prob_2 and assign the variable to be the probability of observing more than 5 heads from 10 fair coin flips. Then print prob_2.

Use the binom.cdf() method from the scipy.stats library.

4.

Assign the object prob_3 the probability of observing between 2 and 5 heads from 10 fair coin flips. Then print prob_3

5.

Uncomment and run the code for the probability mass function at the bottom of script.py. See how this calculation is simpler?

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?