Confidence Intervals

This code demonstrates how to create a 99% confidence interval for the mean of a sample in Julia. Remember to adapt this code for different confidence levels and sample data as needed.

Breakdown

  1. Import necessary packages:

    • Statistics: Provides functions for statistical calculations like mean and std.
    • Distributions: Provides probability distributions, including the t-distribution.
  2. Define sample data: Replace the example data with your actual data.

  3. Calculate sample statistics:

    • sample_mean: Calculates the mean of the data.
    • sample_std: Calculates the sample standard deviation (corrected for sample size).
  4. Calculate degrees of freedom:

    • degrees_of_freedom: Calculates the degrees of freedom for the t-distribution.
  5. Define confidence level:

    • confidence_level: Sets the desired confidence level (0.99 for 99%).
  6. Calculate alpha:

    • alpha: Calculates the significance level (1 - confidence level).
  7. Find the critical t-value:

    • quantile(TDist(degrees_of_freedom), 1 - alpha/2) finds the critical t-value from the t-distribution for the given degrees of freedom and alpha/2 (since it’s a two-tailed interval).
  8. Calculate margin of error:

    • margin_of_error: Calculates the margin of error based on the critical t-value, sample standard deviation, and sample size.
  9. Calculate confidence interval:

    • lower_bound and upper_bound: Calculate the lower and upper bounds of the confidence interval.
  10. Print the results:

using Statistics, Distributions

# Sample data (replace with your actual data)
data = [10.0, 12.5, 15.3, 18.1, 20.2, 11.7, 13.9, 16.5, 19.0, 21.4]

# Calculate sample mean and standard deviation
sample_mean = mean(data)
sample_std = std(data, corrected=true)  # Corrected for sample standard deviation

# Calculate degrees of freedom
degrees_of_freedom = length(data) - 1

# Define confidence level (99%)
confidence_level = 0.99

# Calculate alpha
alpha = 1 - confidence_level

# Find the critical t-value
t_critical = quantile(TDist(degrees_of_freedom), 1 - alpha/2)

# Calculate margin of error
margin_of_error = t_critical * (sample_std / sqrt(length(data)))

# Calculate confidence interval
lower_bound = sample_mean - margin_of_error
upper_bound = sample_mean + margin_of_error

# Print the results
println("99% Confidence Interval:")
println("Lower Bound: ", lower_bound)
println("Upper Bound: ", upper_bound) 

Explanation: