tetl 0.1.0
Embedded Template Library
Loading...
Searching...
No Matches
generate_canonical.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: BSL-1.0
2
3#ifndef TETL_RANDOM_GENERATE_CANONICAL_HPP
4#define TETL_RANDOM_GENERATE_CANONICAL_HPP
5
11
12namespace etl {
13
14namespace detail {
15
16[[nodiscard]] constexpr auto generate_canonical_iterations(int bits, uint64_t gMin, uint64_t gMax) -> int
17{
18 if (bits == 0 || (gMax == numeric_limits<uint64_t>::max() && gMin == 0)) {
19 return 1;
20 }
21
22 auto const range = (gMax - gMin) + 1;
23 auto const target = ~uint64_t{0} >> (64 - bits);
24
25 auto product = uint64_t{1};
26 auto ceiling = int{0};
27
28 while (product <= target) {
29 ++ceiling;
30 if (product > numeric_limits<uint64_t>::max() / range) {
31 break;
32 }
33 product *= range;
34 }
35
36 return ceiling;
37}
38
39} // namespace detail
40
43template <typename Real, size_t Bits, typename RNG>
44[[nodiscard]] constexpr auto generate_canonical(RNG& g) noexcept(noexcept(g())) -> Real
45{
46 constexpr auto digits = static_cast<size_t>(numeric_limits<Real>::digits);
47 constexpr auto minBits = static_cast<int>(digits < Bits ? digits : Bits);
48
49 auto const r = (static_cast<Real>(RNG::max()) - static_cast<Real>(RNG::min())) + Real{1};
50 auto const k = detail::generate_canonical_iterations(minBits, RNG::min(), RNG::max());
51
52 auto result = Real{0};
53 auto factor = Real{1};
54
55 for (int i = 0; i < k; ++i) {
56 result += (static_cast<Real>(g()) - RNG::min()) * factor;
57 factor *= r;
58 }
59
60 return result / factor;
61}
62
63} // namespace etl
64
65#endif // TETL_RANDOM_GENERATE_CANONICAL_HPP
constexpr auto generate_canonical(RNG &g) noexcept(noexcept(g())) -> Real
Generates a random floating point number in range [0,1).
Definition generate_canonical.hpp:44
Definition adjacent_find.hpp:8
TETL_BUILTIN_UINT64 uint64_t
Unsigned integer type with width of exactly 64 bits.
Definition uint_t.hpp:20
static constexpr int digits
Definition numeric_limits.hpp:24
static constexpr auto max() noexcept
Definition numeric_limits.hpp:21