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