Statistics Confidence Intervals
A confidence interval gives a range of plausible values for a population parameter, built from sample data, along with a stated long-run success rate for the method used to build it.
What a Confidence Interval Really Means
A confidence interval is a range built from sample data that is meant to capture a population parameter, like a mean or a proportion, along with a stated confidence level such as 95%.
Building a CI for a Mean (Sigma Known)
Example
import math
def z_confidence_interval(sample_mean, pop_std, n, z_crit=1.96):
margin = z_crit * (pop_std / math.sqrt(n))
return sample_mean - margin, sample_mean + margin
lower, upper = z_confidence_interval(sample_mean=72.5, pop_std=9.0, n=50)
print("95% CI:", (round(lower, 2), round(upper, 2)))Building a CI for a Mean (Sigma Unknown)
When the population standard deviation isn't known - the far more common situation - we estimate it from the sample and use a critical value from the t-distribution with n - 1 degrees of freedom instead of the normal distribution. Because the t-distribution has heavier tails, this produces a slightly wider interval that accounts for the extra uncertainty of estimating the spread from the same data used to estimate the mean.
Example
import math
def sample_std(data):
mean = sum(data) / len(data)
variance = sum((x - mean) ** 2 for x in data) / (len(data) - 1)
return math.sqrt(variance)
def t_confidence_interval(sample, t_crit):
n = len(sample)
mean = sum(sample) / n
s = sample_std(sample)
margin = t_crit * (s / math.sqrt(n))
return mean - margin, mean + margin
# t critical value for 95% confidence, df = n - 1 = 14, looked up from a t-table
scores = [61, 64, 59, 70, 68, 62, 65, 60, 66, 63, 69, 58, 67, 64, 61]
lower, upper = t_confidence_interval(scores, t_crit=2.145)
print("95% CI:", (round(lower, 2), round(upper, 2)))- A larger sample size shrinks the interval, since standard error falls as sample size grows
- A higher confidence level (say 99% instead of 90%) widens the interval
- More variability in the underlying data widens the interval
- Decide on a confidence level, such as 95%
- Compute the sample mean and standard error
- Look up the appropriate critical value (z if sigma is known, t with n - 1 degrees of freedom otherwise)
- Multiply the critical value by the standard error to get the margin of error
- Add and subtract the margin of error from the sample mean to get the interval