Repository Public
1import Foundation23/// Gauss–Legendre quadrature nodes and weights on [−1, 1].4enum GaussLegendre {5 /// Nodes/weights by Newton iteration on the Legendre polynomial (accurate to machine precision).6 static func rule(_ n: Int) -> (nodes: [Double], weights: [Double]) {7 var x = [Double](repeating: 0, count: n), w = [Double](repeating: 0, count: n)8 let m = (n + 1) / 29 for i in 0..<m {10 var z = cos(Double.pi * (Double(i) + 0.75) / (Double(n) + 0.5))11 var pp = 0.012 for _ in 0..<100 {13 var p1 = 1.0, p2 = 0.014 for j in 1...n {15 let p3 = p216 p2 = p117 p1 = ((2 * Double(j) - 1) * z * p2 - (Double(j) - 1) * p3) / Double(j)18 }19 pp = Double(n) * (z * p1 - p2) / (z * z - 1)20 let dz = p1 / pp21 z -= dz22 if abs(dz) < 1e-16 { break }23 }24 x[i] = -z; x[n - 1 - i] = z25 w[i] = 2 / ((1 - z * z) * pp * pp); w[n - 1 - i] = w[i]26 }27 return (x, w)28 }2930 static let rule16 = rule(16)31}3233/// Distribution of the studentized range Q = (max − min of k independent N(0,1)) / s, where34/// ν·s² ~ χ²(ν) independently. Used by Tukey's HSD. The CDF is evaluated by nested composite35/// Gauss–Legendre quadrature of36/// P(Q ≤ q) = ∫₀^∞ f_s(s) · k ∫ φ(z)[Φ(z) − Φ(z − q·s)]^{k−1} dz ds.37/// Intended for k ≥ 2 groups and df ≥ 1 (validated against SciPy for 2 ≤ k ≤ 20, 2 ≤ df ≤ 1000).38public struct StudentizedRangeDistribution: Sendable, Hashable, Codable {39 /// Number of groups (means) compared.40 public var k: Int41 /// Degrees of freedom of the variance estimate.42 public var df: Double43 public init(k: Int, df: Double) { self.k = k; self.df = df }4445 // inner rule: z from −8.5 to 8.5 in 17 panels of 16 points; Φ(z) precomputed once46 private static let inner: (z: [Double], w: [Double], phi: [Double], cdf: [Double]) = {47 let (x, w) = GaussLegendre.rule1648 var zs = [Double](), ws = [Double](), ph = [Double](), cd = [Double]()49 let panels = 17, lo = -8.5, width = 1.050 for p in 0..<panels {51 let a = lo + Double(p) * width52 for i in 0..<16 {53 let z = a + (x[i] + 1) / 2 * width54 zs.append(z); ws.append(w[i] * width / 2)55 ph.append(exp(-0.5 * z * z) / (2 * Double.pi).squareRoot())56 cd.append(0.5 * erfc(-z / 2.0.squareRoot()))57 }58 }59 return (zs, ws, ph, cd)60 }()6162 /// P(range of k standard normals ≤ w).63 static func rangeCDF(_ w: Double, k: Int) -> Double {64 guard w > 0 else { return 0 }65 let t = Self.inner66 let e = Double(k - 1)67 var s = 0.068 let c = 1 / 2.0.squareRoot()69 t.z.withUnsafeBufferPointer { z in70 t.w.withUnsafeBufferPointer { wt in71 t.phi.withUnsafeBufferPointer { phi in72 t.cdf.withUnsafeBufferPointer { cdf in73 for i in 0..<z.count {74 let u = z[i] - w75 // Φ(u) is 0 or 1 to double precision beyond ±8.3: skip the erfc call76 let lower = u < -8.3 ? 0 : (u > 8.3 ? 1 : 0.5 * erfc(-u * c))77 let d = cdf[i] - lower78 if d > 0 { s += wt[i] * phi[i] * pow(d, e) }79 }80 }81 }82 }83 }84 return min(1, Double(k) * s)85 }8687 /// P(Q ≤ q).88 public func cdf(_ q: Double) -> Double {89 guard k >= 2, df > 0, !q.isNaN else { return .nan }90 if q <= 0 { return 0 }91 if q.isInfinite { return 1 }92 if df > 2e5 { return Self.rangeCDF(q, k: k) }93 // s = √(χ²_ν / ν): integrate over the central 1 − 2e-16 of its mass94 let chi = ChiSquaredDistribution(df: df)95 let sLo = (chi.quantile(1e-16) / df).squareRoot(), sHi = (chi.isf(1e-16) / df).squareRoot()96 let logC = df / 2 * log(df) - SpecialFunctions.logGamma(df / 2) - (df / 2 - 1) * log(2)97 let (x, w) = GaussLegendre.rule1698 let panels = 1499 let width = (sHi - sLo) / Double(panels)100 var total = 0.0101 for p in 0..<panels {102 let a = sLo + Double(p) * width103 for i in 0..<16 {104 let s = a + (x[i] + 1) / 2 * width105 let dens = exp(logC + (df - 1) * log(s) - df * s * s / 2)106 if dens > 0 { total += w[i] * width / 2 * dens * Self.rangeCDF(q * s, k: k) }107 }108 }109 return min(1, max(0, total))110 }111112 /// P(Q > q).113 public func sf(_ q: Double) -> Double { 1 - cdf(q) }114115 /// The q with P(Q ≤ q) = p (Brent's method on the CDF; relative accuracy about 1e-9).116 public func quantile(_ p: Double) -> Double {117 guard k >= 2, df > 0, p >= 0, p <= 1 else { return .nan }118 if p == 0 { return 0 }119 if p == 1 { return .infinity }120 var hi = 8.0121 while cdf(hi) < p && hi < 1e6 { hi *= 2 }122 guard let r = try? RootFinder.brent({ self.cdf($0) - p }, lower: 0, upper: hi, xtol: 1e-10) else { return .nan }123 return r.root124 }125}126