Link Search Menu Expand Document (external link)

How to compute a confidence interval for the difference between two means when both population variances are known (in Python, using NumPy and SciPy)

See all solutions.

Task

If we have samples from two independent populations, and both of the population variances are known, how do we construct a confidence interval for the difference between the population means?

Related tasks:

Solution

We’re going to use some fake data here to illustrate how to make the confidence interval. Replace our fake data and population variances with your actual data and population variances if you use this code.

1
2
3
4
sample1 = [15, 10, 7, 22, 17, 14]
sample2 = [9, 1, 11, 13, 3, 6]
pop1_variance = 2.3
pop2_variance = 3

We will need the size and mean of each sample.

1
2
3
4
5
import numpy as np
n_sample1 = len(sample1)
n_sample2 = len(sample2)
xbar1 = np.mean(sample1)
xbar2 = np.mean(sample2)

We can then use that data to create the confidence interval.

1
2
3
4
5
6
7
8
9
10
11
# Find the critical value from the normal distribution
from scipy import stats
alpha = 0.05       # replace with your chosen alpha (here, a 95% confidence level)
critical_val = stats.norm.ppf(1-alpha/2)

# Find the lower and upper bounds of the confidence interval
upper_bound = (xbar1 - xbar2) + \
    critical_val*np.sqrt((pop1_variance/n_sample1) + (pop2_variance/n_sample2))
lower_bound = (xbar1 - xbar2) - \
    critical_val*np.sqrt((pop1_variance/n_sample1) + (pop2_variance/n_sample2))
lower_bound, upper_bound
1
(5.15791188458682, 8.842088115413178)

Our 95% confidence interval for the true difference between the population means is $[5.1579, 8.842]$.

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Elizabeth Czarniak (CZARNIA_ELIZ@bentley.edu)