xref: /aosp_15_r20/external/abseil-cpp/absl/random/internal/chi_square.cc (revision 9356374a3709195abf420251b3e825997ff56c0f)
1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "absl/random/internal/chi_square.h"
16 
17 #include <cmath>
18 
19 #include "absl/random/internal/distribution_test_util.h"
20 
21 namespace absl {
22 ABSL_NAMESPACE_BEGIN
23 namespace random_internal {
24 namespace {
25 
26 #if defined(__EMSCRIPTEN__)
27 // Workaround __EMSCRIPTEN__ error: llvm_fma_f64 not found.
fma(double x,double y,double z)28 inline double fma(double x, double y, double z) {
29   return (x * y) + z;
30 }
31 #endif
32 
33 // Use Horner's method to evaluate a polynomial.
34 template <typename T, unsigned N>
EvaluatePolynomial(T x,const T (& poly)[N])35 inline T EvaluatePolynomial(T x, const T (&poly)[N]) {
36 #if !defined(__EMSCRIPTEN__)
37   using std::fma;
38 #endif
39   T p = poly[N - 1];
40   for (unsigned i = 2; i <= N; i++) {
41     p = fma(p, x, poly[N - i]);
42   }
43   return p;
44 }
45 
46 static constexpr int kLargeDOF = 150;
47 
48 // Returns the probability of a normal z-value.
49 //
50 // Adapted from the POZ function in:
51 //     Ibbetson D, Algorithm 209
52 //     Collected Algorithms of the CACM 1963 p. 616
53 //
POZ(double z)54 double POZ(double z) {
55   static constexpr double kP1[] = {
56       0.797884560593,  -0.531923007300, 0.319152932694,
57       -0.151968751364, 0.059054035642,  -0.019198292004,
58       0.005198775019,  -0.001075204047, 0.000124818987,
59   };
60   static constexpr double kP2[] = {
61       0.999936657524,  0.000535310849,  -0.002141268741, 0.005353579108,
62       -0.009279453341, 0.011630447319,  -0.010557625006, 0.006549791214,
63       -0.002034254874, -0.000794620820, 0.001390604284,  -0.000676904986,
64       -0.000019538132, 0.000152529290,  -0.000045255659,
65   };
66 
67   const double kZMax = 6.0;  // Maximum meaningful z-value.
68   if (z == 0.0) {
69     return 0.5;
70   }
71   double x;
72   double y = 0.5 * std::fabs(z);
73   if (y >= (kZMax * 0.5)) {
74     x = 1.0;
75   } else if (y < 1.0) {
76     double w = y * y;
77     x = EvaluatePolynomial(w, kP1) * y * 2.0;
78   } else {
79     y -= 2.0;
80     x = EvaluatePolynomial(y, kP2);
81   }
82   return z > 0.0 ? ((x + 1.0) * 0.5) : ((1.0 - x) * 0.5);
83 }
84 
85 // Approximates the survival function of the normal distribution.
86 //
87 // Algorithm 26.2.18, from:
88 // [Abramowitz and Stegun, Handbook of Mathematical Functions,p.932]
89 // http://people.math.sfu.ca/~cbm/aands/abramowitz_and_stegun.pdf
90 //
normal_survival(double z)91 double normal_survival(double z) {
92   // Maybe replace with the alternate formulation.
93   // 0.5 * erfc((x - mean)/(sqrt(2) * sigma))
94   static constexpr double kR[] = {
95       1.0, 0.196854, 0.115194, 0.000344, 0.019527,
96   };
97   double r = EvaluatePolynomial(z, kR);
98   r *= r;
99   return 0.5 / (r * r);
100 }
101 
102 }  // namespace
103 
104 // Calculates the critical chi-square value given degrees-of-freedom and a
105 // p-value, usually using bisection. Also known by the name CRITCHI.
ChiSquareValue(int dof,double p)106 double ChiSquareValue(int dof, double p) {
107   static constexpr double kChiEpsilon =
108       0.000001;  // Accuracy of the approximation.
109   static constexpr double kChiMax =
110       99999.0;  // Maximum chi-squared value.
111 
112   const double p_value = 1.0 - p;
113   if (dof < 1 || p_value > 1.0) {
114     return 0.0;
115   }
116 
117   if (dof > kLargeDOF) {
118     // For large degrees of freedom, use the normal approximation by
119     //     Wilson, E. B. and Hilferty, M. M. (1931)
120     //                     chi^2 - mean
121     //                Z = --------------
122     //                        stddev
123     const double z = InverseNormalSurvival(p_value);
124     const double mean = 1 - 2.0 / (9 * dof);
125     const double variance = 2.0 / (9 * dof);
126     // Cannot use this method if the variance is 0.
127     if (variance != 0) {
128       double term = z * std::sqrt(variance) + mean;
129       return dof * (term * term * term);
130     }
131   }
132 
133   if (p_value <= 0.0) return kChiMax;
134 
135   // Otherwise search for the p value by bisection
136   double min_chisq = 0.0;
137   double max_chisq = kChiMax;
138   double current = dof / std::sqrt(p_value);
139   while ((max_chisq - min_chisq) > kChiEpsilon) {
140     if (ChiSquarePValue(current, dof) < p_value) {
141       max_chisq = current;
142     } else {
143       min_chisq = current;
144     }
145     current = (max_chisq + min_chisq) * 0.5;
146   }
147   return current;
148 }
149 
150 // Calculates the p-value (probability) of a given chi-square value
151 // and degrees of freedom.
152 //
153 // Adapted from the POCHISQ function from:
154 //     Hill, I. D. and Pike, M. C.  Algorithm 299
155 //     Collected Algorithms of the CACM 1963 p. 243
156 //
ChiSquarePValue(double chi_square,int dof)157 double ChiSquarePValue(double chi_square, int dof) {
158   static constexpr double kLogSqrtPi =
159       0.5723649429247000870717135;  // Log[Sqrt[Pi]]
160   static constexpr double kInverseSqrtPi =
161       0.5641895835477562869480795;  // 1/(Sqrt[Pi])
162 
163   // For large degrees of freedom, use the normal approximation by
164   //     Wilson, E. B. and Hilferty, M. M. (1931)
165   // Via Wikipedia:
166   //   By the Central Limit Theorem, because the chi-square distribution is the
167   //   sum of k independent random variables with finite mean and variance, it
168   //   converges to a normal distribution for large k.
169   if (dof > kLargeDOF) {
170     // Re-scale everything.
171     const double chi_square_scaled = std::pow(chi_square / dof, 1.0 / 3);
172     const double mean = 1 - 2.0 / (9 * dof);
173     const double variance = 2.0 / (9 * dof);
174     // If variance is 0, this method cannot be used.
175     if (variance != 0) {
176       const double z = (chi_square_scaled - mean) / std::sqrt(variance);
177       if (z > 0) {
178         return normal_survival(z);
179       } else if (z < 0) {
180         return 1.0 - normal_survival(-z);
181       } else {
182         return 0.5;
183       }
184     }
185   }
186 
187   // The chi square function is >= 0 for any degrees of freedom.
188   // In other words, probability that the chi square function >= 0 is 1.
189   if (chi_square <= 0.0) return 1.0;
190 
191   // If the degrees of freedom is zero, the chi square function is always 0 by
192   // definition. In other words, the probability that the chi square function
193   // is > 0 is zero (chi square values <= 0 have been filtered above).
194   if (dof < 1) return 0;
195 
196   auto capped_exp = [](double x) { return x < -20 ? 0.0 : std::exp(x); };
197   static constexpr double kBigX = 20;
198 
199   double a = 0.5 * chi_square;
200   const bool even = !(dof & 1);  // True if dof is an even number.
201   const double y = capped_exp(-a);
202   double s = even ? y : (2.0 * POZ(-std::sqrt(chi_square)));
203 
204   if (dof <= 2) {
205     return s;
206   }
207 
208   chi_square = 0.5 * (dof - 1.0);
209   double z = (even ? 1.0 : 0.5);
210   if (a > kBigX) {
211     double e = (even ? 0.0 : kLogSqrtPi);
212     double c = std::log(a);
213     while (z <= chi_square) {
214       e = std::log(z) + e;
215       s += capped_exp(c * z - a - e);
216       z += 1.0;
217     }
218     return s;
219   }
220 
221   double e = (even ? 1.0 : (kInverseSqrtPi / std::sqrt(a)));
222   double c = 0.0;
223   while (z <= chi_square) {
224     e = e * (a / z);
225     c = c + e;
226     z += 1.0;
227   }
228   return c * y + s;
229 }
230 
231 }  // namespace random_internal
232 ABSL_NAMESPACE_END
233 }  // namespace absl
234