tvl-depot/absl/random/distributions.h
Abseil Team e9324d926a Export of internal Abseil changes.
--
7a6ff16a85beb730c172d5d25cf1b5e1be885c56 by Laramie Leavitt <lar@google.com>:

Internal change.

PiperOrigin-RevId: 254454546

--
ff8f9bafaefc26d451f576ea4a06d150aed63f6f by Andy Soffer <asoffer@google.com>:

Internal changes

PiperOrigin-RevId: 254451562

--
deefc5b651b479ce36f0b4ef203e119c0c8936f2 by CJ Johnson <johnsoncj@google.com>:

Account for subtracting unsigned values from the size of InlinedVector

PiperOrigin-RevId: 254450625

--
3c677316a27bcadc17e41957c809ca472d5fef14 by Andy Soffer <asoffer@google.com>:

Add C++17's std::make_from_tuple to absl/utility/utility.h

PiperOrigin-RevId: 254411573

--
4ee3536a918830eeec402a28fc31a62c7c90b940 by CJ Johnson <johnsoncj@google.com>:

Adds benchmark for the rest of the InlinedVector public API

PiperOrigin-RevId: 254408378

--
e5a21a00700ee83498ff1efbf649169756463ee4 by CJ Johnson <johnsoncj@google.com>:

Updates the definition of InlinedVector::shrink_to_fit() to be exception safe and adds exception safety tests for it.

PiperOrigin-RevId: 254401387

--
2ea82e72b86d82d78b4e4712a63a55981b53c64b by Laramie Leavitt <lar@google.com>:

Use absl::InsecureBitGen in place of std::mt19937
in tests absl/random/...distribution_test.cc

PiperOrigin-RevId: 254289444

--
fa099e02c413a7ffda732415e8105cad26a90337 by Andy Soffer <asoffer@google.com>:

Internal changes

PiperOrigin-RevId: 254286334

--
ce34b7f36933b30cfa35b9c9a5697a792b5666e4 by Andy Soffer <asoffer@google.com>:

Internal changes

PiperOrigin-RevId: 254273059

--
6f9c473da7c2090c2e85a37c5f00622e8a912a89 by Jorg Brown <jorg@google.com>:

Change absl::container_internal::CompressedTuple to instantiate its
internal Storage class with the name of the type it's holding, rather
than the name of the Tuple.  This is not an externally-visible change,
other than less compiler memory is used and less debug information is
generated.

PiperOrigin-RevId: 254269285

--
8bd3c186bf2fc0c55d8a2dd6f28a5327502c9fba by Andy Soffer <asoffer@google.com>:

Adding short-hand IntervalClosed for IntervalClosedClosed and IntervalOpen for
IntervalOpenOpen.

PiperOrigin-RevId: 254252419

--
ea957f99b6a04fccd42aa05605605f3b44b1ecfd by Abseil Team <absl-team@google.com>:

Do not directly use __SIZEOF_INT128__.

In order to avoid linker errors when building with clang-cl (__fixunsdfti, __udivti3 and __fixunssfti are undefined), this CL uses ABSL_HAVE_INTRINSIC_INT128 which is not defined for clang-cl.

PiperOrigin-RevId: 254250739

--
89ab385cd26b34d64130bce856253aaba96d2345 by Andy Soffer <asoffer@google.com>:

Internal changes

PiperOrigin-RevId: 254242321

--
cffc793d93eca6d6bdf7de733847b6ab4a255ae9 by CJ Johnson <johnsoncj@google.com>:

Adds benchmark for InlinedVector::reserve(size_type)

PiperOrigin-RevId: 254199226

--
c90c7a9fa3c8f0c9d5114036979548b055ea2f2a by Gennadiy Rozental <rogeeff@google.com>:

Import of CCTZ from GitHub.

PiperOrigin-RevId: 254072387

--
c4c388beae016c9570ab54ffa1d52660e4a85b7b by Laramie Leavitt <lar@google.com>:

Internal cleanup.

PiperOrigin-RevId: 254062381

