Repository Public
1import Foundation23/// Method for a binomial proportion interval.4public enum ProportionIntervalMethod: String, Sendable, Codable, CaseIterable {5 /// Wilson score interval (recommended default; no continuity correction).6 case wilson7 /// Wald / normal approximation p̂ ± z·√(p̂(1−p̂)/n).8 case wald9 /// Clopper–Pearson "exact" interval from Beta quantiles.10 case clopperPearson11}1213extension Inference {14 /// Confidence interval for a mean with unknown variance: x̄ ± t(1−α/2; n−1)·s/√n.15 public static func meanInterval(_ x: [Double], level: Double = 0.95) throws -> ConfidenceInterval {16 let v = try clean(x, min: 2, "sample")17 try checkLevel(level)18 let n = Double(v.count), m = Descriptive.mean(v)19 let half = StudentTDistribution(df: n - 1).isf((1 - level) / 2) * Descriptive.standardDeviation(v) / n.squareRoot()20 return ConfidenceInterval(estimate: m, lower: m - half, upper: m + half, level: level,21 method: "Student t, df = \(v.count - 1)")22 }2324 /// Confidence interval for a mean with KNOWN population standard deviation: x̄ ± z·σ/√n.25 public static func meanInterval(_ x: [Double], knownSigma sigma: Double, level: Double = 0.95) throws -> ConfidenceInterval {26 let v = try clean(x, min: 1, "sample")27 try checkLevel(level)28 guard sigma > 0 else { throw StatError.invalidInput("sigma must be positive") }29 let m = Descriptive.mean(v)30 let half = NormalDistribution.standard.isf((1 - level) / 2) * sigma / Double(v.count).squareRoot()31 return ConfidenceInterval(estimate: m, lower: m - half, upper: m + half, level: level, method: "Normal, known σ")32 }3334 /// Confidence interval for a binomial proportion (default: Wilson score).35 public static func proportionInterval(successes k: Int, trials n: Int, level: Double = 0.95,36 method: ProportionIntervalMethod = .wilson) throws -> ConfidenceInterval {37 guard n > 0, k >= 0, k <= n else { throw StatError.invalidInput("need 0 ≤ successes ≤ trials and trials > 0") }38 try checkLevel(level)39 let p = Double(k) / Double(n), nd = Double(n)40 let z = NormalDistribution.standard.isf((1 - level) / 2)41 switch method {42 case .wilson:43 let denom = 1 + z * z / nd44 let centre = (p + z * z / (2 * nd)) / denom45 let half = z * (p * (1 - p) / nd + z * z / (4 * nd * nd)).squareRoot() / denom46 return ConfidenceInterval(estimate: p, lower: max(0, centre - half), upper: min(1, centre + half), level: level, method: "Wilson score")47 case .wald:48 let half = z * (p * (1 - p) / nd).squareRoot()49 return ConfidenceInterval(estimate: p, lower: max(0, p - half), upper: min(1, p + half), level: level, method: "Wald (normal approximation)")50 case .clopperPearson:51 let a = (1 - level) / 252 let lo = k == 0 ? 0 : BetaDistribution(a: Double(k), b: Double(n - k + 1)).quantile(a)53 let hi = k == n ? 1 : BetaDistribution(a: Double(k + 1), b: Double(n - k)).isf(a)54 return ConfidenceInterval(estimate: p, lower: lo, upper: hi, level: level, method: "Clopper–Pearson (exact)")55 }56 }5758 /// Confidence interval for a variance of normal data: [(n−1)s²/χ²(1−α/2), (n−1)s²/χ²(α/2)], df = n − 1.59 public static func varianceInterval(_ x: [Double], level: Double = 0.95) throws -> ConfidenceInterval {60 let v = try clean(x, min: 2, "sample")61 try checkLevel(level)62 let df = Double(v.count - 1), s2 = Descriptive.variance(v)63 let chi = ChiSquaredDistribution(df: df)64 let a = (1 - level) / 265 return ConfidenceInterval(estimate: s2, lower: df * s2 / chi.isf(a), upper: df * s2 / chi.quantile(a), level: level,66 method: "Chi-square, df = \(v.count - 1) (normal data)")67 }6869 /// Confidence interval for the difference of two means μx − μy.70 /// `equalVariances: true` uses the pooled variance with n₁+n₂−2 df; false uses Welch's standard error71 /// and the Welch–Satterthwaite degrees of freedom.72 public static func meanDifferenceInterval(_ x: [Double], _ y: [Double], equalVariances: Bool = false,73 level: Double = 0.95) throws -> ConfidenceInterval {74 let s = try twoSampleStats(x, y, equalVariances: equalVariances)75 try checkLevel(level)76 let half = StudentTDistribution(df: s.df).isf((1 - level) / 2) * s.se77 return ConfidenceInterval(estimate: s.diff, lower: s.diff - half, upper: s.diff + half, level: level,78 method: (equalVariances ? "Pooled-variance t" : "Welch t") + String(format: ", df = %.6g", s.df))79 }8081 struct TwoSampleStats { var diff, se, df, mx, my, vx, vy, pooledSD: Double; var nx, ny: Int }8283 static func twoSampleStats(_ x: [Double], _ y: [Double], equalVariances: Bool) throws -> TwoSampleStats {84 let a = try clean(x, min: 2, "first sample"), b = try clean(y, min: 2, "second sample")85 let n1 = Double(a.count), n2 = Double(b.count)86 let v1 = Descriptive.variance(a), v2 = Descriptive.variance(b)87 let m1 = Descriptive.mean(a), m2 = Descriptive.mean(b)88 let sp2 = ((n1 - 1) * v1 + (n2 - 1) * v2) / (n1 + n2 - 2)89 let se: Double, df: Double90 if equalVariances {91 se = (sp2 * (1 / n1 + 1 / n2)).squareRoot()92 df = n1 + n2 - 293 } else {94 let a1 = v1 / n1, a2 = v2 / n295 se = (a1 + a2).squareRoot()96 df = (a1 + a2) * (a1 + a2) / (a1 * a1 / (n1 - 1) + a2 * a2 / (n2 - 1))97 }98 guard se > 0 else { throw StatError.invalidInput("both samples are constant: the standard error is zero") }99 return TwoSampleStats(diff: m1 - m2, se: se, df: df, mx: m1, my: m2, vx: v1, vy: v2, pooledSD: sp2.squareRoot(), nx: a.count, ny: b.count)100 }101}102