gaussian_distribution.h 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. #ifndef ABSL_RANDOM_GAUSSIAN_DISTRIBUTION_H_
  15. #define ABSL_RANDOM_GAUSSIAN_DISTRIBUTION_H_
  16. // absl::gaussian_distribution implements the Ziggurat algorithm
  17. // for generating random gaussian numbers.
  18. //
  19. // Implementation based on "The Ziggurat Method for Generating Random Variables"
  20. // by George Marsaglia and Wai Wan Tsang: http://www.jstatsoft.org/v05/i08/
  21. //
  22. #include <cmath>
  23. #include <cstdint>
  24. #include <istream>
  25. #include <limits>
  26. #include <type_traits>
  27. #include "absl/base/config.h"
  28. #include "absl/random/internal/fast_uniform_bits.h"
  29. #include "absl/random/internal/generate_real.h"
  30. #include "absl/random/internal/iostream_state_saver.h"
  31. namespace absl {
  32. ABSL_NAMESPACE_BEGIN
  33. namespace random_internal {
  34. // absl::gaussian_distribution_base implements the underlying ziggurat algorithm
  35. // using the ziggurat tables generated by the gaussian_distribution_gentables
  36. // binary.
  37. //
  38. // The specific algorithm has some of the improvements suggested by the
  39. // 2005 paper, "An Improved Ziggurat Method to Generate Normal Random Samples",
  40. // Jurgen A Doornik. (https://www.doornik.com/research/ziggurat.pdf)
  41. class ABSL_DLL gaussian_distribution_base {
  42. public:
  43. template <typename URBG>
  44. inline double zignor(URBG& g); // NOLINT(runtime/references)
  45. private:
  46. friend class TableGenerator;
  47. template <typename URBG>
  48. inline double zignor_fallback(URBG& g, // NOLINT(runtime/references)
  49. bool neg);
  50. // Constants used for the gaussian distribution.
  51. static constexpr double kR = 3.442619855899; // Start of the tail.
  52. static constexpr double kRInv = 0.29047645161474317; // ~= (1.0 / kR) .
  53. static constexpr double kV = 9.91256303526217e-3;
  54. static constexpr uint64_t kMask = 0x07f;
  55. // The ziggurat tables store the pdf(f) and inverse-pdf(x) for equal-area
  56. // points on one-half of the normal distribution, where the pdf function,
  57. // pdf = e ^ (-1/2 *x^2), assumes that the mean = 0 & stddev = 1.
  58. //
  59. // These tables are just over 2kb in size; larger tables might improve the
  60. // distributions, but also lead to more cache pollution.
  61. //
  62. // x = {3.71308, 3.44261, 3.22308, ..., 0}
  63. // f = {0.00101, 0.00266, 0.00554, ..., 1}
  64. struct Tables {
  65. double x[kMask + 2];
  66. double f[kMask + 2];
  67. };
  68. static const Tables zg_;
  69. random_internal::FastUniformBits<uint64_t> fast_u64_;
  70. };
  71. } // namespace random_internal
  72. // absl::gaussian_distribution:
  73. // Generates a number conforming to a Gaussian distribution.
  74. template <typename RealType = double>
  75. class gaussian_distribution : random_internal::gaussian_distribution_base {
  76. public:
  77. using result_type = RealType;
  78. class param_type {
  79. public:
  80. using distribution_type = gaussian_distribution;
  81. explicit param_type(result_type mean = 0, result_type stddev = 1)
  82. : mean_(mean), stddev_(stddev) {}
  83. // Returns the mean distribution parameter. The mean specifies the location
  84. // of the peak. The default value is 0.0.
  85. result_type mean() const { return mean_; }
  86. // Returns the deviation distribution parameter. The default value is 1.0.
  87. result_type stddev() const { return stddev_; }
  88. friend bool operator==(const param_type& a, const param_type& b) {
  89. return a.mean_ == b.mean_ && a.stddev_ == b.stddev_;
  90. }
  91. friend bool operator!=(const param_type& a, const param_type& b) {
  92. return !(a == b);
  93. }
  94. private:
  95. result_type mean_;
  96. result_type stddev_;
  97. static_assert(
  98. std::is_floating_point<RealType>::value,
  99. "Class-template absl::gaussian_distribution<> must be parameterized "
  100. "using a floating-point type.");
  101. };
  102. gaussian_distribution() : gaussian_distribution(0) {}
  103. explicit gaussian_distribution(result_type mean, result_type stddev = 1)
  104. : param_(mean, stddev) {}
  105. explicit gaussian_distribution(const param_type& p) : param_(p) {}
  106. void reset() {}
  107. // Generating functions
  108. template <typename URBG>
  109. result_type operator()(URBG& g) { // NOLINT(runtime/references)
  110. return (*this)(g, param_);
  111. }
  112. template <typename URBG>
  113. result_type operator()(URBG& g, // NOLINT(runtime/references)
  114. const param_type& p);
  115. param_type param() const { return param_; }
  116. void param(const param_type& p) { param_ = p; }
  117. result_type(min)() const {
  118. return -std::numeric_limits<result_type>::infinity();
  119. }
  120. result_type(max)() const {
  121. return std::numeric_limits<result_type>::infinity();
  122. }
  123. result_type mean() const { return param_.mean(); }
  124. result_type stddev() const { return param_.stddev(); }
  125. friend bool operator==(const gaussian_distribution& a,
  126. const gaussian_distribution& b) {
  127. return a.param_ == b.param_;
  128. }
  129. friend bool operator!=(const gaussian_distribution& a,
  130. const gaussian_distribution& b) {
  131. return a.param_ != b.param_;
  132. }
  133. private:
  134. param_type param_;
  135. };
  136. // --------------------------------------------------------------------------
  137. // Implementation details only below
  138. // --------------------------------------------------------------------------
  139. template <typename RealType>
  140. template <typename URBG>
  141. typename gaussian_distribution<RealType>::result_type
  142. gaussian_distribution<RealType>::operator()(
  143. URBG& g, // NOLINT(runtime/references)
  144. const param_type& p) {
  145. return p.mean() + p.stddev() * static_cast<result_type>(zignor(g));
  146. }
  147. template <typename CharT, typename Traits, typename RealType>
  148. std::basic_ostream<CharT, Traits>& operator<<(
  149. std::basic_ostream<CharT, Traits>& os, // NOLINT(runtime/references)
  150. const gaussian_distribution<RealType>& x) {
  151. auto saver = random_internal::make_ostream_state_saver(os);
  152. os.precision(random_internal::stream_precision_helper<RealType>::kPrecision);
  153. os << x.mean() << os.fill() << x.stddev();
  154. return os;
  155. }
  156. template <typename CharT, typename Traits, typename RealType>
  157. std::basic_istream<CharT, Traits>& operator>>(
  158. std::basic_istream<CharT, Traits>& is, // NOLINT(runtime/references)
  159. gaussian_distribution<RealType>& x) { // NOLINT(runtime/references)
  160. using result_type = typename gaussian_distribution<RealType>::result_type;
  161. using param_type = typename gaussian_distribution<RealType>::param_type;
  162. auto saver = random_internal::make_istream_state_saver(is);
  163. auto mean = random_internal::read_floating_point<result_type>(is);
  164. if (is.fail()) return is;
  165. auto stddev = random_internal::read_floating_point<result_type>(is);
  166. if (!is.fail()) {
  167. x.param(param_type(mean, stddev));
  168. }
  169. return is;
  170. }
  171. namespace random_internal {
  172. template <typename URBG>
  173. inline double gaussian_distribution_base::zignor_fallback(URBG& g, bool neg) {
  174. using random_internal::GeneratePositiveTag;
  175. using random_internal::GenerateRealFromBits;
  176. // This fallback path happens approximately 0.05% of the time.
  177. double x, y;
  178. do {
  179. // kRInv = 1/r, U(0, 1)
  180. x = kRInv *
  181. std::log(GenerateRealFromBits<double, GeneratePositiveTag, false>(
  182. fast_u64_(g)));
  183. y = -std::log(
  184. GenerateRealFromBits<double, GeneratePositiveTag, false>(fast_u64_(g)));
  185. } while ((y + y) < (x * x));
  186. return neg ? (x - kR) : (kR - x);
  187. }
  188. template <typename URBG>
  189. inline double gaussian_distribution_base::zignor(
  190. URBG& g) { // NOLINT(runtime/references)
  191. using random_internal::GeneratePositiveTag;
  192. using random_internal::GenerateRealFromBits;
  193. using random_internal::GenerateSignedTag;
  194. while (true) {
  195. // We use a single uint64_t to generate both a double and a strip.
  196. // These bits are unused when the generated double is > 1/2^5.
  197. // This may introduce some bias from the duplicated low bits of small
  198. // values (those smaller than 1/2^5, which all end up on the left tail).
  199. uint64_t bits = fast_u64_(g);
  200. int i = static_cast<int>(bits & kMask); // pick a random strip
  201. double j = GenerateRealFromBits<double, GenerateSignedTag, false>(
  202. bits); // U(-1, 1)
  203. const double x = j * zg_.x[i];
  204. // Retangular box. Handles >97% of all cases.
  205. // For any given box, this handles between 75% and 99% of values.
  206. // Equivalent to U(01) < (x[i+1] / x[i]), and when i == 0, ~93.5%
  207. if (std::abs(x) < zg_.x[i + 1]) {
  208. return x;
  209. }
  210. // i == 0: Base box. Sample using a ratio of uniforms.
  211. if (i == 0) {
  212. // This path happens about 0.05% of the time.
  213. return zignor_fallback(g, j < 0);
  214. }
  215. // i > 0: Wedge samples using precomputed values.
  216. double v = GenerateRealFromBits<double, GeneratePositiveTag, false>(
  217. fast_u64_(g)); // U(0, 1)
  218. if ((zg_.f[i + 1] + v * (zg_.f[i] - zg_.f[i + 1])) <
  219. std::exp(-0.5 * x * x)) {
  220. return x;
  221. }
  222. // The wedge was missed; reject the value and try again.
  223. }
  224. }
  225. } // namespace random_internal
  226. ABSL_NAMESPACE_END
  227. } // namespace absl
  228. #endif // ABSL_RANDOM_GAUSSIAN_DISTRIBUTION_H_