libstdc++
uniform_int_dist.h
Go to the documentation of this file.
1// Class template uniform_int_distribution -*- C++ -*-
2
3// Copyright (C) 2009-2026 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/**
26 * @file bits/uniform_int_dist.h
27 * This is an internal header file, included by other library headers.
28 * Do not attempt to use it directly. @headername{random}
29 */
30
31#ifndef _GLIBCXX_BITS_UNIFORM_INT_DIST_H
32#define _GLIBCXX_BITS_UNIFORM_INT_DIST_H
33
34#include <type_traits>
35#include <ext/numeric_traits.h>
36#if __cplusplus > 201703L
37# include <concepts>
38#endif
39#include <bits/concept_check.h> // __glibcxx_function_requires
40
41namespace std _GLIBCXX_VISIBILITY(default)
42{
43_GLIBCXX_BEGIN_NAMESPACE_VERSION
44
45#ifdef __cpp_lib_concepts
46 /// Requirements for a uniform random bit generator.
47 /**
48 * @ingroup random_distributions_uniform
49 * @headerfile random
50 * @since C++20
51 */
52 template<typename _Gen>
54 = invocable<_Gen&> && unsigned_integral<invoke_result_t<_Gen&>>
55 && requires
56 {
57 { _Gen::min() } -> same_as<invoke_result_t<_Gen&>>;
58 { _Gen::max() } -> same_as<invoke_result_t<_Gen&>>;
59 requires bool_constant<(_Gen::min() < _Gen::max())>::value;
60 };
61#endif
62
63 /// @cond undocumented
64 namespace __detail
65 {
66 // Determine whether number is a power of two.
67 // This is true for zero, which is OK because we want _Power_of_2(n+1)
68 // to be true if n==numeric_limits<_Tp>::max() and so n+1 wraps around.
69 template<typename _Tp>
70 constexpr bool
71 _Power_of_2(_Tp __x)
72 {
73 return ((__x - 1) & __x) == 0;
74 }
75
76 template<int __s,
77 int __which = ((__s <= __CHAR_BIT__ * sizeof (int))
78 + (__s <= __CHAR_BIT__ * sizeof (long))
79 + (__s <= __CHAR_BIT__ * sizeof (long long))
80 /* assume long long no bigger than __int128 */
81 + (__s <= 128))>
82 struct _Select_uint_least_t
83 {
84 static_assert(__which < 0, /* needs to be dependent */
85 "sorry, would be too much trouble for a slow result");
86 };
87
88 template<int __s>
89 struct _Select_uint_least_t<__s, 4>
90 { using type = unsigned int; };
91
92 template<int __s>
93 struct _Select_uint_least_t<__s, 3>
94 { using type = unsigned long; };
95
96 template<int __s>
97 struct _Select_uint_least_t<__s, 2>
98 { using type = unsigned long long; };
99
100// Alternate specialization for
101#if __SIZEOF_INT128__ > __SIZEOF_LONG_LONG__
102 template<int __s>
103 struct _Select_uint_least_t<__s, 1>
104 { __extension__ using type = unsigned __int128; };
105#elif __has_builtin(__builtin_add_overflow) \
106 && __has_builtin(__builtin_sub_overflow) \
107 && defined __UINT64_TYPE__
108 template<int __s>
109 struct _Select_uint_least_t<__s, 1>; // Defined in bits/random.h
110#endif
111 }
112 /// @endcond
113
114 /**
115 * @brief Uniform discrete distribution for random numbers.
116 * A discrete random distribution on the range @f$[min, max]@f$ with equal
117 * probability throughout the range.
118 *
119 * @ingroup random_distributions_uniform
120 * @headerfile random
121 * @since C++11
122 */
123 template<typename _IntType = int>
125 {
127 "template argument must be an integral type");
128
129 public:
130 /** The type of the range of the distribution. */
131 typedef _IntType result_type;
132 /** Parameter type. */
133 struct param_type
134 {
135 typedef uniform_int_distribution<_IntType> distribution_type;
136
137 param_type() : param_type(0) { }
138
139 explicit
140 param_type(_IntType __a,
141 _IntType __b = __gnu_cxx::__int_traits<_IntType>::__max)
142 : _M_a(__a), _M_b(__b)
143 {
144 __glibcxx_assert(_M_a <= _M_b);
145 }
146
148 a() const
149 { return _M_a; }
150
152 b() const
153 { return _M_b; }
154
155 friend bool
156 operator==(const param_type& __p1, const param_type& __p2)
157 { return __p1._M_a == __p2._M_a && __p1._M_b == __p2._M_b; }
158
159 friend bool
160 operator!=(const param_type& __p1, const param_type& __p2)
161 { return !(__p1 == __p2); }
162
163 private:
164 _IntType _M_a;
165 _IntType _M_b;
166 };
167
168 public:
169 /**
170 * @brief Constructs a uniform distribution object.
171 */
173
174 /**
175 * @brief Constructs a uniform distribution object.
176 */
177 explicit
179 _IntType __b
180 = __gnu_cxx::__int_traits<_IntType>::__max)
181 : _M_param(__a, __b)
182 { }
183
184 explicit
185 uniform_int_distribution(const param_type& __p)
186 : _M_param(__p)
187 { }
188
189 /**
190 * @brief Resets the distribution state.
191 *
192 * Does nothing for the uniform integer distribution.
193 */
194 void
195 reset() { }
196
197 result_type
198 a() const
199 { return _M_param.a(); }
200
201 result_type
202 b() const
203 { return _M_param.b(); }
204
205 /**
206 * @brief Returns the parameter set of the distribution.
207 */
208 param_type
209 param() const
210 { return _M_param; }
211
212 /**
213 * @brief Sets the parameter set of the distribution.
214 * @param __param The new parameter set of the distribution.
215 */
216 void
217 param(const param_type& __param)
218 { _M_param = __param; }
219
220 /**
221 * @brief Returns the inclusive lower bound of the distribution range.
222 */
223 result_type
224 min() const
225 { return this->a(); }
226
227 /**
228 * @brief Returns the inclusive upper bound of the distribution range.
229 */
230 result_type
231 max() const
232 { return this->b(); }
233
234 /**
235 * @brief Generating functions.
236 */
237 template<typename _UniformRandomBitGenerator>
238 result_type
239 operator()(_UniformRandomBitGenerator& __urng)
240 { return this->operator()(__urng, _M_param); }
241
242 template<typename _UniformRandomBitGenerator>
243 result_type
244 operator()(_UniformRandomBitGenerator& __urng,
245 const param_type& __p);
246
247 template<typename _ForwardIterator,
248 typename _UniformRandomBitGenerator>
249 void
250 __generate(_ForwardIterator __f, _ForwardIterator __t,
251 _UniformRandomBitGenerator& __urng)
252 { this->__generate(__f, __t, __urng, _M_param); }
253
254 template<typename _ForwardIterator,
255 typename _UniformRandomBitGenerator>
256 void
257 __generate(_ForwardIterator __f, _ForwardIterator __t,
258 _UniformRandomBitGenerator& __urng,
259 const param_type& __p)
260 { this->__generate_impl(__f, __t, __urng, __p); }
261
262 template<typename _UniformRandomBitGenerator>
263 void
264 __generate(result_type* __f, result_type* __t,
265 _UniformRandomBitGenerator& __urng,
266 const param_type& __p)
267 { this->__generate_impl(__f, __t, __urng, __p); }
268
269 /**
270 * @brief Return true if two uniform integer distributions have
271 * the same parameters.
272 */
273 friend bool
275 const uniform_int_distribution& __d2)
276 { return __d1._M_param == __d2._M_param; }
277
278 private:
279 template<typename _ForwardIterator,
280 typename _UniformRandomBitGenerator>
281 void
282 __generate_impl(_ForwardIterator __f, _ForwardIterator __t,
283 _UniformRandomBitGenerator& __urng,
284 const param_type& __p);
285
286 param_type _M_param;
287
288 // Lemire's nearly divisionless algorithm.
289 // Returns an unbiased random number from __g downscaled to [0,__range)
290 // using an unsigned type _Wp twice as wide as unsigned type _Up.
291 template<size_t _Bits, typename _Urbg>
292 static typename __detail::_Select_uint_least_t<_Bits>::type
293 _S_nd(_Urbg& __g, typename __detail::_Select_uint_least_t<_Bits>::type __range)
294 {
295 using _Up = typename __detail::_Select_uint_least_t<_Bits>::type;
296 using _Wp = typename __detail::_Select_uint_least_t<2 * _Bits>::type;
297 using _Up_traits = __gnu_cxx::__int_traits<_Up>;
298
299 constexpr auto __min = _Urbg::min();
300 constexpr _Up __mask = (_Bits < _Up_traits::__digits)
301 ? (_Up(1) << _Bits) - 1 : ~_Up(0);
302
303 // reference: Fast Random Integer Generation in an Interval
304 // ACM Transactions on Modeling and Computer Simulation 29 (1), 2019
305 // https://arxiv.org/abs/1805.10941
306 _Wp __product = _Wp(__g() - __min) * _Wp(__range);
307 _Up __low = _Up(__product) & __mask;
308 if (__low < __range)
309 {
310 const _Up __threshold = -__range % __range;
311 while (__low < __threshold)
312 {
313 __product = _Wp(__g() - __min) * _Wp(__range);
314 __low = _Up(__product) & __mask;
315
316 // The algorithm is modified to alternate between rejecting
317 // from the beginning and end of the range. This guarantees
318 // that we stop for non-uniform engines that always result
319 // in values below the __threshold.
320 const _Up __back_threshold = __mask - __threshold;
321 if (__low <= __back_threshold)
322 break;
323
324 __product = _Wp(__g() - __min) * _Wp(__range);
325 __low = _Up(__product) & __mask;
326 }
327 }
328 return _Up(__product >> _Bits) & __mask;
329 }
330 };
331
332 template<typename _IntType>
333 template<typename _UniformRandomBitGenerator>
336 operator()(_UniformRandomBitGenerator& __urng,
337 const param_type& __param)
338 {
339 typedef decltype(__urng()) _Gresult_type;
340 typedef typename make_unsigned<result_type>::type __utype;
341 typedef typename common_type<_Gresult_type, __utype>::type __uctype;
342
343 constexpr __uctype __urngmin = _UniformRandomBitGenerator::min();
344 constexpr __uctype __urngmax = _UniformRandomBitGenerator::max();
345 static_assert( __urngmin < __urngmax,
346 "Uniform random bit generator must define min() < max()");
347 constexpr __uctype __urngrange = __urngmax - __urngmin;
348
349 const __uctype __urange
350 = __uctype(__param.b()) - __uctype(__param.a());
351
352 __uctype __ret;
353 if (__urngrange > __urange)
354 {
355 // downscaling
356
357 const __uctype __uerange = __urange + 1; // __urange can be zero
358
359#pragma GCC diagnostic push
360#pragma GCC diagnostic ignored "-Wc++17-extensions" // if constexpr
361#if __has_builtin(__builtin_popcountg)
362 constexpr auto __bits = __builtin_popcountg(__urngrange);
363 if constexpr (__detail::_Power_of_2(__urngrange + 1) && __bits <= 32)
364 {
365 // __urng produces values that use no more than 32-bits,
366 // so 64-bit integer is sufficient to downscale to desired range.
367 __UINT32_TYPE__ __u32erange = __uerange;
368 __ret = _S_nd<__bits>(__urng, __u32erange);
369 }
370# if __SIZEOF_INT128__
371 else if constexpr (__detail::_Power_of_2(__urngrange + 1) && __bits <= 64)
372 {
373 // __urng produces values that use no more than 64-bits,
374 // so 128-bit integer is sufficient to downscale to desired range.
375 __UINT64_TYPE__ __u64erange = __uerange;
376 __ret = _S_nd<__bits>(__urng, __u64erange);
377 }
378# endif
379 else
380#endif
381 {
382 // fallback case (2 divisions)
383 const __uctype __scaling = __urngrange / __uerange;
384 const __uctype __past = __uerange * __scaling;
385 do
386 __ret = __uctype(__urng()) - __urngmin;
387 while (__ret >= __past);
388 __ret /= __scaling;
389 }
390#pragma GCC diagnostic pop
391 }
392 else if (__urngrange < __urange)
393 {
394 // upscaling
395 /*
396 Note that every value in [0, urange]
397 can be written uniquely as
398
399 (urngrange + 1) * high + low
400
401 where
402
403 high in [0, urange / (urngrange + 1)]
404
405 and
406
407 low in [0, urngrange].
408 */
409 __uctype __tmp; // wraparound control
410 do
411 {
412 const __uctype __uerngrange = __urngrange + 1;
413 __tmp = (__uerngrange * operator()
414 (__urng, param_type(0, __urange / __uerngrange)));
415 __ret = __tmp + (__uctype(__urng()) - __urngmin);
416 }
417 while (__ret > __urange || __ret < __tmp);
418 }
419 else
420 __ret = __uctype(__urng()) - __urngmin;
421
422 return __ret + __param.a();
423 }
424
425
426 template<typename _IntType>
427 template<typename _ForwardIterator,
428 typename _UniformRandomBitGenerator>
429 void
431 __generate_impl(_ForwardIterator __f, _ForwardIterator __t,
432 _UniformRandomBitGenerator& __urng,
433 const param_type& __param)
434 {
435 __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>)
436 typedef decltype(__urng()) _Gresult_type;
437 typedef typename make_unsigned<result_type>::type __utype;
438 typedef typename common_type<_Gresult_type, __utype>::type __uctype;
439
440 static_assert( __urng.min() < __urng.max(),
441 "Uniform random bit generator must define min() < max()");
442
443 constexpr __uctype __urngmin = __urng.min();
444 constexpr __uctype __urngmax = __urng.max();
445 constexpr __uctype __urngrange = __urngmax - __urngmin;
446 const __uctype __urange
447 = __uctype(__param.b()) - __uctype(__param.a());
448
449 __uctype __ret;
450
451 if (__urngrange > __urange)
452 {
453 if (__detail::_Power_of_2(__urngrange + 1)
454 && __detail::_Power_of_2(__urange + 1))
455 {
456 while (__f != __t)
457 {
458 __ret = __uctype(__urng()) - __urngmin;
459 *__f++ = (__ret & __urange) + __param.a();
460 }
461 }
462 else
463 {
464 // downscaling
465 const __uctype __uerange = __urange + 1; // __urange can be zero
466 const __uctype __scaling = __urngrange / __uerange;
467 const __uctype __past = __uerange * __scaling;
468 while (__f != __t)
469 {
470 do
471 __ret = __uctype(__urng()) - __urngmin;
472 while (__ret >= __past);
473 *__f++ = __ret / __scaling + __param.a();
474 }
475 }
476 }
477 else if (__urngrange < __urange)
478 {
479 // upscaling
480 /*
481 Note that every value in [0, urange]
482 can be written uniquely as
483
484 (urngrange + 1) * high + low
485
486 where
487
488 high in [0, urange / (urngrange + 1)]
489
490 and
491
492 low in [0, urngrange].
493 */
494 __uctype __tmp; // wraparound control
495 while (__f != __t)
496 {
497 do
498 {
499 constexpr __uctype __uerngrange = __urngrange + 1;
500 __tmp = (__uerngrange * operator()
501 (__urng, param_type(0, __urange / __uerngrange)));
502 __ret = __tmp + (__uctype(__urng()) - __urngmin);
503 }
504 while (__ret > __urange || __ret < __tmp);
505 *__f++ = __ret;
506 }
507 }
508 else
509 while (__f != __t)
510 *__f++ = __uctype(__urng()) - __urngmin + __param.a();
511 }
512
513 // operator!= and operator<< and operator>> are defined in <bits/random.h>
514
515_GLIBCXX_END_NAMESPACE_VERSION
516} // namespace std
517
518#endif
ISO C++ entities toplevel namespace is std.
Implementation details not part of the namespace std interface.
__numeric_traits_integer< _Tp > __int_traits
Convenience alias for __numeric_traits<integer-type>.
is_integral
Definition type_traits:565
common_type
Definition type_traits:2601
Uniform discrete distribution for random numbers. A discrete random distribution on the range with e...
void reset()
Resets the distribution state.
uniform_int_distribution()
Constructs a uniform distribution object.
void param(const param_type &__param)
Sets the parameter set of the distribution.
result_type min() const
Returns the inclusive lower bound of the distribution range.
friend bool operator==(const uniform_int_distribution &__d1, const uniform_int_distribution &__d2)
Return true if two uniform integer distributions have the same parameters.
result_type max() const
Returns the inclusive upper bound of the distribution range.
result_type operator()(_UniformRandomBitGenerator &__urng)
Generating functions.
uniform_int_distribution(_IntType __a, _IntType __b=__gnu_cxx::__int_traits< _IntType >::__max)
Constructs a uniform distribution object.
param_type param() const
Returns the parameter set of the distribution.
[concept.same], concept same_as
Definition concepts:65
[concept.invocable], concept invocable
Definition concepts:383
Requirements for a uniform random bit generator.