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 return std::pow(z * std::sqrt(variance) + mean, 3.0) * dof;
129 }
130 }
131
132 if (p_value <= 0.0) return kChiMax;
133
134 // Otherwise search for the p value by bisection
135 double min_chisq = 0.0;
136 double max_chisq = kChiMax;
137 double current = dof / std::sqrt(p_value);
138 while ((max_chisq - min_chisq) > kChiEpsilon) {
139 if (ChiSquarePValue(current, dof) < p_value) {
140 max_chisq = current;
141 } else {
142 min_chisq = current;
143 }
144 current = (max_chisq + min_chisq) * 0.5;
145 }
146 return current;
147 }
148
149 // Calculates the p-value (probability) of a given chi-square value
150 // and degrees of freedom.
151 //
152 // Adapted from the POCHISQ function from:
153 // Hill, I. D. and Pike, M. C. Algorithm 299
154 // Collected Algorithms of the CACM 1963 p. 243
155 //
ChiSquarePValue(double chi_square,int dof)156 double ChiSquarePValue(double chi_square, int dof) {
157 static constexpr double kLogSqrtPi =
158 0.5723649429247000870717135; // Log[Sqrt[Pi]]
159 static constexpr double kInverseSqrtPi =
160 0.5641895835477562869480795; // 1/(Sqrt[Pi])
161
162 // For large degrees of freedom, use the normal approximation by
163 // Wilson, E. B. and Hilferty, M. M. (1931)
164 // Via Wikipedia:
165 // By the Central Limit Theorem, because the chi-square distribution is the
166 // sum of k independent random variables with finite mean and variance, it
167 // converges to a normal distribution for large k.
168 if (dof > kLargeDOF) {
169 // Re-scale everything.
170 const double chi_square_scaled = std::pow(chi_square / dof, 1.0 / 3);
171 const double mean = 1 - 2.0 / (9 * dof);
172 const double variance = 2.0 / (9 * dof);
173 // If variance is 0, this method cannot be used.
174 if (variance != 0) {
175 const double z = (chi_square_scaled - mean) / std::sqrt(variance);
176 if (z > 0) {
177 return normal_survival(z);
178 } else if (z < 0) {
179 return 1.0 - normal_survival(-z);
180 } else {
181 return 0.5;
182 }
183 }
184 }
185
186 // The chi square function is >= 0 for any degrees of freedom.
187 // In other words, probability that the chi square function >= 0 is 1.
188 if (chi_square <= 0.0) return 1.0;
189
190 // If the degrees of freedom is zero, the chi square function is always 0 by
191 // definition. In other words, the probability that the chi square function
192 // is > 0 is zero (chi square values <= 0 have been filtered above).
193 if (dof < 1) return 0;
194
195 auto capped_exp = [](double x) { return x < -20 ? 0.0 : std::exp(x); };
196 static constexpr double kBigX = 20;
197
198 double a = 0.5 * chi_square;
199 const bool even = !(dof & 1); // True if dof is an even number.
200 const double y = capped_exp(-a);
201 double s = even ? y : (2.0 * POZ(-std::sqrt(chi_square)));
202
203 if (dof <= 2) {
204 return s;
205 }
206
207 chi_square = 0.5 * (dof - 1.0);
208 double z = (even ? 1.0 : 0.5);
209 if (a > kBigX) {
210 double e = (even ? 0.0 : kLogSqrtPi);
211 double c = std::log(a);
212 while (z <= chi_square) {
213 e = std::log(z) + e;
214 s += capped_exp(c * z - a - e);
215 z += 1.0;
216 }
217 return s;
218 }
219
220 double e = (even ? 1.0 : (kInverseSqrtPi / std::sqrt(a)));
221 double c = 0.0;
222 while (z <= chi_square) {
223 e = e * (a / z);
224 c = c + e;
225 z += 1.0;
226 }
227 return c * y + s;
228 }
229
230 } // namespace random_internal
231 ABSL_NAMESPACE_END
232 } // namespace absl
233