1 // Copyright 2017 The Abseil Authors.
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
7 // https://www.apache.org/licenses/LICENSE-2.0
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.
15 #ifndef ABSL_RANDOM_GAUSSIAN_DISTRIBUTION_H_
16 #define ABSL_RANDOM_GAUSSIAN_DISTRIBUTION_H_
18 // absl::gaussian_distribution implements the Ziggurat algorithm
19 // for generating random gaussian numbers.
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/
29 #include <type_traits>
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"
36 namespace random_internal {
38 // absl::gaussian_distribution_base implements the underlying ziggurat algorithm
39 // using the ziggurat tables generated by the gaussian_distribution_gentables
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 {
47 template <typename URBG>
48 inline double zignor(URBG& g); // NOLINT(runtime/references)
51 friend class TableGenerator;
53 template <typename URBG>
54 inline double zignor_fallback(URBG& g, // NOLINT(runtime/references)
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;
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.
67 // These tables are just over 2kb in size; larger tables might improve the
68 // distributions, but also lead to more cache pollution.
70 // x = {3.71308, 3.44261, 3.22308, ..., 0}
71 // f = {0.00101, 0.00266, 0.00554, ..., 1}
76 static const Tables zg_;
77 random_internal::FastUniformBits<uint64_t> fast_u64_;
80 } // namespace random_internal
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 {
87 using result_type = RealType;
91 using distribution_type = gaussian_distribution;
93 explicit param_type(result_type mean = 0, result_type stddev = 1)
94 : mean_(mean), stddev_(stddev) {}
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_; }
100 // Returns the deviation distribution parameter. The default value is 1.0.
101 result_type stddev() const { return stddev_; }
103 friend bool operator==(const param_type& a, const param_type& b) {
104 return a.mean_ == b.mean_ && a.stddev_ == b.stddev_;
107 friend bool operator!=(const param_type& a, const param_type& b) {
116 std::is_floating_point<RealType>::value,
117 "Class-template absl::gaussian_distribution<> must be parameterized "
118 "using a floating-point type.");
121 gaussian_distribution() : gaussian_distribution(0) {}
123 explicit gaussian_distribution(result_type mean, result_type stddev = 1)
124 : param_(mean, stddev) {}
126 explicit gaussian_distribution(const param_type& p) : param_(p) {}
130 // Generating functions
131 template <typename URBG>
132 result_type operator()(URBG& g) { // NOLINT(runtime/references)
133 return (*this)(g, param_);
136 template <typename URBG>
137 result_type operator()(URBG& g, // NOLINT(runtime/references)
138 const param_type& p);
140 param_type param() const { return param_; }
141 void param(const param_type& p) { param_ = p; }
143 result_type(min)() const {
144 return -std::numeric_limits<result_type>::infinity();
146 result_type(max)() const {
147 return std::numeric_limits<result_type>::infinity();
150 result_type mean() const { return param_.mean(); }
151 result_type stddev() const { return param_.stddev(); }
153 friend bool operator==(const gaussian_distribution& a,
154 const gaussian_distribution& b) {
155 return a.param_ == b.param_;
157 friend bool operator!=(const gaussian_distribution& a,
158 const gaussian_distribution& b) {
159 return a.param_ != b.param_;
166 // --------------------------------------------------------------------------
167 // Implementation details only below
168 // --------------------------------------------------------------------------
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));
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();
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;
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);
201 x.param(param_type(mean, stddev));
206 namespace random_internal {
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.
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);
220 template <typename URBG>
221 inline double gaussian_distribution_base::zignor(
222 URBG& g) { // NOLINT(runtime/references)
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];
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]) {
240 // i == 0: Base box. Sample using a ratio of uniforms.
242 // This path happens about 0.05% of the time.
243 return zignor_fallback(g, j < 0);
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)) {
253 // The wedge was missed; reject the value and try again.
257 } // namespace random_internal
260 #endif // ABSL_RANDOM_GAUSSIAN_DISTRIBUTION_H_