--
d3c992e221cc74e5372d0c8fa410170b6a43c062 by Tom Manshreck <shreck@google.com>:

Update distributions.h to Abseil standards

PiperOrigin-RevId: 254054946

--
d15ad0035c34ef11b14fadc5a4a2d3ec415f5518 by CJ Johnson <johnsoncj@google.com>:

Removes functions with only one caller from the implementation details of InlinedVector by manually inlining the definitions

PiperOrigin-RevId: 254005427

--
2f37e807efc3a8ef1f4b539bdd379917d4151520 by Andy Soffer <asoffer@google.com>:

Initial release of Abseil Random

PiperOrigin-RevId: 253999861

--
24ed1694b6430791d781ed533a8f8ccf6cac5856 by CJ Johnson <johnsoncj@google.com>:

Updates the definition of InlinedVector::assign(...)/InlinedVector::operator=(...) to new, exception-safe implementations with exception safety tests to boot

PiperOrigin-RevId: 253993691

--
5613d95f5a7e34a535cfaeadce801441e990843e by CJ Johnson <johnsoncj@google.com>:

Adds benchmarks for InlinedVector::shrink_to_fit()

PiperOrigin-RevId: 253989647

--
2a96ddfdac40bbb8cb6a7f1aeab90917067c6e63 by Abseil Team <absl-team@google.com>:

Initial release of Abseil Random

PiperOrigin-RevId: 253927497

--
bf1aff8fc9ffa921ad74643e9525ecf25b0d8dc1 by Andy Soffer <asoffer@google.com>:

Initial release of Abseil Random

PiperOrigin-RevId: 253920512

--
bfc03f4a3dcda3cf3a4b84bdb84cda24e3394f41 by Laramie Leavitt <lar@google.com>:

Internal change.

PiperOrigin-RevId: 253886486

--
05036cfcc078ca7c5f581a00dfb0daed568cbb69 by Eric Fiselier <ericwf@google.com>:

Don't include `winsock2.h` because it drags in `windows.h` and friends,
and they define awful macros like OPAQUE, ERROR, and more. This has the
potential to break abseil users.

Instead we only forward declare `timeval` and require Windows users
include `winsock2.h` themselves. This is both inconsistent and poor QoI, but so
including 'windows.h' is bad too.

PiperOrigin-RevId: 253852615
GitOrigin-RevId: 7a6ff16a85beb730c172d5d25cf1b5e1be885c56
Change-Id: Icd6aff87da26f29ec8915da856f051129987cef6
2019-06-21 16:18:10 -04:00

442 lines
18 KiB
C++

