gaussian_distribution.h 9.3 KB

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