chi_square.cc 7.0 KB

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