Confidence Interval for Population Mean (One-Sample t-test)

tags: #statistics/inferential/ttest/one_sample

Formula: CI for one-sample t-test

To compute the CI for a one-sample t-test:

CI(y¯)=y¯±tn1SE(y¯), where SE(y¯)=sn

where, t is the critical value from student’s distribution with n1 degrees of freedom based on the confidence level.


Computing the CI in Python

We can use the t.interval() function from the scipy.stats library to calculate a confidence interval for a population mean:

from scipy.stats import t

# compute ci interval
t.interval(alpha, df, loc, scale)

Note that the t.interval() function takes the following arguments:

Example
import numpy as np
from scipy.stats import t

# Generate sample data
sample = np.array([4.3, 3.8, 5.1, 4.9, 3.5, 4.2, 4.6, 4.0, 5.2, 4.7])

# Compute the sample mean and sample standard deviation
n = len(sample)
sample_mean = np.mean(sample)
sample_std = np.std(sample, ddof=1)

# Set the desired confidence level and degrees of freedom
alpha = 0.05
df = n - 1

# Compute the t-value for the desired confidence level and degrees of freedom
t_value = t.ppf(1 - alpha / 2, df)

# Compute the lower and upper bounds of the confidence interval
lower_bound, upper_bound = t.interval(alpha, df, loc=sample_mean, scale=sample_std / np.sqrt(n))

# Print the results
print("Sample mean: {:.2f}".format(sample_mean))
print("Sample standard deviation: {:.2f}".format(sample_std))
print("95% confidence interval: [{:.2f}, {:.2f}]".format(lower_bound, upper_bound))
Powered by Forestry.md