Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Section 2.4 — Continuous random variables

This notebook contains all the code examples from Section 2.4 Continuous random variables of the No Bullshit Guide to Statistics.

Notebook setup

We’ll start by importing the Python modules we’ll need for this notebook.


[notice] A new release of pip is available: 26.0.1 -> 26.1.2
[notice] To update, run: pip install --upgrade pip
Note: you may need to restart the kernel to use updated packages.

Definitions

Random variables

  • random variable XX: a quantity that can take on different values.

  • sample space X\mathcal{X}: describes the set of all possible outcomes of the random variable XX.

  • outcome: a particular value {X=x}\{X = x\} that can occur as a result of observing the random variable XX.

  • event subset of the sample space {a≤X≤b}\{a \leq X \leq b\} that can occur as a result of observing the random variable XX.

  • fXf_X: the probability density function (PDF) is a function that assigns probabilities to the different outcome in the sample space of a random variable. The probability distribution function of the random variable XX is a function of the form fX:X→Rf_X: \mathcal{X} \to \mathbb{R}.

Calculus prerequisites

Functions

In Python, we define functions using the def keyword. For example, the code cell below defines the function g(x)=12xg(x)=\frac{1}{2}x, then evaluate it on the input x=5x=5.

2.5
<Figure size 750x230 with 1 Axes>

Integrals

The area under the graph of the function gg, between x=2x=2 and x=6x=6 is calculated using the following integral:

Ag(2,6)=∫x=2x=6g(x) dx=8.A_g(2,6) = \int_{x=2}^{x=6} g(x)\,dx = 8.
<Figure size 750x230 with 1 Axes>

The function quad from the scipy.integrate module allows us to compute the integral of any function.

(8.0, 8.881784197001252e-14)

The function quad returns two numbers as output: (Ag(2,6),ϵ)\big(A_g(2,6),\epsilon\big). The first number is the value of the area we’re interested in. The second number, ϵ\epsilon, indicates the accuracy of the procedure used to calculate the area, which is ϵ=8.88×10−14\epsilon=8.88\times 10^{-14} in this case. We’re usually only interested in the value of the area, so we select the first element of the output, as shown below.

8.0

We used [0] to select the first value of the output, which is the value of the area Ag(2,6)=8A_g(2,6)=8.

Integral functions

The integral function F0(b)F_0(b) corresponds to the area calculation with a variable upper limit of integration Af(0,b)A_f(0,b). It is defined as:

F0(b)=Af(0,b)=∫x=0x=b ⁣f(x) dx.F_0(b) = A_f(0,b) = \int_{x=0}^{x=b} \! f(x)\,dx.

The integral function of the function g(x)=12xg(x)=\frac{1}{2}x is G0(b)=Ag(0,b)=14x2G_0(b) = A_g(0,b) = \frac{1}{4}x^2.

<Figure size 750x230 with 1 Axes>
<Figure size 800x200 with 5 Axes>

Computer models for random variables

Consider the computer model rvX for the random variable X∼M(θ)X \sim \mathcal{M}(\theta).

We saw previously in Section 2.1

TODO: compare and sync with text with Section 2.1

  • <model>: the family of probability distributions

  • <params>: parameters of the model—specific value of the control knobs we choose in the general family of distributions to create a particular distribution

  • <model>(<params>): a particular instance of probability model created by choosing a model family <model> and the model parameters <params>.

    • example 1: uniform family of distribution U(α,β)\mathcal{U}(\alpha,\beta) with parameters α\alpha and β\beta.

    • example 2: normal family of distribution N(μ,σ)\mathcal{N}(\mu,\sigma) with parameters μ\mu and σ\sigma.

  • ∼\sim: math shorthand symbol that stands for “is distributed according to.” For example X∼model(θ)X \sim \texttt{model}(\theta) means the random variable XX is distributed according to model instance model\texttt{model} and parameters θ\theta.

Summary of methods

TODO: import table of methods

