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