You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

gaussian_distribution.h 12 kB

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