Width of a Confidence Interval

Width of a Confidence IntervalΒΆ

In the class, we have seen that a \(100(1-\alpha)\%\) confidence interval for \(\mu\), when the population is \(N(\mu, \sigma^2)\) with known \(\sigma^2\), is:

\((\bar{X} - z_{1-\alpha/2}*\frac{\sigma}{\sqrt n}, \bar{X} + z_{1-\alpha/2}*\frac{\sigma}{\sqrt n})\).

The confidence interval length is: \(2 * z_{1-\alpha/2}*\frac{\sigma}{\sqrt n}\).

#import required libraries
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
import math
import ipywidgets as widgets
from IPython.display import display
def ci_width(conf_level, sigma, n):

    mu = 10
    sd = sigma
    two_tail_prob = (1-conf_level)/2  
    upper_bound = stats.norm.ppf(q = (1-two_tail_prob), loc = mu, scale = sd/math.sqrt(n))  
    lower_bound = stats.norm.ppf(q = (two_tail_prob), loc = mu, scale = sd/math.sqrt(n))
    
    #start off plotting 
    fig, ax = plt.subplots(figsize = (6, 6))

    #for pdf curve
    #generate synthetic data to plot the pdf
    xbar = stats.norm.rvs(loc = mu, scale = sd/math.sqrt(n), size = 10000)
    xbar1 = np.sort(xbar)

    plt.plot(xbar1, stats.norm.pdf(xbar1, loc = mu, scale = sd/math.sqrt(n)))

    x2 = np.arange(lower_bound, upper_bound, 0.01)

    plt.fill_between(x2,stats.norm.pdf(x2, loc = mu, scale = sd/math.sqrt(n)), color='blue')
    
    plt.text(int(np.min(xbar1))+1,np.max(stats.norm.pdf(xbar1, loc = mu, scale = sd/math.sqrt(n)))-0.05,
         "CI Length = $%.4f$" % (2*(upper_bound-lower_bound)), fontsize=14)
       
    plt.show()
con_level_wid = widgets.FloatSlider(min = 0.9, max = 0.99, step=0.01, value=0.95, description = "Clevel")
sigma_wid = widgets.FloatSlider(min = 0.1, max = 10, step=0.1, value=1, description = "Sigma")
size_wid = widgets.IntSlider(min = 1, max = 200, step=1, value=50, description = "Size")
widgets.interact(ci_width, conf_level = con_level_wid, sigma = sigma_wid, n = size_wid);
#ci_width(conf_level = 0.99, sigma = 4, n = 100)