uniform_real_distribution.h 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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. // -----------------------------------------------------------------------------
  16. // File: uniform_real_distribution.h
  17. // -----------------------------------------------------------------------------
  18. //
  19. // This header defines a class for representing a uniform floating-point
  20. // distribution over a half-open interval [a,b). You use this distribution in
  21. // combination with an Abseil random bit generator to produce random values
  22. // according to the rules of the distribution.
  23. //
  24. // `y_absl::uniform_real_distribution` is a drop-in replacement for the C++11
  25. // `std::uniform_real_distribution` [rand.dist.uni.real] but is considerably
  26. // faster than the libstdc++ implementation.
  27. //
  28. // Note: the standard-library version may occasionally return `1.0` when
  29. // default-initialized. See https://bugs.llvm.org//show_bug.cgi?id=18767
  30. // `y_absl::uniform_real_distribution` does not exhibit this behavior.
  31. #ifndef Y_ABSL_RANDOM_UNIFORM_REAL_DISTRIBUTION_H_
  32. #define Y_ABSL_RANDOM_UNIFORM_REAL_DISTRIBUTION_H_
  33. #include <cassert>
  34. #include <cmath>
  35. #include <cstdint>
  36. #include <istream>
  37. #include <limits>
  38. #include <type_traits>
  39. #include "y_absl/meta/type_traits.h"
  40. #include "y_absl/random/internal/fast_uniform_bits.h"
  41. #include "y_absl/random/internal/generate_real.h"
  42. #include "y_absl/random/internal/iostream_state_saver.h"
  43. namespace y_absl {
  44. Y_ABSL_NAMESPACE_BEGIN
  45. // y_absl::uniform_real_distribution<T>
  46. //
  47. // This distribution produces random floating-point values uniformly distributed
  48. // over the half-open interval [a, b).
  49. //
  50. // Example:
  51. //
  52. // y_absl::BitGen gen;
  53. //
  54. // // Use the distribution to produce a value between 0.0 (inclusive)
  55. // // and 1.0 (exclusive).
  56. // double value = y_absl::uniform_real_distribution<double>(0, 1)(gen);
  57. //
  58. template <typename RealType = double>
  59. class uniform_real_distribution {
  60. public:
  61. using result_type = RealType;
  62. class param_type {
  63. public:
  64. using distribution_type = uniform_real_distribution;
  65. explicit param_type(result_type lo = 0, result_type hi = 1)
  66. : lo_(lo), hi_(hi), range_(hi - lo) {
  67. // [rand.dist.uni.real] preconditions 2 & 3
  68. assert(lo <= hi);
  69. // NOTE: For integral types, we can promote the range to an unsigned type,
  70. // which gives full width of the range. However for real (fp) types, this
  71. // is not possible, so value generation cannot use the full range of the
  72. // real type.
  73. assert(range_ <= (std::numeric_limits<result_type>::max)());
  74. }
  75. result_type a() const { return lo_; }
  76. result_type b() const { return hi_; }
  77. friend bool operator==(const param_type& a, const param_type& b) {
  78. return a.lo_ == b.lo_ && a.hi_ == b.hi_;
  79. }
  80. friend bool operator!=(const param_type& a, const param_type& b) {
  81. return !(a == b);
  82. }
  83. private:
  84. friend class uniform_real_distribution;
  85. result_type lo_, hi_, range_;
  86. static_assert(std::is_floating_point<RealType>::value,
  87. "Class-template y_absl::uniform_real_distribution<> must be "
  88. "parameterized using a floating-point type.");
  89. };
  90. uniform_real_distribution() : uniform_real_distribution(0) {}
  91. explicit uniform_real_distribution(result_type lo, result_type hi = 1)
  92. : param_(lo, hi) {}
  93. explicit uniform_real_distribution(const param_type& param) : param_(param) {}
  94. // uniform_real_distribution<T>::reset()
  95. //
  96. // Resets the uniform real distribution. Note that this function has no effect
  97. // because the distribution already produces independent values.
  98. void reset() {}
  99. template <typename URBG>
  100. result_type operator()(URBG& gen) { // NOLINT(runtime/references)
  101. return operator()(gen, param_);
  102. }
  103. template <typename URBG>
  104. result_type operator()(URBG& gen, // NOLINT(runtime/references)
  105. const param_type& p);
  106. result_type a() const { return param_.a(); }
  107. result_type b() const { return param_.b(); }
  108. param_type param() const { return param_; }
  109. void param(const param_type& params) { param_ = params; }
  110. result_type(min)() const { return a(); }
  111. result_type(max)() const { return b(); }
  112. friend bool operator==(const uniform_real_distribution& a,
  113. const uniform_real_distribution& b) {
  114. return a.param_ == b.param_;
  115. }
  116. friend bool operator!=(const uniform_real_distribution& a,
  117. const uniform_real_distribution& b) {
  118. return a.param_ != b.param_;
  119. }
  120. private:
  121. param_type param_;
  122. random_internal::FastUniformBits<uint64_t> fast_u64_;
  123. };
  124. // -----------------------------------------------------------------------------
  125. // Implementation details follow
  126. // -----------------------------------------------------------------------------
  127. template <typename RealType>
  128. template <typename URBG>
  129. typename uniform_real_distribution<RealType>::result_type
  130. uniform_real_distribution<RealType>::operator()(
  131. URBG& gen, const param_type& p) { // NOLINT(runtime/references)
  132. using random_internal::GeneratePositiveTag;
  133. using random_internal::GenerateRealFromBits;
  134. using real_type =
  135. y_absl::conditional_t<std::is_same<RealType, float>::value, float, double>;
  136. while (true) {
  137. const result_type sample =
  138. GenerateRealFromBits<real_type, GeneratePositiveTag, true>(
  139. fast_u64_(gen));
  140. const result_type res = p.a() + (sample * p.range_);
  141. if (res < p.b() || p.range_ <= 0 || !std::isfinite(p.range_)) {
  142. return res;
  143. }
  144. // else sample rejected, try again.
  145. }
  146. }
  147. template <typename CharT, typename Traits, typename RealType>
  148. std::basic_ostream<CharT, Traits>& operator<<(
  149. std::basic_ostream<CharT, Traits>& os, // NOLINT(runtime/references)
  150. const uniform_real_distribution<RealType>& x) {
  151. auto saver = random_internal::make_ostream_state_saver(os);
  152. os.precision(random_internal::stream_precision_helper<RealType>::kPrecision);
  153. os << x.a() << os.fill() << x.b();
  154. return os;
  155. }
  156. template <typename CharT, typename Traits, typename RealType>
  157. std::basic_istream<CharT, Traits>& operator>>(
  158. std::basic_istream<CharT, Traits>& is, // NOLINT(runtime/references)
  159. uniform_real_distribution<RealType>& x) { // NOLINT(runtime/references)
  160. using param_type = typename uniform_real_distribution<RealType>::param_type;
  161. using result_type = typename uniform_real_distribution<RealType>::result_type;
  162. auto saver = random_internal::make_istream_state_saver(is);
  163. auto a = random_internal::read_floating_point<result_type>(is);
  164. if (is.fail()) return is;
  165. auto b = random_internal::read_floating_point<result_type>(is);
  166. if (!is.fail()) {
  167. x.param(param_type(a, b));
  168. }
  169. return is;
  170. }
  171. Y_ABSL_NAMESPACE_END
  172. } // namespace y_absl
  173. #endif // Y_ABSL_RANDOM_UNIFORM_REAL_DISTRIBUTION_H_