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. // `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. // `absl::uniform_real_distribution` does not exhibit this behavior.
  31. #ifndef ABSL_RANDOM_UNIFORM_REAL_DISTRIBUTION_H_
  32. #define 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 "absl/meta/type_traits.h"
  40. #include "absl/random/internal/fast_uniform_bits.h"
  41. #include "absl/random/internal/generate_real.h"
  42. #include "absl/random/internal/iostream_state_saver.h"
  43. namespace absl {
  44. ABSL_NAMESPACE_BEGIN
  45. // 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. // absl::BitGen gen;
  53. //
  54. // // Use the distribution to produce a value between 0.0 (inclusive)
  55. // // and 1.0 (exclusive).
  56. // double value = 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. assert(std::isfinite(range_));
  75. }
  76. result_type a() const { return lo_; }
  77. result_type b() const { return hi_; }
  78. friend bool operator==(const param_type& a, const param_type& b) {
  79. return a.lo_ == b.lo_ && a.hi_ == b.hi_;
  80. }
  81. friend bool operator!=(const param_type& a, const param_type& b) {
  82. return !(a == b);
  83. }
  84. private:
  85. friend class uniform_real_distribution;
  86. result_type lo_, hi_, range_;
  87. static_assert(std::is_floating_point<RealType>::value,
  88. "Class-template absl::uniform_real_distribution<> must be "
  89. "parameterized using a floating-point type.");
  90. };
  91. uniform_real_distribution() : uniform_real_distribution(0) {}
  92. explicit uniform_real_distribution(result_type lo, result_type hi = 1)
  93. : param_(lo, hi) {}
  94. explicit uniform_real_distribution(const param_type& param) : param_(param) {}
  95. // uniform_real_distribution<T>::reset()
  96. //
  97. // Resets the uniform real distribution. Note that this function has no effect
  98. // because the distribution already produces independent values.
  99. void reset() {}
  100. template <typename URBG>
  101. result_type operator()(URBG& gen) { // NOLINT(runtime/references)
  102. return operator()(gen, param_);
  103. }
  104. template <typename URBG>
  105. result_type operator()(URBG& gen, // NOLINT(runtime/references)
  106. const param_type& p);
  107. result_type a() const { return param_.a(); }
  108. result_type b() const { return param_.b(); }
  109. param_type param() const { return param_; }
  110. void param(const param_type& params) { param_ = params; }
  111. result_type(min)() const { return a(); }
  112. result_type(max)() const { return b(); }
  113. friend bool operator==(const uniform_real_distribution& a,
  114. const uniform_real_distribution& b) {
  115. return a.param_ == b.param_;
  116. }
  117. friend bool operator!=(const uniform_real_distribution& a,
  118. const uniform_real_distribution& b) {
  119. return a.param_ != b.param_;
  120. }
  121. private:
  122. param_type param_;
  123. random_internal::FastUniformBits<uint64_t> fast_u64_;
  124. };
  125. // -----------------------------------------------------------------------------
  126. // Implementation details follow
  127. // -----------------------------------------------------------------------------
  128. template <typename RealType>
  129. template <typename URBG>
  130. typename uniform_real_distribution<RealType>::result_type
  131. uniform_real_distribution<RealType>::operator()(
  132. URBG& gen, const param_type& p) { // NOLINT(runtime/references)
  133. using random_internal::GeneratePositiveTag;
  134. using random_internal::GenerateRealFromBits;
  135. using real_type =
  136. absl::conditional_t<std::is_same<RealType, float>::value, float, double>;
  137. while (true) {
  138. const result_type sample =
  139. GenerateRealFromBits<real_type, GeneratePositiveTag, true>(
  140. fast_u64_(gen));
  141. const result_type res = p.a() + (sample * p.range_);
  142. if (res < p.b() || p.range_ <= 0 || !std::isfinite(p.range_)) {
  143. return res;
  144. }
  145. // else sample rejected, try again.
  146. }
  147. }
  148. template <typename CharT, typename Traits, typename RealType>
  149. std::basic_ostream<CharT, Traits>& operator<<(
  150. std::basic_ostream<CharT, Traits>& os, // NOLINT(runtime/references)
  151. const uniform_real_distribution<RealType>& x) {
  152. auto saver = random_internal::make_ostream_state_saver(os);
  153. os.precision(random_internal::stream_precision_helper<RealType>::kPrecision);
  154. os << x.a() << os.fill() << x.b();
  155. return os;
  156. }
  157. template <typename CharT, typename Traits, typename RealType>
  158. std::basic_istream<CharT, Traits>& operator>>(
  159. std::basic_istream<CharT, Traits>& is, // NOLINT(runtime/references)
  160. uniform_real_distribution<RealType>& x) { // NOLINT(runtime/references)
  161. using param_type = typename uniform_real_distribution<RealType>::param_type;
  162. using result_type = typename uniform_real_distribution<RealType>::result_type;
  163. auto saver = random_internal::make_istream_state_saver(is);
  164. auto a = random_internal::read_floating_point<result_type>(is);
  165. if (is.fail()) return is;
  166. auto b = random_internal::read_floating_point<result_type>(is);
  167. if (!is.fail()) {
  168. x.param(param_type(a, b));
  169. }
  170. return is;
  171. }
  172. ABSL_NAMESPACE_END
  173. } // namespace absl
  174. #endif // ABSL_RANDOM_UNIFORM_REAL_DISTRIBUTION_H_