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_BETA_DISTRIBUTION_H_
16 #define ABSL_RANDOM_BETA_DISTRIBUTION_H_
23 #include <type_traits>
25 #include "absl/random/internal/distribution_impl.h"
26 #include "absl/random/internal/fast_uniform_bits.h"
27 #include "absl/random/internal/fastmath.h"
28 #include "absl/random/internal/iostream_state_saver.h"
32 // absl::beta_distribution:
33 // Generate a floating-point variate conforming to a Beta distribution:
34 // pdf(x) \propto x^(alpha-1) * (1-x)^(beta-1),
35 // where the params alpha and beta are both strictly positive real values.
37 // The support is the open interval (0, 1), but the return value might be equal
38 // to 0 or 1, due to numerical errors when alpha and beta are very different.
40 // Usage note: One usage is that alpha and beta are counts of number of
41 // successes and failures. When the total number of trials are large, consider
42 // approximating a beta distribution with a Gaussian distribution with the same
43 // mean and variance. One could use the skewness, which depends only on the
44 // smaller of alpha and beta when the number of trials are sufficiently large,
45 // to quantify how far a beta distribution is from the normal distribution.
46 template <typename RealType = double>
47 class beta_distribution {
49 using result_type = RealType;
53 using distribution_type = beta_distribution;
55 explicit param_type(result_type alpha, result_type beta)
56 : alpha_(alpha), beta_(beta) {
59 assert(alpha <= (std::numeric_limits<result_type>::max)());
60 assert(beta <= (std::numeric_limits<result_type>::max)());
61 if (alpha == 0 || beta == 0) {
62 method_ = DEGENERATE_SMALL;
63 x_ = (alpha >= beta) ? 1 : 0;
66 // a_ = min(beta, alpha), b_ = max(beta, alpha).
76 if (a_ <= 1 && b_ >= ThresholdForLargeA()) {
77 method_ = DEGENERATE_SMALL;
78 x_ = inverted_ ? result_type(1) : result_type(0);
81 // For threshold values, see also:
82 // Evaluation of Beta Generation Algorithms, Ying-Chao Hung, et. al.
84 if ((b_ < 1.0 && a_ + b_ <= 1.2) || a_ <= ThresholdForSmallA()) {
85 // Choose Joehnk over Cheng when it's faster or when Cheng encounters
88 a_ = result_type(1) / alpha_;
89 b_ = result_type(1) / beta_;
90 if (std::isinf(a_) || std::isinf(b_)) {
91 method_ = DEGENERATE_SMALL;
92 x_ = inverted_ ? result_type(1) : result_type(0);
96 if (a_ >= ThresholdForLargeA()) {
97 method_ = DEGENERATE_LARGE;
98 // Note: on PPC for long double, evaluating
99 // `std::numeric_limits::max() / ThresholdForLargeA` results in NaN.
100 result_type r = a_ / b_;
101 x_ = (inverted_ ? result_type(1) : r) / (1 + r);
105 log_x_ = std::log(x_);
108 y_ = result_type(1) / a_;
113 result_type r = (a_ - 1) / (b_ - 1);
114 y_ = std::sqrt((1 + r) / (b_ * r * 2 - r + 1));
115 gamma_ = a_ + result_type(1) / y_;
118 result_type alpha() const { return alpha_; }
119 result_type beta() const { return beta_; }
121 friend bool operator==(const param_type& a, const param_type& b) {
122 return a.alpha_ == b.alpha_ && a.beta_ == b.beta_;
125 friend bool operator!=(const param_type& a, const param_type& b) {
130 friend class beta_distribution;
133 // MSVC does not have constexpr implementations for std::log and std::exp
134 // so they are computed at runtime.
135 #define ABSL_RANDOM_INTERNAL_LOG_EXP_CONSTEXPR
137 #define ABSL_RANDOM_INTERNAL_LOG_EXP_CONSTEXPR constexpr
140 // The threshold for whether std::exp(1/a) is finite.
141 // Note that this value is quite large, and a smaller a_ is NOT abnormal.
142 static ABSL_RANDOM_INTERNAL_LOG_EXP_CONSTEXPR result_type
143 ThresholdForSmallA() {
144 return result_type(1) /
145 std::log((std::numeric_limits<result_type>::max)());
148 // The threshold for whether a * std::log(a) is finite.
149 static ABSL_RANDOM_INTERNAL_LOG_EXP_CONSTEXPR result_type
150 ThresholdForLargeA() {
152 std::log((std::numeric_limits<result_type>::max)()) -
153 std::log(std::log((std::numeric_limits<result_type>::max)())) -
157 #undef ABSL_RANDOM_INTERNAL_LOG_EXP_CONSTEXPR
159 // Pad the threshold for large A for long double on PPC. This is done via a
160 // template specialization below.
161 static constexpr result_type ThresholdPadding() { return 0; }
164 JOEHNK, // Uses algorithm Joehnk
165 CHENG_BA, // Uses algorithm BA in Cheng
166 CHENG_BB, // Uses algorithm BB in Cheng
169 // Hung et al. Evaluation of beta generation algorithms. Communications
170 // in Statistics-Simulation and Computation 38.4 (2009): 750-770.
172 // Zechner, Heinz, and Ernst Stadlober. Generating beta variates via
173 // patchwork rejection. Computing 50.1 (1993): 1-18.
175 DEGENERATE_SMALL, // a_ is abnormally small.
176 DEGENERATE_LARGE, // a_ is abnormally large.
182 result_type a_; // the smaller of {alpha, beta}, or 1.0/alpha_ in JOEHNK
183 result_type b_; // the larger of {alpha, beta}, or 1.0/beta_ in JOEHNK
184 result_type x_; // alpha + beta, or the result in degenerate cases
185 result_type log_x_; // log(x_)
186 result_type y_; // "beta" in Cheng
187 result_type gamma_; // "gamma" in Cheng
191 // Placing this last for optimal alignment.
192 // Whether alpha_ != a_, i.e. true iff alpha_ > beta_.
195 static_assert(std::is_floating_point<RealType>::value,
196 "Class-template absl::beta_distribution<> must be "
197 "parameterized using a floating-point type.");
200 beta_distribution() : beta_distribution(1) {}
202 explicit beta_distribution(result_type alpha, result_type beta = 1)
203 : param_(alpha, beta) {}
205 explicit beta_distribution(const param_type& p) : param_(p) {}
209 // Generating functions
210 template <typename URBG>
211 result_type operator()(URBG& g) { // NOLINT(runtime/references)
212 return (*this)(g, param_);
215 template <typename URBG>
216 result_type operator()(URBG& g, // NOLINT(runtime/references)
217 const param_type& p);
219 param_type param() const { return param_; }
220 void param(const param_type& p) { param_ = p; }
222 result_type(min)() const { return 0; }
223 result_type(max)() const { return 1; }
225 result_type alpha() const { return param_.alpha(); }
226 result_type beta() const { return param_.beta(); }
228 friend bool operator==(const beta_distribution& a,
229 const beta_distribution& b) {
230 return a.param_ == b.param_;
232 friend bool operator!=(const beta_distribution& a,
233 const beta_distribution& b) {
234 return a.param_ != b.param_;
238 template <typename URBG>
239 result_type AlgorithmJoehnk(URBG& g, // NOLINT(runtime/references)
240 const param_type& p);
242 template <typename URBG>
243 result_type AlgorithmCheng(URBG& g, // NOLINT(runtime/references)
244 const param_type& p);
246 template <typename URBG>
247 result_type DegenerateCase(URBG& g, // NOLINT(runtime/references)
248 const param_type& p) {
249 if (p.method_ == param_type::DEGENERATE_SMALL && p.alpha_ == p.beta_) {
250 // Returns 0 or 1 with equal probability.
251 random_internal::FastUniformBits<uint8_t> fast_u8;
252 return static_cast<result_type>((fast_u8(g) & 0x10) !=
253 0); // pick any single bit.
259 random_internal::FastUniformBits<uint64_t> fast_u64_;
262 #if defined(__powerpc64__) || defined(__PPC64__) || defined(__powerpc__) || \
263 defined(__ppc__) || defined(__PPC__)
264 // PPC needs a more stringent boundary for long double.
266 constexpr long double
267 beta_distribution<long double>::param_type::ThresholdPadding() {
272 template <typename RealType>
273 template <typename URBG>
274 typename beta_distribution<RealType>::result_type
275 beta_distribution<RealType>::AlgorithmJoehnk(
276 URBG& g, // NOLINT(runtime/references)
277 const param_type& p) {
278 // Based on Joehnk, M. D. Erzeugung von betaverteilten und gammaverteilten
279 // Zufallszahlen. Metrika 8.1 (1964): 5-15.
280 // This method is described in Knuth, Vol 2 (Third Edition), pp 134.
281 using RandU64ToReal = typename random_internal::RandU64ToReal<result_type>;
282 using random_internal::PositiveValueT;
283 result_type u, v, x, y, z;
285 u = RandU64ToReal::template Value<PositiveValueT, false>(fast_u64_(g));
286 v = RandU64ToReal::template Value<PositiveValueT, false>(fast_u64_(g));
288 // Direct method. std::pow is slow for float, so rely on the optimizer to
289 // remove the std::pow() path for that case.
290 if (!std::is_same<float, result_type>::value) {
291 x = std::pow(u, p.a_);
292 y = std::pow(v, p.b_);
295 // Reject if and only if `x + y > 1.0`
299 // When both alpha and beta are small, x and y are both close to 0, so
300 // divide by (x+y) directly may result in nan.
306 // x = log( pow(u, p.a_) ), y = log( pow(v, p.b_) )
307 // since u, v <= 1.0, x, y < 0.
308 x = std::log(u) * p.a_;
309 y = std::log(v) * p.b_;
310 if (!std::isfinite(x) || !std::isfinite(y)) {
313 // z = log( pow(u, a) + pow(v, b) )
314 z = x > y ? (x + std::log(1 + std::exp(y - x)))
315 : (y + std::log(1 + std::exp(x - y)));
316 // Reject iff log(x+y) > 0.
320 return std::exp(x - z);
324 template <typename RealType>
325 template <typename URBG>
326 typename beta_distribution<RealType>::result_type
327 beta_distribution<RealType>::AlgorithmCheng(
328 URBG& g, // NOLINT(runtime/references)
329 const param_type& p) {
330 // Based on Cheng, Russell CH. Generating beta variates with nonintegral
331 // shape parameters. Communications of the ACM 21.4 (1978): 317-322.
332 // (https://dl.acm.org/citation.cfm?id=359482).
333 using RandU64ToReal = typename random_internal::RandU64ToReal<result_type>;
334 using random_internal::PositiveValueT;
336 static constexpr result_type kLogFour =
337 result_type(1.3862943611198906188344642429163531361); // log(4)
338 static constexpr result_type kS =
339 result_type(2.6094379124341003746007593332261876); // 1+log(5)
341 const bool use_algorithm_ba = (p.method_ == param_type::CHENG_BA);
342 result_type u1, u2, v, w, z, r, s, t, bw_inv, lhs;
344 u1 = RandU64ToReal::template Value<PositiveValueT, false>(fast_u64_(g));
345 u2 = RandU64ToReal::template Value<PositiveValueT, false>(fast_u64_(g));
346 v = p.y_ * std::log(u1 / (1 - u1));
347 w = p.a_ * std::exp(v);
348 bw_inv = result_type(1) / (p.b_ + w);
349 r = p.gamma_ * v - kLogFour;
352 if (!use_algorithm_ba && s + kS >= 5 * z) {
356 if (!use_algorithm_ba && s >= t) {
359 lhs = p.x_ * (p.log_x_ + std::log(bw_inv)) + r;
364 return p.inverted_ ? (1 - w * bw_inv) : w * bw_inv;
367 template <typename RealType>
368 template <typename URBG>
369 typename beta_distribution<RealType>::result_type
370 beta_distribution<RealType>::operator()(URBG& g, // NOLINT(runtime/references)
371 const param_type& p) {
373 case param_type::JOEHNK:
374 return AlgorithmJoehnk(g, p);
375 case param_type::CHENG_BA:
376 ABSL_FALLTHROUGH_INTENDED;
377 case param_type::CHENG_BB:
378 return AlgorithmCheng(g, p);
380 return DegenerateCase(g, p);
384 template <typename CharT, typename Traits, typename RealType>
385 std::basic_ostream<CharT, Traits>& operator<<(
386 std::basic_ostream<CharT, Traits>& os, // NOLINT(runtime/references)
387 const beta_distribution<RealType>& x) {
388 auto saver = random_internal::make_ostream_state_saver(os);
389 os.precision(random_internal::stream_precision_helper<RealType>::kPrecision);
390 os << x.alpha() << os.fill() << x.beta();
394 template <typename CharT, typename Traits, typename RealType>
395 std::basic_istream<CharT, Traits>& operator>>(
396 std::basic_istream<CharT, Traits>& is, // NOLINT(runtime/references)
397 beta_distribution<RealType>& x) { // NOLINT(runtime/references)
398 using result_type = typename beta_distribution<RealType>::result_type;
399 using param_type = typename beta_distribution<RealType>::param_type;
400 result_type alpha, beta;
402 auto saver = random_internal::make_istream_state_saver(is);
403 alpha = random_internal::read_floating_point<result_type>(is);
404 if (is.fail()) return is;
405 beta = random_internal::read_floating_point<result_type>(is);
407 x.param(param_type(alpha, beta));
414 #endif // ABSL_RANDOM_BETA_DISTRIBUTION_H_