• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
32 #ifndef ABSL_RANDOM_UNIFORM_REAL_DISTRIBUTION_H_
33 #define ABSL_RANDOM_UNIFORM_REAL_DISTRIBUTION_H_
34 
35 #include <cassert>
36 #include <cmath>
37 #include <cstdint>
38 #include <istream>
39 #include <limits>
40 #include <type_traits>
41 
42 #include "absl/meta/type_traits.h"
43 #include "absl/random/internal/fast_uniform_bits.h"
44 #include "absl/random/internal/generate_real.h"
45 #include "absl/random/internal/iostream_state_saver.h"
46 
47 namespace absl {
48 ABSL_NAMESPACE_BEGIN
49 
50 // absl::uniform_real_distribution<T>
51 //
52 // This distribution produces random floating-point values uniformly distributed
53 // over the half-open interval [a, b).
54 //
55 // Example:
56 //
57 //   absl::BitGen gen;
58 //
59 //   // Use the distribution to produce a value between 0.0 (inclusive)
60 //   // and 1.0 (exclusive).
61 //   double value = absl::uniform_real_distribution<double>(0, 1)(gen);
62 //
63 template <typename RealType = double>
64 class uniform_real_distribution {
65  public:
66   using result_type = RealType;
67 
68   class param_type {
69    public:
70     using distribution_type = uniform_real_distribution;
71 
72     explicit param_type(result_type lo = 0, result_type hi = 1)
lo_(lo)73         : lo_(lo), hi_(hi), range_(hi - lo) {
74       // [rand.dist.uni.real] preconditions 2 & 3
75       assert(lo <= hi);
76       // NOTE: For integral types, we can promote the range to an unsigned type,
77       // which gives full width of the range. However for real (fp) types, this
78       // is not possible, so value generation cannot use the full range of the
79       // real type.
80       assert(range_ <= (std::numeric_limits<result_type>::max)());
81       assert(std::isfinite(range_));
82     }
83 
a()84     result_type a() const { return lo_; }
b()85     result_type b() const { return hi_; }
86 
87     friend bool operator==(const param_type& a, const param_type& b) {
88       return a.lo_ == b.lo_ && a.hi_ == b.hi_;
89     }
90 
91     friend bool operator!=(const param_type& a, const param_type& b) {
92       return !(a == b);
93     }
94 
95    private:
96     friend class uniform_real_distribution;
97     result_type lo_, hi_, range_;
98 
99     static_assert(std::is_floating_point<RealType>::value,
100                   "Class-template absl::uniform_real_distribution<> must be "
101                   "parameterized using a floating-point type.");
102   };
103 
uniform_real_distribution()104   uniform_real_distribution() : uniform_real_distribution(0) {}
105 
106   explicit uniform_real_distribution(result_type lo, result_type hi = 1)
param_(lo,hi)107       : param_(lo, hi) {}
108 
uniform_real_distribution(const param_type & param)109   explicit uniform_real_distribution(const param_type& param) : param_(param) {}
110 
111   // uniform_real_distribution<T>::reset()
112   //
113   // Resets the uniform real distribution. Note that this function has no effect
114   // because the distribution already produces independent values.
reset()115   void reset() {}
116 
117   template <typename URBG>
operator()118   result_type operator()(URBG& gen) {  // NOLINT(runtime/references)
119     return operator()(gen, param_);
120   }
121 
122   template <typename URBG>
123   result_type operator()(URBG& gen,  // NOLINT(runtime/references)
124                          const param_type& p);
125 
a()126   result_type a() const { return param_.a(); }
b()127   result_type b() const { return param_.b(); }
128 
param()129   param_type param() const { return param_; }
param(const param_type & params)130   void param(const param_type& params) { param_ = params; }
131 
result_type(min)132   result_type(min)() const { return a(); }
result_type(max)133   result_type(max)() const { return b(); }
134 
135   friend bool operator==(const uniform_real_distribution& a,
136                          const uniform_real_distribution& b) {
137     return a.param_ == b.param_;
138   }
139   friend bool operator!=(const uniform_real_distribution& a,
140                          const uniform_real_distribution& b) {
141     return a.param_ != b.param_;
142   }
143 
144  private:
145   param_type param_;
146   random_internal::FastUniformBits<uint64_t> fast_u64_;
147 };
148 
149 // -----------------------------------------------------------------------------
150 // Implementation details follow
151 // -----------------------------------------------------------------------------
152 template <typename RealType>
153 template <typename URBG>
154 typename uniform_real_distribution<RealType>::result_type
operator()155 uniform_real_distribution<RealType>::operator()(
156     URBG& gen, const param_type& p) {  // NOLINT(runtime/references)
157   using random_internal::GeneratePositiveTag;
158   using random_internal::GenerateRealFromBits;
159   using real_type =
160       absl::conditional_t<std::is_same<RealType, float>::value, float, double>;
161 
162   while (true) {
163     const result_type sample =
164         GenerateRealFromBits<real_type, GeneratePositiveTag, true>(
165             fast_u64_(gen));
166     const result_type res = p.a() + (sample * p.range_);
167     if (res < p.b() || p.range_ <= 0 || !std::isfinite(p.range_)) {
168       return res;
169     }
170     // else sample rejected, try again.
171   }
172 }
173 
174 template <typename CharT, typename Traits, typename RealType>
175 std::basic_ostream<CharT, Traits>& operator<<(
176     std::basic_ostream<CharT, Traits>& os,  // NOLINT(runtime/references)
177     const uniform_real_distribution<RealType>& x) {
178   auto saver = random_internal::make_ostream_state_saver(os);
179   os.precision(random_internal::stream_precision_helper<RealType>::kPrecision);
180   os << x.a() << os.fill() << x.b();
181   return os;
182 }
183 
184 template <typename CharT, typename Traits, typename RealType>
185 std::basic_istream<CharT, Traits>& operator>>(
186     std::basic_istream<CharT, Traits>& is,     // NOLINT(runtime/references)
187     uniform_real_distribution<RealType>& x) {  // NOLINT(runtime/references)
188   using param_type = typename uniform_real_distribution<RealType>::param_type;
189   using result_type = typename uniform_real_distribution<RealType>::result_type;
190   auto saver = random_internal::make_istream_state_saver(is);
191   auto a = random_internal::read_floating_point<result_type>(is);
192   if (is.fail()) return is;
193   auto b = random_internal::read_floating_point<result_type>(is);
194   if (!is.fail()) {
195     x.param(param_type(a, b));
196   }
197   return is;
198 }
199 ABSL_NAMESPACE_END
200 }  // namespace absl
201 
202 #endif  // ABSL_RANDOM_UNIFORM_REAL_DISTRIBUTION_H_
203