chi_square.cc 7.0 KB

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