Login
📚 Python for Introductory Statistics
Chapters ▾

10.2 Confidence Interval for Mean μ (t Distribution)

Watch demo video

Consider a random sample of n from a population with an unknow mean μ and unknown standard deviation σ. To construct an interval estimate of the population mean μ with (1α)100 confidence, use the following: Confidence level, C=1α

C=1α (level of confidence)

E=tα2×sn (Margin of Error)

x¯E<μ<x¯+E (confidence interval)

scipy.stats to obtain the value of tα2

from scipy import stats
stats.t.ppf(C+(1-C)/2,n-1,0,1)  # df=n-1

Note: When the sample size is large, the t-distribution is robust when the shape of the distribution is not normal.

Margin of Error for μ (t-distribution summary stats given)

To find the margin of error to estimate the population mean when summary stats is given, use the function error_t_mean below with arguments: level of confidence C, std and n. Here the population is assumed to be normal.

E = t α 2 s n

# margin of error given the level of confidence C, mean, std and n 
def error_t_mean(C,std,n):
    from scipy import stats
    ebm = (std/n**.5)*stats.t.ppf(C+(1-C)/2,n-1,0,1)
    return print("Margin of Error is",ebm)

You can also use the code below by substituting std, n and C:

from scipy import stats
error = (std/n**.5)*stats.t.ppf(C+(1-C)/2,n-1,0,1)

Example: In a study of a new pain relieving drag, the mean and standard deviation of pain levels for 15 subjects are 8 and 1.7 respectively. Find the margin of error for constructing a 95% confidence interval for the mean pain levels for the population (assume normal).

# Option 1

from scipy import stats 
C = .95
std = 1.72
n = 15

error = (std/n**.5)*stats.t.ppf(C+(1-C)/2,n-1,0,1)
error
Show expected output
0.9525042514911835
# Option 2
error_t_mean(.95, 1.72, 15)
Show expected output
Margin of Error is 0.9525042514911835

Interpretation: In both cases, the margin of error is 0.9525042514911835.

To find the confidence interval for estimating the population mean when summary stats is given you can subtract and add the margin of error from above to the mean or use the function conf_t_mean below with arguments: level of confidence C, mean, std and n. Here the population is assumed to be normal.

# confidence interval given level of confidence C and x 

def conf_t_mean(C,mean,std,n):
    from scipy import stats
    ebm = (std/n**.5)*stats.t.ppf(C+(1-C)/2,n-1,0,1)
    print ('mean is',mean,'and std is',std)
    return print("(", mean-ebm, ",", mean+ebm, ')' )

Example:

Adapted from Python for Introductory Statistics, by Simon Aman (Truman College, City Colleges of Chicago), licensed under CC BY 4.0. Changes were made: reformatted as an accessible XYZ web edition with live in-browser code cells. License: CC-BY-4.0.