// Copyright 2017 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// -----------------------------------------------------------------------------
// File: distributions.h
// -----------------------------------------------------------------------------
//
// This header defines functions representing distributions, which you use in
// combination with an Abseil random bit generator to produce random values
// according to the rules of that distribution.
//
// The Abseil random library defines the following distributions within this
// file:
//
// * `absl::Uniform` for uniform (constant) distributions having constant
// probability
// * `absl::Bernoulli` for discrete distributions having exactly two outcomes
// * `absl::Beta` for continuous distributions parameterized through two
// free parameters
// * `absl::Exponential` for discrete distributions of events occurring
// continuously and independently at a constant average rate
// * `absl::Gaussian` (also known as "normal distributions") for continuous
// distributions using an associated quadratic function
// * `absl::LogUniform` for continuous uniform distributions where the log
// to the given base of all values is uniform
// * `absl::Poisson` for discrete probability distributions that express the
// probability of a given number of events occurring within a fixed interval
// * `absl::Zipf` for discrete probability distributions commonly used for
// modelling of rare events
//
// Prefer use of these distribution function classes over manual construction of
// your own distribution classes, as it allows library maintainers greater
// flexibility to change the underlying implementation in the future.
#ifndef ABSL_RANDOM_DISTRIBUTIONS_H_
#define ABSL_RANDOM_DISTRIBUTIONS_H_
#include <algorithm>
#include <cmath>
#include <limits>
#include <random>
#include <type_traits>
#include "absl/base/internal/inline_variable.h"
#include "absl/random/bernoulli_distribution.h"
#include "absl/random/beta_distribution.h"
#include "absl/random/distribution_format_traits.h"
#include "absl/random/exponential_distribution.h"
#include "absl/random/gaussian_distribution.h"
#include "absl/random/internal/distributions.h" // IWYU pragma: export
#include "absl/random/internal/uniform_helper.h" // IWYU pragma: export
#include "absl/random/log_uniform_int_distribution.h"
#include "absl/random/poisson_distribution.h"
#include "absl/random/uniform_int_distribution.h"
#include "absl/random/uniform_real_distribution.h"
#include "absl/random/zipf_distribution.h"
namespace absl {
ABSL_INTERNAL_INLINE_CONSTEXPR(random_internal::IntervalClosedClosedT,
IntervalClosedClosed, {});
ABSL_INTERNAL_INLINE_CONSTEXPR(random_internal::IntervalClosedClosedT,
IntervalClosed, {});
ABSL_INTERNAL_INLINE_CONSTEXPR(random_internal::IntervalClosedOpenT,
IntervalClosedOpen, {});
ABSL_INTERNAL_INLINE_CONSTEXPR(random_internal::IntervalOpenOpenT,
IntervalOpenOpen, {});
ABSL_INTERNAL_INLINE_CONSTEXPR(random_internal::IntervalOpenOpenT,
IntervalOpen, {});
ABSL_INTERNAL_INLINE_CONSTEXPR(random_internal::IntervalOpenClosedT,
IntervalOpenClosed, {});
// -----------------------------------------------------------------------------
// absl::Uniform<T>(tag, bitgen, lo, hi)
// -----------------------------------------------------------------------------
//
// `absl::Uniform()` produces random values of type `T` uniformly distributed in
// a defined interval {lo, hi}. The interval `tag` defines the type of interval
// which should be one of the following possible values:
//
// * `absl::IntervalOpenOpen`
// * `absl::IntervalOpenClosed`
// * `absl::IntervalClosedOpen`
// * `absl::IntervalClosedClosed`
//
// where "open" refers to an exclusive value (excluded) from the output, while
// "closed" refers to an inclusive value (included) from the output.
//
// In the absence of an explicit return type `T`, `absl::Uniform()` will deduce
// the return type based on the provided endpoint arguments {A lo, B hi}.
// Given these endpoints, one of {A, B} will be chosen as the return type, if
// a type can be implicitly converted into the other in a lossless way. The
// lack of any such implcit conversion between {A, B} will produce a
// compile-time error
//
// See https://en.wikipedia.org/wiki/Uniform_distribution_(continuous)
//
// Example:
//
// absl::BitGen bitgen;
//
// // Produce a random float value between 0.0 and 1.0, inclusive
// auto x = absl::Uniform(absl::IntervalClosedClosed, bitgen, 0.0f, 1.0f);
//
// // The most common interval of `absl::IntervalClosedOpen` is available by
// // default:
//
// auto x = absl::Uniform(bitgen, 0.0f, 1.0f);
//
// // Return-types are typically inferred from the arguments, however callers
// // can optionally provide an explicit return-type to the template.
//
// auto x = absl::Uniform<float>(bitgen, 0, 1);
//
template <typename R = void, typename TagType, typename URBG>
typename absl::enable_if_t<!std::is_same<R, void>::value, R> //
Uniform(TagType tag,
URBG&& urbg, // NOLINT(runtime/references)
R lo, R hi) {
using gen_t = absl::decay_t<URBG>;
return random_internal::UniformImpl<R, TagType, gen_t>(tag, urbg, lo, hi);
}
// absl::Uniform<T>(bitgen, lo, hi)
//
// Overload of `Uniform()` using the default closed-open interval of [lo, hi),
// and returning values of type `T`
template <typename R = void, typename URBG>
typename absl::enable_if_t<!std::is_same<R, void>::value, R> //
Uniform(URBG&& urbg, // NOLINT(runtime/references)
R lo, R hi) {
constexpr auto tag = absl::IntervalClosedOpen;
using tag_t = decltype(tag);
using gen_t = absl::decay_t<URBG>;
return random_internal::UniformImpl<R, tag_t, gen_t>(tag, urbg, lo, hi);
}
// absl::Uniform(tag, bitgen, lo, hi)
//
// Overload of `Uniform()` using different (but compatible) lo, hi types. Note
// that a compile-error will result if the return type cannot be deduced
// correctly from the passed types.
template <typename R = void, typename TagType, typename URBG, typename A,
typename B>
typename absl::enable_if_t<std::is_same<R, void>::value,
random_internal::uniform_inferred_return_t<A, B>>
Uniform(TagType tag,
URBG&& urbg, // NOLINT(runtime/references)
A lo, B hi) {
using gen_t = absl::decay_t<URBG>;
using return_t = typename random_internal::uniform_inferred_return_t<A, B>;
return random_internal::UniformImpl<return_t, TagType, gen_t>(tag, urbg, lo,
hi);
}
// absl::Uniform(bitgen, lo, hi)
//
// Overload of `Uniform()` using different (but compatible) lo, hi types and the
// default closed-open interval of [lo, hi). Note that a compile-error will
// result if the return type cannot be deduced correctly from the passed types.
template <typename R = void, typename URBG, typename A, typename B>
typename absl::enable_if_t<std::is_same<R, void>::value,
random_internal::uniform_inferred_return_t<A, B>>
Uniform(URBG&& urbg, // NOLINT(runtime/references)
A lo, B hi) {
constexpr auto tag = absl::IntervalClosedOpen;
using tag_t = decltype(tag);
using gen_t = absl::decay_t<URBG>;
using return_t = typename random_internal::uniform_inferred_return_t<A, B>;
return random_internal::UniformImpl<return_t, tag_t, gen_t>(tag, urbg, lo,
hi);
}
// absl::Uniform<unsigned T>(bitgen)
//
// Overload of Uniform() using the minimum and maximum values of a given type
// `T` (which must be unsigned), returning a value of type `unsigned T`
template <typename R, typename URBG>
typename absl::enable_if_t<!std::is_signed<R>::value, R> //
Uniform(URBG&& urbg) { // NOLINT(runtime/references)
constexpr auto tag = absl::IntervalClosedClosed;
constexpr auto lo = std::numeric_limits<R>::lowest();
constexpr auto hi = (std::numeric_limits<R>::max)();
using tag_t = decltype(tag);
using gen_t = absl::decay_t<URBG>;
return random_internal::UniformImpl<R, tag_t, gen_t>(tag, urbg, lo, hi);
}
// -----------------------------------------------------------------------------
// absl::Bernoulli(bitgen, p)
// -----------------------------------------------------------------------------
//
// `absl::Bernoulli` produces a random boolean value, with probability `p`
// (where 0.0 <= p <= 1.0) equaling `true`.
//
// Prefer `absl::Bernoulli` to produce boolean values over other alternatives
// such as comparing an `absl::Uniform()` value to a specific output.
//
// See https://en.wikipedia.org/wiki/Bernoulli_distribution
//
// Example:
//
// absl::BitGen bitgen;
// ...
// if (absl::Bernoulli(bitgen, 1.0/3721.0)) {
// std::cout << "Asteroid field navigation successful.";
// }
//
template <typename URBG>
bool Bernoulli(URBG&& urbg, // NOLINT(runtime/references)
double p) {
using gen_t = absl::decay_t<URBG>;
using distribution_t = absl::bernoulli_distribution;
using format_t = random_internal::DistributionFormatTraits<distribution_t>;
return random_internal::DistributionCaller<gen_t>::template Call<
distribution_t, format_t>(&urbg, p);
}
// -----------------------------------------------------------------------------
// absl::Beta<T>(bitgen, alpha, beta)
// -----------------------------------------------------------------------------
//
// `absl::Beta` produces a floating point number distributed in the closed
// interval [0,1] and parameterized by two values `alpha` and `beta` as per a
// Beta distribution. `T` must be a floating point type, but may be inferred
// from the types of `alpha` and `beta`.
//
// See https://en.wikipedia.org/wiki/Beta_distribution.
//
// Example:
//
// absl::BitGen bitgen;
// ...
// double sample = absl::Beta(bitgen, 3.0, 2.0);
//
template <typename RealType, typename URBG>
RealType Beta(URBG&& urbg, // NOLINT(runtime/references)
RealType alpha, RealType beta) {
static_assert(
std::is_floating_point<RealType>::value,
"Template-argument 'RealType' must be a floating-point type, in "
"absl::Beta<RealType, URBG>(...)");
using gen_t = absl::decay_t<URBG>;
using distribution_t = typename absl::beta_distribution<RealType>;
using format_t = random_internal::DistributionFormatTraits<distribution_t>;
return random_internal::DistributionCaller<gen_t>::template Call<
distribution_t, format_t>(&urbg, alpha, beta);
}
// -----------------------------------------------------------------------------
// absl::Exponential<T>(bitgen, lambda = 1)
// -----------------------------------------------------------------------------
//
// `absl::Exponential` produces a floating point number for discrete
// distributions of events occurring continuously and independently at a
// constant average rate. `T` must be a floating point type, but may be inferred
// from the type of `lambda`.
//
// See https://en.wikipedia.org/wiki/Exponential_distribution.
//
// Example:
//
// absl::BitGen bitgen;
// ...
// double call_length = absl::Exponential(bitgen, 7.0);
//
template <typename RealType, typename URBG>
RealType Exponential(URBG&& urbg, // NOLINT(runtime/references)
RealType lambda = 1) {
static_assert(
std::is_floating_point<RealType>::value,
"Template-argument 'RealType' must be a floating-point type, in "
"absl::Exponential<RealType, URBG>(...)");
using gen_t = absl::decay_t<URBG>;
using distribution_t = typename absl::exponential_distribution<RealType>;
using format_t = random_internal::DistributionFormatTraits<distribution_t>;
return random_internal::DistributionCaller<gen_t>::template Call<
distribution_t, format_t>(&urbg, lambda);
}
// -----------------------------------------------------------------------------
// absl::Gaussian<T>(bitgen, mean = 0, stddev = 1)
// -----------------------------------------------------------------------------
//
// `absl::Gaussian` produces a floating point number selected from the Gaussian
// (ie. "Normal") distribution. `T` must be a floating point type, but may be
// inferred from the types of `mean` and `stddev`.
//
// See https://en.wikipedia.org/wiki/Normal_distribution
//
// Example:
//
// absl::BitGen bitgen;
// ...
// double giraffe_height = absl::Gaussian(bitgen, 16.3, 3.3);
//
template <typename RealType, typename URBG>
RealType Gaussian(URBG&& urbg, // NOLINT(runtime/references)
RealType mean = 0, RealType stddev = 1) {
static_assert(
std::is_floating_point<RealType>::value,
"Template-argument 'RealType' must be a floating-point type, in "
"absl::Gaussian<RealType, URBG>(...)");
using gen_t = absl::decay_t<URBG>;
using distribution_t = typename absl::gaussian_distribution<RealType>;
using format_t = random_internal::DistributionFormatTraits<distribution_t>;
return random_internal::DistributionCaller<gen_t>::template Call<
distribution_t, format_t>(&urbg, mean, stddev);
}
// -----------------------------------------------------------------------------
// absl::LogUniform<T>(bitgen, lo, hi, base = 2)
// -----------------------------------------------------------------------------
//
// `absl::LogUniform` produces random values distributed where the log to a
// given base of all values is uniform in a closed interval [lo, hi]. `T` must
// be an integral type, but may be inferred from the types of `lo` and `hi`.
//
// I.e., `LogUniform(0, n, b)` is uniformly distributed across buckets
// [0], [1, b-1], [b, b^2-1] .. [b^(k-1), (b^k)-1] .. [b^floor(log(n, b)), n]
// and is uniformly distributed within each bucket.
//
// The resulting probability density is inversely related to bucket size, though
// values in the final bucket may be more likely than previous values. (In the
// extreme case where n = b^i the final value will be tied with zero as the most
// probable result.
//
// If `lo` is nonzero then this distribution is shifted to the desired interval,
// so LogUniform(lo, hi, b) is equivalent to LogUniform(0, hi-lo, b)+lo.
//
// See http://ecolego.facilia.se/ecolego/show/Log-Uniform%20Distribution
//
// Example:
//
// absl::BitGen bitgen;
// ...
// int v = absl::LogUniform(bitgen, 0, 1000);
//
template <typename IntType, typename URBG>
IntType LogUniform(URBG&& urbg, // NOLINT(runtime/references)
IntType lo, IntType hi, IntType base = 2) {
static_assert(std::is_integral<IntType>::value,
"Template-argument 'IntType' must be an integral type, in "
"absl::LogUniform<IntType, URBG>(...)");
using gen_t = absl::decay_t<URBG>;
using distribution_t = typename absl::log_uniform_int_distribution<IntType>;
using format_t = random_internal::DistributionFormatTraits<distribution_t>;
return random_internal::DistributionCaller<gen_t>::template Call<
distribution_t, format_t>(&urbg, lo, hi, base);
}
// -----------------------------------------------------------------------------
// absl::Poisson<T>(bitgen, mean = 1)
// -----------------------------------------------------------------------------
//
// `absl::Poisson` produces discrete probabilities for a given number of events
// occurring within a fixed interval within the closed interval [0, max]. `T`
// must be an integral type.
//
// See https://en.wikipedia.org/wiki/Poisson_distribution
//
// Example:
//
// absl::BitGen bitgen;
// ...
// int requests_per_minute = absl::Poisson<int>(bitgen, 3.2);
//
template <typename IntType, typename URBG>
IntType Poisson(URBG&& urbg, // NOLINT(runtime/references)
double mean = 1.0) {
static_assert(std::is_integral<IntType>::value,
"Template-argument 'IntType' must be an integral type, in "
"absl::Poisson<IntType, URBG>(...)");
using gen_t = absl::decay_t<URBG>;
using distribution_t = typename absl::poisson_distribution<IntType>;
using format_t = random_internal::DistributionFormatTraits<distribution_t>;
return random_internal::DistributionCaller<gen_t>::template Call<
distribution_t, format_t>(&urbg, mean);
}
// -----------------------------------------------------------------------------
// absl::Zipf<T>(bitgen, hi = max, q = 2, v = 1)
// -----------------------------------------------------------------------------
//
// `absl::Zipf` produces discrete probabilities commonly used for modelling of
// rare events over the closed interval [0, hi]. The parameters `v` and `q`
// determine the skew of the distribution. `T` must be an integral type, but
// may be inferred from the type of `hi`.
//
// See http://mathworld.wolfram.com/ZipfDistribution.html
//
// Example:
//
// absl::BitGen bitgen;
// ...
// int term_rank = absl::Zipf<int>(bitgen);
//
template <typename IntType, typename URBG>
IntType Zipf(URBG&& urbg, // NOLINT(runtime/references)
IntType hi = (std::numeric_limits<IntType>::max)(), double q = 2.0,
double v = 1.0) {
static_assert(std::is_integral<IntType>::value,
"Template-argument 'IntType' must be an integral type, in "
"absl::Zipf<IntType, URBG>(...)");
using gen_t = absl::decay_t<URBG>;
using distribution_t = typename absl::zipf_distribution<IntType>;
using format_t = random_internal::DistributionFormatTraits<distribution_t>;
return random_internal::DistributionCaller<gen_t>::template Call<
distribution_t, format_t>(&urbg, hi, q, v);
}
} // namespace absl.
#endif // ABSL_RANDOM_DISTRIBUTIONS_H_