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_BETA_DISTRIBUTION_H_
16 #define ABSL_RANDOM_BETA_DISTRIBUTION_H_
17
18 #include <cassert>
19 #include <cmath>
20 #include <istream>
21 #include <limits>
22 #include <ostream>
23 #include <type_traits>
24
25 #include "absl/meta/type_traits.h"
26 #include "absl/random/internal/fast_uniform_bits.h"
27 #include "absl/random/internal/fastmath.h"
28 #include "absl/random/internal/generate_real.h"
29 #include "absl/random/internal/iostream_state_saver.h"
30
31 namespace absl {
32 ABSL_NAMESPACE_BEGIN
33
34 // absl::beta_distribution:
35 // Generate a floating-point variate conforming to a Beta distribution:
36 // pdf(x) \propto x^(alpha-1) * (1-x)^(beta-1),
37 // where the params alpha and beta are both strictly positive real values.
38 //
39 // The support is the open interval (0, 1), but the return value might be equal
40 // to 0 or 1, due to numerical errors when alpha and beta are very different.
41 //
42 // Usage note: One usage is that alpha and beta are counts of number of
43 // successes and failures. When the total number of trials are large, consider
44 // approximating a beta distribution with a Gaussian distribution with the same
45 // mean and variance. One could use the skewness, which depends only on the
46 // smaller of alpha and beta when the number of trials are sufficiently large,
47 // to quantify how far a beta distribution is from the normal distribution.
48 template <typename RealType = double>
49 class beta_distribution {
50 public:
51 using result_type = RealType;
52
53 class param_type {
54 public:
55 using distribution_type = beta_distribution;
56
param_type(result_type alpha,result_type beta)57 explicit param_type(result_type alpha, result_type beta)
58 : alpha_(alpha), beta_(beta) {
59 assert(alpha >= 0);
60 assert(beta >= 0);
61 assert(alpha <= (std::numeric_limits<result_type>::max)());
62 assert(beta <= (std::numeric_limits<result_type>::max)());
63 if (alpha == 0 || beta == 0) {
64 method_ = DEGENERATE_SMALL;
65 x_ = (alpha >= beta) ? 1 : 0;
66 return;
67 }
68 // a_ = min(beta, alpha), b_ = max(beta, alpha).
69 if (beta < alpha) {
70 inverted_ = true;
71 a_ = beta;
72 b_ = alpha;
73 } else {
74 inverted_ = false;
75 a_ = alpha;
76 b_ = beta;
77 }
78 if (a_ <= 1 && b_ >= ThresholdForLargeA()) {
79 method_ = DEGENERATE_SMALL;
80 x_ = inverted_ ? result_type(1) : result_type(0);
81 return;
82 }
83 // For threshold values, see also:
84 // Evaluation of Beta Generation Algorithms, Ying-Chao Hung, et. al.
85 // February, 2009.
86 if ((b_ < 1.0 && a_ + b_ <= 1.2) || a_ <= ThresholdForSmallA()) {
87 // Choose Joehnk over Cheng when it's faster or when Cheng encounters
88 // numerical issues.
89 method_ = JOEHNK;
90 a_ = result_type(1) / alpha_;
91 b_ = result_type(1) / beta_;
92 if (std::isinf(a_) || std::isinf(b_)) {
93 method_ = DEGENERATE_SMALL;
94 x_ = inverted_ ? result_type(1) : result_type(0);
95 }
96 return;
97 }
98 if (a_ >= ThresholdForLargeA()) {
99 method_ = DEGENERATE_LARGE;
100 // Note: on PPC for long double, evaluating
101 // `std::numeric_limits::max() / ThresholdForLargeA` results in NaN.
102 result_type r = a_ / b_;
103 x_ = (inverted_ ? result_type(1) : r) / (1 + r);
104 return;
105 }
106 x_ = a_ + b_;
107 log_x_ = std::log(x_);
108 if (a_ <= 1) {
109 method_ = CHENG_BA;
110 y_ = result_type(1) / a_;
111 gamma_ = a_ + a_;
112 return;
113 }
114 method_ = CHENG_BB;
115 result_type r = (a_ - 1) / (b_ - 1);
116 y_ = std::sqrt((1 + r) / (b_ * r * 2 - r + 1));
117 gamma_ = a_ + result_type(1) / y_;
118 }
119
alpha()120 result_type alpha() const { return alpha_; }
beta()121 result_type beta() const { return beta_; }
122
123 friend bool operator==(const param_type& a, const param_type& b) {
124 return a.alpha_ == b.alpha_ && a.beta_ == b.beta_;
125 }
126
127 friend bool operator!=(const param_type& a, const param_type& b) {
128 return !(a == b);
129 }
130
131 private:
132 friend class beta_distribution;
133
134 #ifdef _MSC_VER
135 // MSVC does not have constexpr implementations for std::log and std::exp
136 // so they are computed at runtime.
137 #define ABSL_RANDOM_INTERNAL_LOG_EXP_CONSTEXPR
138 #else
139 #define ABSL_RANDOM_INTERNAL_LOG_EXP_CONSTEXPR constexpr
140 #endif
141
142 // The threshold for whether std::exp(1/a) is finite.
143 // Note that this value is quite large, and a smaller a_ is NOT abnormal.
144 static ABSL_RANDOM_INTERNAL_LOG_EXP_CONSTEXPR result_type
ThresholdForSmallA()145 ThresholdForSmallA() {
146 return result_type(1) /
147 std::log((std::numeric_limits<result_type>::max)());
148 }
149
150 // The threshold for whether a * std::log(a) is finite.
151 static ABSL_RANDOM_INTERNAL_LOG_EXP_CONSTEXPR result_type
ThresholdForLargeA()152 ThresholdForLargeA() {
153 return std::exp(
154 std::log((std::numeric_limits<result_type>::max)()) -
155 std::log(std::log((std::numeric_limits<result_type>::max)())) -
156 ThresholdPadding());
157 }
158
159 #undef ABSL_RANDOM_INTERNAL_LOG_EXP_CONSTEXPR
160
161 // Pad the threshold for large A for long double on PPC. This is done via a
162 // template specialization below.
ThresholdPadding()163 static constexpr result_type ThresholdPadding() { return 0; }
164
165 enum Method {
166 JOEHNK, // Uses algorithm Joehnk
167 CHENG_BA, // Uses algorithm BA in Cheng
168 CHENG_BB, // Uses algorithm BB in Cheng
169
170 // Note: See also:
171 // Hung et al. Evaluation of beta generation algorithms. Communications
172 // in Statistics-Simulation and Computation 38.4 (2009): 750-770.
173 // especially:
174 // Zechner, Heinz, and Ernst Stadlober. Generating beta variates via
175 // patchwork rejection. Computing 50.1 (1993): 1-18.
176
177 DEGENERATE_SMALL, // a_ is abnormally small.
178 DEGENERATE_LARGE, // a_ is abnormally large.
179 };
180
181 result_type alpha_;
182 result_type beta_;
183
184 result_type a_; // the smaller of {alpha, beta}, or 1.0/alpha_ in JOEHNK
185 result_type b_; // the larger of {alpha, beta}, or 1.0/beta_ in JOEHNK
186 result_type x_; // alpha + beta, or the result in degenerate cases
187 result_type log_x_; // log(x_)
188 result_type y_; // "beta" in Cheng
189 result_type gamma_; // "gamma" in Cheng
190
191 Method method_;
192
193 // Placing this last for optimal alignment.
194 // Whether alpha_ != a_, i.e. true iff alpha_ > beta_.
195 bool inverted_;
196
197 static_assert(std::is_floating_point<RealType>::value,
198 "Class-template absl::beta_distribution<> must be "
199 "parameterized using a floating-point type.");
200 };
201
beta_distribution()202 beta_distribution() : beta_distribution(1) {}
203
204 explicit beta_distribution(result_type alpha, result_type beta = 1)
param_(alpha,beta)205 : param_(alpha, beta) {}
206
beta_distribution(const param_type & p)207 explicit beta_distribution(const param_type& p) : param_(p) {}
208
reset()209 void reset() {}
210
211 // Generating functions
212 template <typename URBG>
operator()213 result_type operator()(URBG& g) { // NOLINT(runtime/references)
214 return (*this)(g, param_);
215 }
216
217 template <typename URBG>
218 result_type operator()(URBG& g, // NOLINT(runtime/references)
219 const param_type& p);
220
param()221 param_type param() const { return param_; }
param(const param_type & p)222 void param(const param_type& p) { param_ = p; }
223
result_type(min)224 result_type(min)() const { return 0; }
result_type(max)225 result_type(max)() const { return 1; }
226
alpha()227 result_type alpha() const { return param_.alpha(); }
beta()228 result_type beta() const { return param_.beta(); }
229
230 friend bool operator==(const beta_distribution& a,
231 const beta_distribution& b) {
232 return a.param_ == b.param_;
233 }
234 friend bool operator!=(const beta_distribution& a,
235 const beta_distribution& b) {
236 return a.param_ != b.param_;
237 }
238
239 private:
240 template <typename URBG>
241 result_type AlgorithmJoehnk(URBG& g, // NOLINT(runtime/references)
242 const param_type& p);
243
244 template <typename URBG>
245 result_type AlgorithmCheng(URBG& g, // NOLINT(runtime/references)
246 const param_type& p);
247
248 template <typename URBG>
DegenerateCase(URBG & g,const param_type & p)249 result_type DegenerateCase(URBG& g, // NOLINT(runtime/references)
250 const param_type& p) {
251 if (p.method_ == param_type::DEGENERATE_SMALL && p.alpha_ == p.beta_) {
252 // Returns 0 or 1 with equal probability.
253 random_internal::FastUniformBits<uint8_t> fast_u8;
254 return static_cast<result_type>((fast_u8(g) & 0x10) !=
255 0); // pick any single bit.
256 }
257 return p.x_;
258 }
259
260 param_type param_;
261 random_internal::FastUniformBits<uint64_t> fast_u64_;
262 };
263
264 #if defined(__powerpc64__) || defined(__PPC64__) || defined(__powerpc__) || \
265 defined(__ppc__) || defined(__PPC__)
266 // PPC needs a more stringent boundary for long double.
267 template <>
268 constexpr long double
ThresholdPadding()269 beta_distribution<long double>::param_type::ThresholdPadding() {
270 return 10;
271 }
272 #endif
273
274 template <typename RealType>
275 template <typename URBG>
276 typename beta_distribution<RealType>::result_type
AlgorithmJoehnk(URBG & g,const param_type & p)277 beta_distribution<RealType>::AlgorithmJoehnk(
278 URBG& g, // NOLINT(runtime/references)
279 const param_type& p) {
280 using random_internal::GeneratePositiveTag;
281 using random_internal::GenerateRealFromBits;
282 using real_type =
283 absl::conditional_t<std::is_same<RealType, float>::value, float, double>;
284
285 // Based on Joehnk, M. D. Erzeugung von betaverteilten und gammaverteilten
286 // Zufallszahlen. Metrika 8.1 (1964): 5-15.
287 // This method is described in Knuth, Vol 2 (Third Edition), pp 134.
288
289 result_type u, v, x, y, z;
290 for (;;) {
291 u = GenerateRealFromBits<real_type, GeneratePositiveTag, false>(
292 fast_u64_(g));
293 v = GenerateRealFromBits<real_type, GeneratePositiveTag, false>(
294 fast_u64_(g));
295
296 // Direct method. std::pow is slow for float, so rely on the optimizer to
297 // remove the std::pow() path for that case.
298 if (!std::is_same<float, result_type>::value) {
299 x = std::pow(u, p.a_);
300 y = std::pow(v, p.b_);
301 z = x + y;
302 if (z > 1) {
303 // Reject if and only if `x + y > 1.0`
304 continue;
305 }
306 if (z > 0) {
307 // When both alpha and beta are small, x and y are both close to 0, so
308 // divide by (x+y) directly may result in nan.
309 return x / z;
310 }
311 }
312
313 // Log transform.
314 // x = log( pow(u, p.a_) ), y = log( pow(v, p.b_) )
315 // since u, v <= 1.0, x, y < 0.
316 x = std::log(u) * p.a_;
317 y = std::log(v) * p.b_;
318 if (!std::isfinite(x) || !std::isfinite(y)) {
319 continue;
320 }
321 // z = log( pow(u, a) + pow(v, b) )
322 z = x > y ? (x + std::log(1 + std::exp(y - x)))
323 : (y + std::log(1 + std::exp(x - y)));
324 // Reject iff log(x+y) > 0.
325 if (z > 0) {
326 continue;
327 }
328 return std::exp(x - z);
329 }
330 }
331
332 template <typename RealType>
333 template <typename URBG>
334 typename beta_distribution<RealType>::result_type
AlgorithmCheng(URBG & g,const param_type & p)335 beta_distribution<RealType>::AlgorithmCheng(
336 URBG& g, // NOLINT(runtime/references)
337 const param_type& p) {
338 using random_internal::GeneratePositiveTag;
339 using random_internal::GenerateRealFromBits;
340 using real_type =
341 absl::conditional_t<std::is_same<RealType, float>::value, float, double>;
342
343 // Based on Cheng, Russell CH. Generating beta variates with nonintegral
344 // shape parameters. Communications of the ACM 21.4 (1978): 317-322.
345 // (https://dl.acm.org/citation.cfm?id=359482).
346 static constexpr result_type kLogFour =
347 result_type(1.3862943611198906188344642429163531361); // log(4)
348 static constexpr result_type kS =
349 result_type(2.6094379124341003746007593332261876); // 1+log(5)
350
351 const bool use_algorithm_ba = (p.method_ == param_type::CHENG_BA);
352 result_type u1, u2, v, w, z, r, s, t, bw_inv, lhs;
353 for (;;) {
354 u1 = GenerateRealFromBits<real_type, GeneratePositiveTag, false>(
355 fast_u64_(g));
356 u2 = GenerateRealFromBits<real_type, GeneratePositiveTag, false>(
357 fast_u64_(g));
358 v = p.y_ * std::log(u1 / (1 - u1));
359 w = p.a_ * std::exp(v);
360 bw_inv = result_type(1) / (p.b_ + w);
361 r = p.gamma_ * v - kLogFour;
362 s = p.a_ + r - w;
363 z = u1 * u1 * u2;
364 if (!use_algorithm_ba && s + kS >= 5 * z) {
365 break;
366 }
367 t = std::log(z);
368 if (!use_algorithm_ba && s >= t) {
369 break;
370 }
371 lhs = p.x_ * (p.log_x_ + std::log(bw_inv)) + r;
372 if (lhs >= t) {
373 break;
374 }
375 }
376 return p.inverted_ ? (1 - w * bw_inv) : w * bw_inv;
377 }
378
379 template <typename RealType>
380 template <typename URBG>
381 typename beta_distribution<RealType>::result_type
operator()382 beta_distribution<RealType>::operator()(URBG& g, // NOLINT(runtime/references)
383 const param_type& p) {
384 switch (p.method_) {
385 case param_type::JOEHNK:
386 return AlgorithmJoehnk(g, p);
387 case param_type::CHENG_BA:
388 ABSL_FALLTHROUGH_INTENDED;
389 case param_type::CHENG_BB:
390 return AlgorithmCheng(g, p);
391 default:
392 return DegenerateCase(g, p);
393 }
394 }
395
396 template <typename CharT, typename Traits, typename RealType>
397 std::basic_ostream<CharT, Traits>& operator<<(
398 std::basic_ostream<CharT, Traits>& os, // NOLINT(runtime/references)
399 const beta_distribution<RealType>& x) {
400 auto saver = random_internal::make_ostream_state_saver(os);
401 os.precision(random_internal::stream_precision_helper<RealType>::kPrecision);
402 os << x.alpha() << os.fill() << x.beta();
403 return os;
404 }
405
406 template <typename CharT, typename Traits, typename RealType>
407 std::basic_istream<CharT, Traits>& operator>>(
408 std::basic_istream<CharT, Traits>& is, // NOLINT(runtime/references)
409 beta_distribution<RealType>& x) { // NOLINT(runtime/references)
410 using result_type = typename beta_distribution<RealType>::result_type;
411 using param_type = typename beta_distribution<RealType>::param_type;
412 result_type alpha, beta;
413
414 auto saver = random_internal::make_istream_state_saver(is);
415 alpha = random_internal::read_floating_point<result_type>(is);
416 if (is.fail()) return is;
417 beta = random_internal::read_floating_point<result_type>(is);
418 if (!is.fail()) {
419 x.param(param_type(alpha, beta));
420 }
421 return is;
422 }
423
424 ABSL_NAMESPACE_END
425 } // namespace absl
426
427 #endif // ABSL_RANDOM_BETA_DISTRIBUTION_H_
428