uniform_int_dist.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. // Class template uniform_int_distribution -*- C++ -*-
  2. // Copyright (C) 2009-2022 Free Software Foundation, Inc.
  3. //
  4. // This file is part of the GNU ISO C++ Library. This library is free
  5. // software; you can redistribute it and/or modify it under the
  6. // terms of the GNU General Public License as published by the
  7. // Free Software Foundation; either version 3, or (at your option)
  8. // any later version.
  9. // This library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. // Under Section 7 of GPL version 3, you are granted additional
  14. // permissions described in the GCC Runtime Library Exception, version
  15. // 3.1, as published by the Free Software Foundation.
  16. // You should have received a copy of the GNU General Public License and
  17. // a copy of the GCC Runtime Library Exception along with this program;
  18. // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
  19. // <http://www.gnu.org/licenses/>.
  20. /**
  21. * @file bits/uniform_int_dist.h
  22. * This is an internal header file, included by other library headers.
  23. * Do not attempt to use it directly. @headername{random}
  24. */
  25. #ifndef _GLIBCXX_BITS_UNIFORM_INT_DIST_H
  26. #define _GLIBCXX_BITS_UNIFORM_INT_DIST_H
  27. #include <type_traits>
  28. #include <ext/numeric_traits.h>
  29. #if __cplusplus > 201703L
  30. # include <concepts>
  31. #endif
  32. #include <bits/concept_check.h> // __glibcxx_function_requires
  33. namespace std _GLIBCXX_VISIBILITY(default)
  34. {
  35. _GLIBCXX_BEGIN_NAMESPACE_VERSION
  36. #ifdef __cpp_lib_concepts
  37. /// Requirements for a uniform random bit generator.
  38. template<typename _Gen>
  39. concept uniform_random_bit_generator
  40. = invocable<_Gen&> && unsigned_integral<invoke_result_t<_Gen&>>
  41. && requires
  42. {
  43. { _Gen::min() } -> same_as<invoke_result_t<_Gen&>>;
  44. { _Gen::max() } -> same_as<invoke_result_t<_Gen&>>;
  45. requires bool_constant<(_Gen::min() < _Gen::max())>::value;
  46. };
  47. #endif
  48. namespace __detail
  49. {
  50. // Determine whether number is a power of two.
  51. // This is true for zero, which is OK because we want _Power_of_2(n+1)
  52. // to be true if n==numeric_limits<_Tp>::max() and so n+1 wraps around.
  53. template<typename _Tp>
  54. constexpr bool
  55. _Power_of_2(_Tp __x)
  56. {
  57. return ((__x - 1) & __x) == 0;
  58. }
  59. }
  60. /**
  61. * @brief Uniform discrete distribution for random numbers.
  62. * A discrete random distribution on the range @f$[min, max]@f$ with equal
  63. * probability throughout the range.
  64. */
  65. template<typename _IntType = int>
  66. class uniform_int_distribution
  67. {
  68. static_assert(std::is_integral<_IntType>::value,
  69. "template argument must be an integral type");
  70. public:
  71. /** The type of the range of the distribution. */
  72. typedef _IntType result_type;
  73. /** Parameter type. */
  74. struct param_type
  75. {
  76. typedef uniform_int_distribution<_IntType> distribution_type;
  77. param_type() : param_type(0) { }
  78. explicit
  79. param_type(_IntType __a,
  80. _IntType __b = __gnu_cxx::__int_traits<_IntType>::__max)
  81. : _M_a(__a), _M_b(__b)
  82. {
  83. __glibcxx_assert(_M_a <= _M_b);
  84. }
  85. result_type
  86. a() const
  87. { return _M_a; }
  88. result_type
  89. b() const
  90. { return _M_b; }
  91. friend bool
  92. operator==(const param_type& __p1, const param_type& __p2)
  93. { return __p1._M_a == __p2._M_a && __p1._M_b == __p2._M_b; }
  94. friend bool
  95. operator!=(const param_type& __p1, const param_type& __p2)
  96. { return !(__p1 == __p2); }
  97. private:
  98. _IntType _M_a;
  99. _IntType _M_b;
  100. };
  101. public:
  102. /**
  103. * @brief Constructs a uniform distribution object.
  104. */
  105. uniform_int_distribution() : uniform_int_distribution(0) { }
  106. /**
  107. * @brief Constructs a uniform distribution object.
  108. */
  109. explicit
  110. uniform_int_distribution(_IntType __a,
  111. _IntType __b
  112. = __gnu_cxx::__int_traits<_IntType>::__max)
  113. : _M_param(__a, __b)
  114. { }
  115. explicit
  116. uniform_int_distribution(const param_type& __p)
  117. : _M_param(__p)
  118. { }
  119. /**
  120. * @brief Resets the distribution state.
  121. *
  122. * Does nothing for the uniform integer distribution.
  123. */
  124. void
  125. reset() { }
  126. result_type
  127. a() const
  128. { return _M_param.a(); }
  129. result_type
  130. b() const
  131. { return _M_param.b(); }
  132. /**
  133. * @brief Returns the parameter set of the distribution.
  134. */
  135. param_type
  136. param() const
  137. { return _M_param; }
  138. /**
  139. * @brief Sets the parameter set of the distribution.
  140. * @param __param The new parameter set of the distribution.
  141. */
  142. void
  143. param(const param_type& __param)
  144. { _M_param = __param; }
  145. /**
  146. * @brief Returns the inclusive lower bound of the distribution range.
  147. */
  148. result_type
  149. min() const
  150. { return this->a(); }
  151. /**
  152. * @brief Returns the inclusive upper bound of the distribution range.
  153. */
  154. result_type
  155. max() const
  156. { return this->b(); }
  157. /**
  158. * @brief Generating functions.
  159. */
  160. template<typename _UniformRandomBitGenerator>
  161. result_type
  162. operator()(_UniformRandomBitGenerator& __urng)
  163. { return this->operator()(__urng, _M_param); }
  164. template<typename _UniformRandomBitGenerator>
  165. result_type
  166. operator()(_UniformRandomBitGenerator& __urng,
  167. const param_type& __p);
  168. template<typename _ForwardIterator,
  169. typename _UniformRandomBitGenerator>
  170. void
  171. __generate(_ForwardIterator __f, _ForwardIterator __t,
  172. _UniformRandomBitGenerator& __urng)
  173. { this->__generate(__f, __t, __urng, _M_param); }
  174. template<typename _ForwardIterator,
  175. typename _UniformRandomBitGenerator>
  176. void
  177. __generate(_ForwardIterator __f, _ForwardIterator __t,
  178. _UniformRandomBitGenerator& __urng,
  179. const param_type& __p)
  180. { this->__generate_impl(__f, __t, __urng, __p); }
  181. template<typename _UniformRandomBitGenerator>
  182. void
  183. __generate(result_type* __f, result_type* __t,
  184. _UniformRandomBitGenerator& __urng,
  185. const param_type& __p)
  186. { this->__generate_impl(__f, __t, __urng, __p); }
  187. /**
  188. * @brief Return true if two uniform integer distributions have
  189. * the same parameters.
  190. */
  191. friend bool
  192. operator==(const uniform_int_distribution& __d1,
  193. const uniform_int_distribution& __d2)
  194. { return __d1._M_param == __d2._M_param; }
  195. private:
  196. template<typename _ForwardIterator,
  197. typename _UniformRandomBitGenerator>
  198. void
  199. __generate_impl(_ForwardIterator __f, _ForwardIterator __t,
  200. _UniformRandomBitGenerator& __urng,
  201. const param_type& __p);
  202. param_type _M_param;
  203. // Lemire's nearly divisionless algorithm.
  204. // Returns an unbiased random number from __g downscaled to [0,__range)
  205. // using an unsigned type _Wp twice as wide as unsigned type _Up.
  206. template<typename _Wp, typename _Urbg, typename _Up>
  207. static _Up
  208. _S_nd(_Urbg& __g, _Up __range)
  209. {
  210. using _Up_traits = __gnu_cxx::__int_traits<_Up>;
  211. using _Wp_traits = __gnu_cxx::__int_traits<_Wp>;
  212. static_assert(!_Up_traits::__is_signed, "U must be unsigned");
  213. static_assert(!_Wp_traits::__is_signed, "W must be unsigned");
  214. static_assert(_Wp_traits::__digits == (2 * _Up_traits::__digits),
  215. "W must be twice as wide as U");
  216. // reference: Fast Random Integer Generation in an Interval
  217. // ACM Transactions on Modeling and Computer Simulation 29 (1), 2019
  218. // https://arxiv.org/abs/1805.10941
  219. _Wp __product = _Wp(__g()) * _Wp(__range);
  220. _Up __low = _Up(__product);
  221. if (__low < __range)
  222. {
  223. _Up __threshold = -__range % __range;
  224. while (__low < __threshold)
  225. {
  226. __product = _Wp(__g()) * _Wp(__range);
  227. __low = _Up(__product);
  228. }
  229. }
  230. return __product >> _Up_traits::__digits;
  231. }
  232. };
  233. template<typename _IntType>
  234. template<typename _UniformRandomBitGenerator>
  235. typename uniform_int_distribution<_IntType>::result_type
  236. uniform_int_distribution<_IntType>::
  237. operator()(_UniformRandomBitGenerator& __urng,
  238. const param_type& __param)
  239. {
  240. typedef typename _UniformRandomBitGenerator::result_type _Gresult_type;
  241. typedef typename make_unsigned<result_type>::type __utype;
  242. typedef typename common_type<_Gresult_type, __utype>::type __uctype;
  243. constexpr __uctype __urngmin = _UniformRandomBitGenerator::min();
  244. constexpr __uctype __urngmax = _UniformRandomBitGenerator::max();
  245. static_assert( __urngmin < __urngmax,
  246. "Uniform random bit generator must define min() < max()");
  247. constexpr __uctype __urngrange = __urngmax - __urngmin;
  248. const __uctype __urange
  249. = __uctype(__param.b()) - __uctype(__param.a());
  250. __uctype __ret;
  251. if (__urngrange > __urange)
  252. {
  253. // downscaling
  254. const __uctype __uerange = __urange + 1; // __urange can be zero
  255. #if defined __UINT64_TYPE__ && defined __UINT32_TYPE__
  256. #if __SIZEOF_INT128__
  257. if _GLIBCXX17_CONSTEXPR (__urngrange == __UINT64_MAX__)
  258. {
  259. // __urng produces values that use exactly 64-bits,
  260. // so use 128-bit integers to downscale to desired range.
  261. __UINT64_TYPE__ __u64erange = __uerange;
  262. __ret = __extension__ _S_nd<unsigned __int128>(__urng,
  263. __u64erange);
  264. }
  265. else
  266. #endif
  267. if _GLIBCXX17_CONSTEXPR (__urngrange == __UINT32_MAX__)
  268. {
  269. // __urng produces values that use exactly 32-bits,
  270. // so use 64-bit integers to downscale to desired range.
  271. __UINT32_TYPE__ __u32erange = __uerange;
  272. __ret = _S_nd<__UINT64_TYPE__>(__urng, __u32erange);
  273. }
  274. else
  275. #endif
  276. {
  277. // fallback case (2 divisions)
  278. const __uctype __scaling = __urngrange / __uerange;
  279. const __uctype __past = __uerange * __scaling;
  280. do
  281. __ret = __uctype(__urng()) - __urngmin;
  282. while (__ret >= __past);
  283. __ret /= __scaling;
  284. }
  285. }
  286. else if (__urngrange < __urange)
  287. {
  288. // upscaling
  289. /*
  290. Note that every value in [0, urange]
  291. can be written uniquely as
  292. (urngrange + 1) * high + low
  293. where
  294. high in [0, urange / (urngrange + 1)]
  295. and
  296. low in [0, urngrange].
  297. */
  298. __uctype __tmp; // wraparound control
  299. do
  300. {
  301. const __uctype __uerngrange = __urngrange + 1;
  302. __tmp = (__uerngrange * operator()
  303. (__urng, param_type(0, __urange / __uerngrange)));
  304. __ret = __tmp + (__uctype(__urng()) - __urngmin);
  305. }
  306. while (__ret > __urange || __ret < __tmp);
  307. }
  308. else
  309. __ret = __uctype(__urng()) - __urngmin;
  310. return __ret + __param.a();
  311. }
  312. template<typename _IntType>
  313. template<typename _ForwardIterator,
  314. typename _UniformRandomBitGenerator>
  315. void
  316. uniform_int_distribution<_IntType>::
  317. __generate_impl(_ForwardIterator __f, _ForwardIterator __t,
  318. _UniformRandomBitGenerator& __urng,
  319. const param_type& __param)
  320. {
  321. __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>)
  322. typedef typename _UniformRandomBitGenerator::result_type _Gresult_type;
  323. typedef typename make_unsigned<result_type>::type __utype;
  324. typedef typename common_type<_Gresult_type, __utype>::type __uctype;
  325. static_assert( __urng.min() < __urng.max(),
  326. "Uniform random bit generator must define min() < max()");
  327. constexpr __uctype __urngmin = __urng.min();
  328. constexpr __uctype __urngmax = __urng.max();
  329. constexpr __uctype __urngrange = __urngmax - __urngmin;
  330. const __uctype __urange
  331. = __uctype(__param.b()) - __uctype(__param.a());
  332. __uctype __ret;
  333. if (__urngrange > __urange)
  334. {
  335. if (__detail::_Power_of_2(__urngrange + 1)
  336. && __detail::_Power_of_2(__urange + 1))
  337. {
  338. while (__f != __t)
  339. {
  340. __ret = __uctype(__urng()) - __urngmin;
  341. *__f++ = (__ret & __urange) + __param.a();
  342. }
  343. }
  344. else
  345. {
  346. // downscaling
  347. const __uctype __uerange = __urange + 1; // __urange can be zero
  348. const __uctype __scaling = __urngrange / __uerange;
  349. const __uctype __past = __uerange * __scaling;
  350. while (__f != __t)
  351. {
  352. do
  353. __ret = __uctype(__urng()) - __urngmin;
  354. while (__ret >= __past);
  355. *__f++ = __ret / __scaling + __param.a();
  356. }
  357. }
  358. }
  359. else if (__urngrange < __urange)
  360. {
  361. // upscaling
  362. /*
  363. Note that every value in [0, urange]
  364. can be written uniquely as
  365. (urngrange + 1) * high + low
  366. where
  367. high in [0, urange / (urngrange + 1)]
  368. and
  369. low in [0, urngrange].
  370. */
  371. __uctype __tmp; // wraparound control
  372. while (__f != __t)
  373. {
  374. do
  375. {
  376. constexpr __uctype __uerngrange = __urngrange + 1;
  377. __tmp = (__uerngrange * operator()
  378. (__urng, param_type(0, __urange / __uerngrange)));
  379. __ret = __tmp + (__uctype(__urng()) - __urngmin);
  380. }
  381. while (__ret > __urange || __ret < __tmp);
  382. *__f++ = __ret;
  383. }
  384. }
  385. else
  386. while (__f != __t)
  387. *__f++ = __uctype(__urng()) - __urngmin + __param.a();
  388. }
  389. // operator!= and operator<< and operator>> are defined in <bits/random.h>
  390. _GLIBCXX_END_NAMESPACE_VERSION
  391. } // namespace std
  392. #endif