blob: 18ff248477b5bd7e3e43d2449981826846d54ad4 [file] [log] [blame]
Austin Schuh36244a12019-09-21 17:52:38 -07001// 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// -----------------------------------------------------------------------------
16// File: distributions.h
17// -----------------------------------------------------------------------------
18//
19// This header defines functions representing distributions, which you use in
20// combination with an Abseil random bit generator to produce random values
21// according to the rules of that distribution.
22//
23// The Abseil random library defines the following distributions within this
24// file:
25//
26// * `absl::Uniform` for uniform (constant) distributions having constant
27// probability
28// * `absl::Bernoulli` for discrete distributions having exactly two outcomes
29// * `absl::Beta` for continuous distributions parameterized through two
30// free parameters
31// * `absl::Exponential` for discrete distributions of events occurring
32// continuously and independently at a constant average rate
33// * `absl::Gaussian` (also known as "normal distributions") for continuous
34// distributions using an associated quadratic function
35// * `absl::LogUniform` for continuous uniform distributions where the log
36// to the given base of all values is uniform
37// * `absl::Poisson` for discrete probability distributions that express the
38// probability of a given number of events occurring within a fixed interval
39// * `absl::Zipf` for discrete probability distributions commonly used for
40// modelling of rare events
41//
42// Prefer use of these distribution function classes over manual construction of
43// your own distribution classes, as it allows library maintainers greater
44// flexibility to change the underlying implementation in the future.
45
46#ifndef ABSL_RANDOM_DISTRIBUTIONS_H_
47#define ABSL_RANDOM_DISTRIBUTIONS_H_
48
49#include <algorithm>
50#include <cmath>
51#include <limits>
52#include <random>
53#include <type_traits>
54
55#include "absl/base/internal/inline_variable.h"
56#include "absl/random/bernoulli_distribution.h"
57#include "absl/random/beta_distribution.h"
58#include "absl/random/distribution_format_traits.h"
59#include "absl/random/exponential_distribution.h"
60#include "absl/random/gaussian_distribution.h"
61#include "absl/random/internal/distributions.h" // IWYU pragma: export
62#include "absl/random/internal/uniform_helper.h" // IWYU pragma: export
63#include "absl/random/log_uniform_int_distribution.h"
64#include "absl/random/poisson_distribution.h"
65#include "absl/random/uniform_int_distribution.h"
66#include "absl/random/uniform_real_distribution.h"
67#include "absl/random/zipf_distribution.h"
68
69namespace absl {
70
71ABSL_INTERNAL_INLINE_CONSTEXPR(IntervalClosedClosedTag, IntervalClosedClosed,
72 {});
73ABSL_INTERNAL_INLINE_CONSTEXPR(IntervalClosedClosedTag, IntervalClosed, {});
74ABSL_INTERNAL_INLINE_CONSTEXPR(IntervalClosedOpenTag, IntervalClosedOpen, {});
75ABSL_INTERNAL_INLINE_CONSTEXPR(IntervalOpenOpenTag, IntervalOpenOpen, {});
76ABSL_INTERNAL_INLINE_CONSTEXPR(IntervalOpenOpenTag, IntervalOpen, {});
77ABSL_INTERNAL_INLINE_CONSTEXPR(IntervalOpenClosedTag, IntervalOpenClosed, {});
78
79// -----------------------------------------------------------------------------
80// absl::Uniform<T>(tag, bitgen, lo, hi)
81// -----------------------------------------------------------------------------
82//
83// `absl::Uniform()` produces random values of type `T` uniformly distributed in
84// a defined interval {lo, hi}. The interval `tag` defines the type of interval
85// which should be one of the following possible values:
86//
87// * `absl::IntervalOpenOpen`
88// * `absl::IntervalOpenClosed`
89// * `absl::IntervalClosedOpen`
90// * `absl::IntervalClosedClosed`
91//
92// where "open" refers to an exclusive value (excluded) from the output, while
93// "closed" refers to an inclusive value (included) from the output.
94//
95// In the absence of an explicit return type `T`, `absl::Uniform()` will deduce
96// the return type based on the provided endpoint arguments {A lo, B hi}.
97// Given these endpoints, one of {A, B} will be chosen as the return type, if
98// a type can be implicitly converted into the other in a lossless way. The
99// lack of any such implcit conversion between {A, B} will produce a
100// compile-time error
101//
102// See https://en.wikipedia.org/wiki/Uniform_distribution_(continuous)
103//
104// Example:
105//
106// absl::BitGen bitgen;
107//
108// // Produce a random float value between 0.0 and 1.0, inclusive
109// auto x = absl::Uniform(absl::IntervalClosedClosed, bitgen, 0.0f, 1.0f);
110//
111// // The most common interval of `absl::IntervalClosedOpen` is available by
112// // default:
113//
114// auto x = absl::Uniform(bitgen, 0.0f, 1.0f);
115//
116// // Return-types are typically inferred from the arguments, however callers
117// // can optionally provide an explicit return-type to the template.
118//
119// auto x = absl::Uniform<float>(bitgen, 0, 1);
120//
121template <typename R = void, typename TagType, typename URBG>
122typename absl::enable_if_t<!std::is_same<R, void>::value, R> //
123Uniform(TagType tag,
124 URBG&& urbg, // NOLINT(runtime/references)
125 R lo, R hi) {
126 using gen_t = absl::decay_t<URBG>;
127 return random_internal::UniformImpl<R, TagType, gen_t>(tag, urbg, lo, hi);
128}
129
130// absl::Uniform<T>(bitgen, lo, hi)
131//
132// Overload of `Uniform()` using the default closed-open interval of [lo, hi),
133// and returning values of type `T`
134template <typename R = void, typename URBG>
135typename absl::enable_if_t<!std::is_same<R, void>::value, R> //
136Uniform(URBG&& urbg, // NOLINT(runtime/references)
137 R lo, R hi) {
138 constexpr auto tag = absl::IntervalClosedOpen;
139 using tag_t = decltype(tag);
140 using gen_t = absl::decay_t<URBG>;
141
142 return random_internal::UniformImpl<R, tag_t, gen_t>(tag, urbg, lo, hi);
143}
144
145// absl::Uniform(tag, bitgen, lo, hi)
146//
147// Overload of `Uniform()` using different (but compatible) lo, hi types. Note
148// that a compile-error will result if the return type cannot be deduced
149// correctly from the passed types.
150template <typename R = void, typename TagType, typename URBG, typename A,
151 typename B>
152typename absl::enable_if_t<std::is_same<R, void>::value,
153 random_internal::uniform_inferred_return_t<A, B>>
154Uniform(TagType tag,
155 URBG&& urbg, // NOLINT(runtime/references)
156 A lo, B hi) {
157 using gen_t = absl::decay_t<URBG>;
158 using return_t = typename random_internal::uniform_inferred_return_t<A, B>;
159
160 return random_internal::UniformImpl<return_t, TagType, gen_t>(tag, urbg, lo,
161 hi);
162}
163
164// absl::Uniform(bitgen, lo, hi)
165//
166// Overload of `Uniform()` using different (but compatible) lo, hi types and the
167// default closed-open interval of [lo, hi). Note that a compile-error will
168// result if the return type cannot be deduced correctly from the passed types.
169template <typename R = void, typename URBG, typename A, typename B>
170typename absl::enable_if_t<std::is_same<R, void>::value,
171 random_internal::uniform_inferred_return_t<A, B>>
172Uniform(URBG&& urbg, // NOLINT(runtime/references)
173 A lo, B hi) {
174 constexpr auto tag = absl::IntervalClosedOpen;
175 using tag_t = decltype(tag);
176 using gen_t = absl::decay_t<URBG>;
177 using return_t = typename random_internal::uniform_inferred_return_t<A, B>;
178
179 return random_internal::UniformImpl<return_t, tag_t, gen_t>(tag, urbg, lo,
180 hi);
181}
182
183// absl::Uniform<unsigned T>(bitgen)
184//
185// Overload of Uniform() using the minimum and maximum values of a given type
186// `T` (which must be unsigned), returning a value of type `unsigned T`
187template <typename R, typename URBG>
188typename absl::enable_if_t<!std::is_signed<R>::value, R> //
189Uniform(URBG&& urbg) { // NOLINT(runtime/references)
190 constexpr auto tag = absl::IntervalClosedClosed;
191 constexpr auto lo = std::numeric_limits<R>::lowest();
192 constexpr auto hi = (std::numeric_limits<R>::max)();
193 using tag_t = decltype(tag);
194 using gen_t = absl::decay_t<URBG>;
195
196 return random_internal::UniformImpl<R, tag_t, gen_t>(tag, urbg, lo, hi);
197}
198
199// -----------------------------------------------------------------------------
200// absl::Bernoulli(bitgen, p)
201// -----------------------------------------------------------------------------
202//
203// `absl::Bernoulli` produces a random boolean value, with probability `p`
204// (where 0.0 <= p <= 1.0) equaling `true`.
205//
206// Prefer `absl::Bernoulli` to produce boolean values over other alternatives
207// such as comparing an `absl::Uniform()` value to a specific output.
208//
209// See https://en.wikipedia.org/wiki/Bernoulli_distribution
210//
211// Example:
212//
213// absl::BitGen bitgen;
214// ...
215// if (absl::Bernoulli(bitgen, 1.0/3721.0)) {
216// std::cout << "Asteroid field navigation successful.";
217// }
218//
219template <typename URBG>
220bool Bernoulli(URBG&& urbg, // NOLINT(runtime/references)
221 double p) {
222 using gen_t = absl::decay_t<URBG>;
223 using distribution_t = absl::bernoulli_distribution;
224 using format_t = random_internal::DistributionFormatTraits<distribution_t>;
225
226 return random_internal::DistributionCaller<gen_t>::template Call<
227 distribution_t, format_t>(&urbg, p);
228}
229
230// -----------------------------------------------------------------------------
231// absl::Beta<T>(bitgen, alpha, beta)
232// -----------------------------------------------------------------------------
233//
234// `absl::Beta` produces a floating point number distributed in the closed
235// interval [0,1] and parameterized by two values `alpha` and `beta` as per a
236// Beta distribution. `T` must be a floating point type, but may be inferred
237// from the types of `alpha` and `beta`.
238//
239// See https://en.wikipedia.org/wiki/Beta_distribution.
240//
241// Example:
242//
243// absl::BitGen bitgen;
244// ...
245// double sample = absl::Beta(bitgen, 3.0, 2.0);
246//
247template <typename RealType, typename URBG>
248RealType Beta(URBG&& urbg, // NOLINT(runtime/references)
249 RealType alpha, RealType beta) {
250 static_assert(
251 std::is_floating_point<RealType>::value,
252 "Template-argument 'RealType' must be a floating-point type, in "
253 "absl::Beta<RealType, URBG>(...)");
254
255 using gen_t = absl::decay_t<URBG>;
256 using distribution_t = typename absl::beta_distribution<RealType>;
257 using format_t = random_internal::DistributionFormatTraits<distribution_t>;
258
259 return random_internal::DistributionCaller<gen_t>::template Call<
260 distribution_t, format_t>(&urbg, alpha, beta);
261}
262
263// -----------------------------------------------------------------------------
264// absl::Exponential<T>(bitgen, lambda = 1)
265// -----------------------------------------------------------------------------
266//
267// `absl::Exponential` produces a floating point number for discrete
268// distributions of events occurring continuously and independently at a
269// constant average rate. `T` must be a floating point type, but may be inferred
270// from the type of `lambda`.
271//
272// See https://en.wikipedia.org/wiki/Exponential_distribution.
273//
274// Example:
275//
276// absl::BitGen bitgen;
277// ...
278// double call_length = absl::Exponential(bitgen, 7.0);
279//
280template <typename RealType, typename URBG>
281RealType Exponential(URBG&& urbg, // NOLINT(runtime/references)
282 RealType lambda = 1) {
283 static_assert(
284 std::is_floating_point<RealType>::value,
285 "Template-argument 'RealType' must be a floating-point type, in "
286 "absl::Exponential<RealType, URBG>(...)");
287
288 using gen_t = absl::decay_t<URBG>;
289 using distribution_t = typename absl::exponential_distribution<RealType>;
290 using format_t = random_internal::DistributionFormatTraits<distribution_t>;
291
292 return random_internal::DistributionCaller<gen_t>::template Call<
293 distribution_t, format_t>(&urbg, lambda);
294}
295
296// -----------------------------------------------------------------------------
297// absl::Gaussian<T>(bitgen, mean = 0, stddev = 1)
298// -----------------------------------------------------------------------------
299//
300// `absl::Gaussian` produces a floating point number selected from the Gaussian
301// (ie. "Normal") distribution. `T` must be a floating point type, but may be
302// inferred from the types of `mean` and `stddev`.
303//
304// See https://en.wikipedia.org/wiki/Normal_distribution
305//
306// Example:
307//
308// absl::BitGen bitgen;
309// ...
310// double giraffe_height = absl::Gaussian(bitgen, 16.3, 3.3);
311//
312template <typename RealType, typename URBG>
313RealType Gaussian(URBG&& urbg, // NOLINT(runtime/references)
314 RealType mean = 0, RealType stddev = 1) {
315 static_assert(
316 std::is_floating_point<RealType>::value,
317 "Template-argument 'RealType' must be a floating-point type, in "
318 "absl::Gaussian<RealType, URBG>(...)");
319
320 using gen_t = absl::decay_t<URBG>;
321 using distribution_t = typename absl::gaussian_distribution<RealType>;
322 using format_t = random_internal::DistributionFormatTraits<distribution_t>;
323
324 return random_internal::DistributionCaller<gen_t>::template Call<
325 distribution_t, format_t>(&urbg, mean, stddev);
326}
327
328// -----------------------------------------------------------------------------
329// absl::LogUniform<T>(bitgen, lo, hi, base = 2)
330// -----------------------------------------------------------------------------
331//
332// `absl::LogUniform` produces random values distributed where the log to a
333// given base of all values is uniform in a closed interval [lo, hi]. `T` must
334// be an integral type, but may be inferred from the types of `lo` and `hi`.
335//
336// I.e., `LogUniform(0, n, b)` is uniformly distributed across buckets
337// [0], [1, b-1], [b, b^2-1] .. [b^(k-1), (b^k)-1] .. [b^floor(log(n, b)), n]
338// and is uniformly distributed within each bucket.
339//
340// The resulting probability density is inversely related to bucket size, though
341// values in the final bucket may be more likely than previous values. (In the
342// extreme case where n = b^i the final value will be tied with zero as the most
343// probable result.
344//
345// If `lo` is nonzero then this distribution is shifted to the desired interval,
346// so LogUniform(lo, hi, b) is equivalent to LogUniform(0, hi-lo, b)+lo.
347//
348// See http://ecolego.facilia.se/ecolego/show/Log-Uniform%20Distribution
349//
350// Example:
351//
352// absl::BitGen bitgen;
353// ...
354// int v = absl::LogUniform(bitgen, 0, 1000);
355//
356template <typename IntType, typename URBG>
357IntType LogUniform(URBG&& urbg, // NOLINT(runtime/references)
358 IntType lo, IntType hi, IntType base = 2) {
359 static_assert(std::is_integral<IntType>::value,
360 "Template-argument 'IntType' must be an integral type, in "
361 "absl::LogUniform<IntType, URBG>(...)");
362
363 using gen_t = absl::decay_t<URBG>;
364 using distribution_t = typename absl::log_uniform_int_distribution<IntType>;
365 using format_t = random_internal::DistributionFormatTraits<distribution_t>;
366
367 return random_internal::DistributionCaller<gen_t>::template Call<
368 distribution_t, format_t>(&urbg, lo, hi, base);
369}
370
371// -----------------------------------------------------------------------------
372// absl::Poisson<T>(bitgen, mean = 1)
373// -----------------------------------------------------------------------------
374//
375// `absl::Poisson` produces discrete probabilities for a given number of events
376// occurring within a fixed interval within the closed interval [0, max]. `T`
377// must be an integral type.
378//
379// See https://en.wikipedia.org/wiki/Poisson_distribution
380//
381// Example:
382//
383// absl::BitGen bitgen;
384// ...
385// int requests_per_minute = absl::Poisson<int>(bitgen, 3.2);
386//
387template <typename IntType, typename URBG>
388IntType Poisson(URBG&& urbg, // NOLINT(runtime/references)
389 double mean = 1.0) {
390 static_assert(std::is_integral<IntType>::value,
391 "Template-argument 'IntType' must be an integral type, in "
392 "absl::Poisson<IntType, URBG>(...)");
393
394 using gen_t = absl::decay_t<URBG>;
395 using distribution_t = typename absl::poisson_distribution<IntType>;
396 using format_t = random_internal::DistributionFormatTraits<distribution_t>;
397
398 return random_internal::DistributionCaller<gen_t>::template Call<
399 distribution_t, format_t>(&urbg, mean);
400}
401
402// -----------------------------------------------------------------------------
403// absl::Zipf<T>(bitgen, hi = max, q = 2, v = 1)
404// -----------------------------------------------------------------------------
405//
406// `absl::Zipf` produces discrete probabilities commonly used for modelling of
407// rare events over the closed interval [0, hi]. The parameters `v` and `q`
408// determine the skew of the distribution. `T` must be an integral type, but
409// may be inferred from the type of `hi`.
410//
411// See http://mathworld.wolfram.com/ZipfDistribution.html
412//
413// Example:
414//
415// absl::BitGen bitgen;
416// ...
417// int term_rank = absl::Zipf<int>(bitgen);
418//
419template <typename IntType, typename URBG>
420IntType Zipf(URBG&& urbg, // NOLINT(runtime/references)
421 IntType hi = (std::numeric_limits<IntType>::max)(), double q = 2.0,
422 double v = 1.0) {
423 static_assert(std::is_integral<IntType>::value,
424 "Template-argument 'IntType' must be an integral type, in "
425 "absl::Zipf<IntType, URBG>(...)");
426
427 using gen_t = absl::decay_t<URBG>;
428 using distribution_t = typename absl::zipf_distribution<IntType>;
429 using format_t = random_internal::DistributionFormatTraits<distribution_t>;
430
431 return random_internal::DistributionCaller<gen_t>::template Call<
432 distribution_t, format_t>(&urbg, hi, q, v);
433}
434
435} // namespace absl
436
437#endif // ABSL_RANDOM_DISTRIBUTIONS_H_