Examples

  • The continuous uniform family of distribution U(α,β)\mathcal{U}(\alpha,\beta), which assigns equal probabilities to all outcomes in the interval [α,β][\alpha,\beta]. To create a computer model for a continuous uniform distribution U(α,β)\mathcal{U}(\alpha,\beta), use the code uniform(loc=alpha,scale=beta-alpha).

  • Normal distribution N(μ,σ)\mathcal{N}(\mu,\sigma) ...

Example 1: uniform distribution

The uniform distribution U∼U(0,1)U \sim \mathcal{U}(0,1) is described by the following probability density function:

pU(u)={1for 0≤u≤1,0for u<0 or u>1.p_U(u) = \begin{cases} 1 & \mathrm{for}\ 0 \le u \le 1, \\ 0 & \mathrm{for}\ u<0\ \mathrm{or}\ u>1. \end{cases}

For a uniform distribution U(0,1)\mathcal{U}(0,1), each uu between 0 and 1 is equally likely to occur, and values of uu outside this range have zero probability of occurring.

Plotting the uniform probability density function

<Figure size 750x230 with 1 Axes>

Alternatively, we can use the helper function plot_pdf from the ministats library to plot the PDF fUf_U.


[notice] A new release of pip is available: 26.0.1 -> 26.1.2
[notice] To update, run: pip install --upgrade pip
Note: you may need to restart the kernel to use updated packages.
<Figure size 750x230 with 1 Axes>

We can pass the options a and b to the function plot_pdf to highlight the area that corresponds to the probability of the event {a≤U≤b}\{ \texttt{a} \leq U \leq \texttt{b} \}.

<Figure size 750x230 with 1 Axes>

Calculating the probability of an event

TODO: math

0.3

The total area under the graph of fUf_U is equal to 1.

1.0

Example 2: standard normal distribution

A standard normal random variable Z∼N(μ=0,σ=1)Z \sim \mathcal{N}(\mu=0,\sigma=1) is described by the probability density function:

fZ(z)=12πe−z22.f_Z(z) = \tfrac{1}{\sqrt{2\pi}} e^{ -\frac{z^2}{2} }.

The mean μZ=0\mu_Z=0 (the Greek letter mu) and the standard deviation σZ=1\sigma_Z=1 (the Greek letter sigma) are called the parameters of the distribution.

The math notation N(μ,σ)\mathcal{N}(\mu, \sigma) is used to describe the whole family of normal probability distributions, and Z∼N(μZ=0,σZ=1)Z \sim \mathcal{N}(\mu_Z=0, \sigma_Z=1) is a particular instance of the distribution with mean μZ=0\mu_Z = 0 and standard deviation σZ=1\sigma_Z = 1.

Plotting the normal probability density function

<Figure size 750x230 with 1 Axes>

Calculating the probability of an event

The code example below shows the calculation of the probability Pr⁡ ⁣({1≤Z≤2})\Pr\!\left( \{ 1 \leq Z \leq 2 \} \right), which corresponds to the integral ∫z=1z=2fZ(z)dz\int_{z=1}^{z=2} f_Z(z) dz.

We use the quad function to integrate rvZ.pdf between z=1z=1 and z=2z=2.

0.13590512198327787

The total area under the graph of fZf_Z is equal to 1.

To verify this claim, we would need to compute ∫u=−∞u=∞fZ(z) dz\int_{u=-\infty}^{u=\infty} f_Z(z)\,dz, but the values of fZf_Z drop off to zero very quickly outside the central region, so it is sufficient to compute the integral ∫u=−10u=10fZ(z) dz\int_{u=-10}^{u=10} f_Z(z)\,dz, which extends 10 standard deviations to the left and 10 standard deviaitons to the right.

1.0000000000000002

Cumulative distribution functions

Definitions:

  • FXF_X: the cumulative distribution function (CDF) tells us the probability of an outcome less than or equal to a given value: FX(b)=Pr({X≤b})F_X(b) = Pr(\{ X \leq b \}).

  • FX−1F_X^{-1}: the inverse cumulative distribution function computes contains the information about the quantiles of the probability distribution. The value FX−1(q)=xqF_X^{-1}(q)=x_q tells how far you need to go in the sample space so that the event {X≤xq}\{ X \leq x_q \} contains a proportion qq of the total probability: Pr⁡({X≤xq})=q\Pr(\{ X \leq x_q \})=q.

Example 1 (continued): uniform random variable

<Figure size 750x230 with 1 Axes>
<Figure size 750x230 with 1 Axes>
<Figure size 750x230 with 2 Axes>
0.3
0.3

Example 2 (continued): normal random variable

<Figure size 750x230 with 2 Axes>
0.13590512198327787
0.13590512198327787

Inverse of the cumulative distribution function

1.644853626951472
0.95
[-1.6448536269514729, 1.644853626951472]

Calculating expectations

We denote EX[w]\mathbb{E}_X[w] the expected value of the function w(X)w(X) computes the average value of w(X)w(X) computed for all the possible values of the random variable XX.

Example 1: mean and variance of the uniform distribution

Mean

μU=EU[U]=∫01ufU(u)  du=∫01u⋅1  du=12.\mu_U = \mathbb{E}_U[U] = \int_0^1 u f_U(u) \; du = \int_0^1 u \cdot 1 \; du = \tfrac{1}{2}.
0.5

So the mean is μU=12=0.5\mu_U = \frac{1}{2} = 0.5.

Variance

The formula for the variance is

σU2=EU ⁣[(U−μU)2]=∫01(u−12)2⋅fU(u)  du.\sigma_U^2 = \mathbb{E}_U\!\left[ (U-\mu_U)^2 \right] = \int_0^1 (u- \tfrac{1}{2})^2 \cdot f_U(u) \; du.
0.08333333333333333

So the variance of UU is σU2=0.083‾=112\sigma_U^2 = 0.08\overline{3} = \frac{1}{12}.

We can compute the standard deviation σU\sigma_U (the square root of the variance) by calling the method rvu.std.

0.28867513459481287

Example 2: mean and variance of a normal distribution

fZ(z)=12πe−z22.f_Z(z) = \tfrac{1}{\sqrt{2\pi}} e^{ -\frac{z^2}{2} }.

The mean of ZZ is

0.0

The variance of ZZ is

1.0
1.0

Skewness and kurtosis

0.0
0.0

Kombucha volume example

A random variable KK with a normal distribution N(μK,σK)\mathcal{N}(\mu_K,\sigma_K) is described by the probability density function:

fK(k)=1σK2πe−(k−μK)22σK2.f_K(k) = \tfrac{1}{\sigma_K\sqrt{2\pi}} e^{\small -\tfrac{(k-\mu_K)^2}{2\sigma_K^2}}.

The mean μK\mu_K (the Greek letter mu) and the standard deviation σK\sigma_K (the Greek letter sigma) are called the parameters of the distribution.

The math notation N(μ,σ)\mathcal{N}(\mu, \sigma) is used to describe the whole family of normal probability distributions, and K∼N(μK=1000,σK=10)K \sim \mathcal{N}(\mu_K=1000, \sigma_K=10) is a particular instance of the distribution with mean μK=1000\mu_K = 1000 and standard deviation σK=10\sigma_K = 10.

Create a normal random variable with mean 1000 and standard deviation 10.

Plotting the probability density function

<Figure size 750x230 with 1 Axes>

The cumulative distribution is the integral of the probability density function:

FK(b)=Pr({K≤b})=∫−∞bfK(k) dk.F_K(b) = \textrm{Pr}(\{K \leq b\}) = \int_{-\infty}^b f_K(k) \, dk.
<Figure size 750x230 with 1 Axes>

The inverse of the cumulative distribution function FK−1F_K^{-1} is available as method rvK.ppf.

<Figure size 750x230 with 1 Axes>

Properties of the distribution

1000.0
100.0
10.0
1000.0
(-inf, inf)

Computing probabilities

Suppose you want to compute the probability of the outcome {980≤K≤1020}\{ 980 \leq K \leq 1020 \} for the random variable KK.

Option A: Obtain Pr({980≤N≤1020})\textrm{Pr}(\{980 \leq N \leq 1020\}) by calculating the integral of fKf_K between 980 and 1020.

0.9544997361036411

Option B: Obtain Pr({980≤N≤1020})\textrm{Pr}(\{980 \leq N \leq 1020\}) by calculating the difference in the CDF FKF_K, Pr({980≤K≤1020})=FK(1020)−FK(980)\textrm{Pr}(\{980 \leq K \leq 1020\}) = F_K(1020) - F_K(980).

0.9544997361036416

Computing quantiles

Suppose we want to find the interval (−∞,kq](-\infty, k_q] that contains proportion qq of the total probability. We can fing kqk_q by calling the inverse CDF funciton FK−1=rvK.ppfF_K^{-1} = \texttt{rvK.ppf}.

First quartile

The first quartile (q=0.25q=0.25 quantile) is located at FK−1(0.25)F_K^{-1}(0.25):

993.2551024980392

We can verify that Pr⁡({K≤993.255})=0.25\Pr(\{K \leq 993.255\}) = 0.25 by calling rvK.cdf with that value.

0.24999999999999895

Second quartile = the median

1000.0

Third quartile

1006.7448975019608

Left tail

983.5514637304852

Right tail

1016.4485362695148

Computing confidence intervals

To compute a 90% confidence interval for the random variable KK, we can call the rvK.ppf() twice.

[983.5514637304852, 1016.4485362695148]

Generating random observations

Let’s say you want to generate n=100n=100 observations from the random variable KK. You can do this by calling the method rvK.rvs(100).

array([1005.8487584 , 1012.3119574 , 1008.21900264])

Sample mean

999.3321800993151

Sample standard deviation

9.234629119029867

Computing expectations

Suppose the distributor accepts only bottles contain between 980 ml and 1020 ml, and you’ll receive a receive payment of $2\$2 for each bottle. Bottles outside that range get rejected and you don’t get paid for them.

2
0
1.9089994604952036

Visually speaking, only the middle part of the probability distribution “counts” towards the payment. The subset that contributes to the expectation can be visualized as the values inside the rectangular region shown below.

<Figure size 750x230 with 1 Axes>

Discussion

Bulk of the normal distribution

How much of the total probability lies within nn standard deviations of the mean?

Pr({μK−nσK≤K≤μK+nσK})  =  pn.\textrm{Pr}(\{\mu_K - n\sigma_K \leq K \leq \mu_K + n\sigma_K\}) \; = \; p_n.
p_2 = Pr( K in [980.0, 1020.0] ) = 0.954
p_3 = Pr( K in [970.0, 1030.0] ) = 0.997

The code below highlights the interval InI_n and computes the probability pnp_n. Change the value of the variable n to get different plots.

<Figure size 750x200 with 2 Axes>
0.9544997361036411
<Figure size 750x230 with 1 Axes>

Try changing the value of the variable n to 1 or 3 in the above code cell.

Tails of the normal distribution

We’re often interested in tail ends of the distribution, which contain the unlikely events.

Pr({K<980.0 or K>1020.0}) = 0.0455
Pr({K<970.0 or K>1030.0}) = 0.0027

The code below highlights the tails of the distribution.

Pr( {K<980.0} ∪ {K>1020.0} ) = 0.0455
<Figure size 750x230 with 1 Axes>

Try changing the value of the variable n in the above code cell.

<Figure size 750x200 with 2 Axes>

The above calculations leads us to an important rule of thumb: the values of the 5% tail of the distribution are approximately n=2n=2 standard deviations away from the mean (more precisely n=1.96n=1.96 to get exactly 5%). We’ll use this facts later in Chapter 3 to define events that are less than 5% likely to occur by chance.

Exercises