rational.hpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. // Boost rational.hpp header file ------------------------------------------//
  2. // (C) Copyright Paul Moore 1999. Permission to copy, use, modify, sell and
  3. // distribute this software is granted provided this copyright notice appears
  4. // in all copies. This software is provided "as is" without express or
  5. // implied warranty, and with no claim as to its suitability for any purpose.
  6. // boostinspect:nolicense (don't complain about the lack of a Boost license)
  7. // (Paul Moore hasn't been in contact for years, so there's no way to change the
  8. // license.)
  9. // See http://www.boost.org/libs/rational for documentation.
  10. // Credits:
  11. // Thanks to the boost mailing list in general for useful comments.
  12. // Particular contributions included:
  13. // Andrew D Jewell, for reminding me to take care to avoid overflow
  14. // Ed Brey, for many comments, including picking up on some dreadful typos
  15. // Stephen Silver contributed the test suite and comments on user-defined
  16. // IntType
  17. // Nickolay Mladenov, for the implementation of operator+=
  18. // Revision History
  19. // 02 Sep 13 Remove unneeded forward declarations; tweak private helper
  20. // function (Daryle Walker)
  21. // 30 Aug 13 Improve exception safety of "assign"; start modernizing I/O code
  22. // (Daryle Walker)
  23. // 27 Aug 13 Add cross-version constructor template, plus some private helper
  24. // functions; add constructor to exception class to take custom
  25. // messages (Daryle Walker)
  26. // 25 Aug 13 Add constexpr qualification wherever possible (Daryle Walker)
  27. // 05 May 12 Reduced use of implicit gcd (Mario Lang)
  28. // 05 Nov 06 Change rational_cast to not depend on division between different
  29. // types (Daryle Walker)
  30. // 04 Nov 06 Off-load GCD and LCM to Boost.Integer; add some invariant checks;
  31. // add std::numeric_limits<> requirement to help GCD (Daryle Walker)
  32. // 31 Oct 06 Recoded both operator< to use round-to-negative-infinity
  33. // divisions; the rational-value version now uses continued fraction
  34. // expansion to avoid overflows, for bug #798357 (Daryle Walker)
  35. // 20 Oct 06 Fix operator bool_type for CW 8.3 (Joaquín M López Muñoz)
  36. // 18 Oct 06 Use EXPLICIT_TEMPLATE_TYPE helper macros from Boost.Config
  37. // (Joaquín M López Muñoz)
  38. // 27 Dec 05 Add Boolean conversion operator (Daryle Walker)
  39. // 28 Sep 02 Use _left versions of operators from operators.hpp
  40. // 05 Jul 01 Recode gcd(), avoiding std::swap (Helmut Zeisel)
  41. // 03 Mar 01 Workarounds for Intel C++ 5.0 (David Abrahams)
  42. // 05 Feb 01 Update operator>> to tighten up input syntax
  43. // 05 Feb 01 Final tidy up of gcd code prior to the new release
  44. // 27 Jan 01 Recode abs() without relying on abs(IntType)
  45. // 21 Jan 01 Include Nickolay Mladenov's operator+= algorithm,
  46. // tidy up a number of areas, use newer features of operators.hpp
  47. // (reduces space overhead to zero), add operator!,
  48. // introduce explicit mixed-mode arithmetic operations
  49. // 12 Jan 01 Include fixes to handle a user-defined IntType better
  50. // 19 Nov 00 Throw on divide by zero in operator /= (John (EBo) David)
  51. // 23 Jun 00 Incorporate changes from Mark Rodgers for Borland C++
  52. // 22 Jun 00 Change _MSC_VER to BOOST_MSVC so other compilers are not
  53. // affected (Beman Dawes)
  54. // 6 Mar 00 Fix operator-= normalization, #include <string> (Jens Maurer)
  55. // 14 Dec 99 Modifications based on comments from the boost list
  56. // 09 Dec 99 Initial Version (Paul Moore)
  57. #ifndef BOOST_RATIONAL_HPP
  58. #define BOOST_RATIONAL_HPP
  59. #include <boost/config.hpp> // for BOOST_NO_STDC_NAMESPACE, BOOST_MSVC, etc
  60. #ifndef BOOST_NO_IOSTREAM
  61. #include <iomanip> // for std::setw
  62. #include <ios> // for std::noskipws, streamsize
  63. #include <istream> // for std::istream
  64. #include <ostream> // for std::ostream
  65. #include <sstream> // for std::ostringstream
  66. #endif
  67. #include <cstddef> // for NULL
  68. #include <stdexcept> // for std::domain_error
  69. #include <string> // for std::string implicit constructor
  70. #include <boost/operators.hpp> // for boost::addable etc
  71. #include <cstdlib> // for std::abs
  72. #include <boost/call_traits.hpp> // for boost::call_traits
  73. #include <boost/detail/workaround.hpp> // for BOOST_WORKAROUND
  74. #include <boost/assert.hpp> // for BOOST_ASSERT
  75. #include <boost/integer/common_factor_rt.hpp> // for boost::integer::gcd, lcm
  76. #include <limits> // for std::numeric_limits
  77. #include <boost/static_assert.hpp> // for BOOST_STATIC_ASSERT
  78. #include <boost/throw_exception.hpp>
  79. #include <boost/utility/enable_if.hpp>
  80. #include <boost/type_traits/is_convertible.hpp>
  81. #include <boost/type_traits/is_class.hpp>
  82. #include <boost/type_traits/is_same.hpp>
  83. // Control whether depreciated GCD and LCM functions are included (default: yes)
  84. #ifndef BOOST_CONTROL_RATIONAL_HAS_GCD
  85. #define BOOST_CONTROL_RATIONAL_HAS_GCD 1
  86. #endif
  87. namespace boost {
  88. #if BOOST_CONTROL_RATIONAL_HAS_GCD
  89. template <typename IntType>
  90. IntType gcd(IntType n, IntType m)
  91. {
  92. // Defer to the version in Boost.Integer
  93. return integer::gcd( n, m );
  94. }
  95. template <typename IntType>
  96. IntType lcm(IntType n, IntType m)
  97. {
  98. // Defer to the version in Boost.Integer
  99. return integer::lcm( n, m );
  100. }
  101. #endif // BOOST_CONTROL_RATIONAL_HAS_GCD
  102. namespace rational_detail{
  103. template <class FromInt, class ToInt>
  104. struct is_compatible_integer
  105. {
  106. BOOST_STATIC_CONSTANT(bool, value = ((std::numeric_limits<FromInt>::is_specialized && std::numeric_limits<FromInt>::is_integer
  107. && (std::numeric_limits<FromInt>::digits <= std::numeric_limits<ToInt>::digits)
  108. && (std::numeric_limits<FromInt>::radix == std::numeric_limits<ToInt>::radix)
  109. && ((std::numeric_limits<FromInt>::is_signed == false) || (std::numeric_limits<ToInt>::is_signed == true))
  110. && is_convertible<FromInt, ToInt>::value)
  111. || is_same<FromInt, ToInt>::value)
  112. || (is_class<ToInt>::value && is_class<FromInt>::value && is_convertible<FromInt, ToInt>::value));
  113. };
  114. }
  115. class bad_rational : public std::domain_error
  116. {
  117. public:
  118. explicit bad_rational() : std::domain_error("bad rational: zero denominator") {}
  119. explicit bad_rational( char const *what ) : std::domain_error( what ) {}
  120. };
  121. template <typename IntType>
  122. class rational
  123. {
  124. // Class-wide pre-conditions
  125. BOOST_STATIC_ASSERT( ::std::numeric_limits<IntType>::is_specialized );
  126. // Helper types
  127. typedef typename boost::call_traits<IntType>::param_type param_type;
  128. struct helper { IntType parts[2]; };
  129. typedef IntType (helper::* bool_type)[2];
  130. public:
  131. // Component type
  132. typedef IntType int_type;
  133. BOOST_CONSTEXPR
  134. rational() : num(0), den(1) {}
  135. template <class T>
  136. BOOST_CONSTEXPR rational(const T& n, typename enable_if_c<
  137. rational_detail::is_compatible_integer<T, IntType>::value
  138. >::type const* = 0) : num(n), den(1) {}
  139. template <class T, class U>
  140. BOOST_CXX14_CONSTEXPR rational(const T& n, const U& d, typename enable_if_c<
  141. rational_detail::is_compatible_integer<T, IntType>::value && rational_detail::is_compatible_integer<U, IntType>::value
  142. >::type const* = 0) : num(n), den(d) {
  143. normalize();
  144. }
  145. template < typename NewType >
  146. BOOST_CONSTEXPR explicit
  147. rational(rational<NewType> const &r, typename enable_if_c<rational_detail::is_compatible_integer<NewType, IntType>::value>::type const* = 0)
  148. : num(r.numerator()), den(is_normalized(int_type(r.numerator()),
  149. int_type(r.denominator())) ? r.denominator() :
  150. (BOOST_THROW_EXCEPTION(bad_rational("bad rational: denormalized conversion")), 0)){}
  151. template < typename NewType >
  152. BOOST_CONSTEXPR explicit
  153. rational(rational<NewType> const &r, typename disable_if_c<rational_detail::is_compatible_integer<NewType, IntType>::value>::type const* = 0)
  154. : num(r.numerator()), den(is_normalized(int_type(r.numerator()),
  155. int_type(r.denominator())) && is_safe_narrowing_conversion(r.denominator()) && is_safe_narrowing_conversion(r.numerator()) ? r.denominator() :
  156. (BOOST_THROW_EXCEPTION(bad_rational("bad rational: denormalized conversion")), 0)){}
  157. // Default copy constructor and assignment are fine
  158. // Add assignment from IntType
  159. template <class T>
  160. BOOST_CXX14_CONSTEXPR typename enable_if_c<
  161. rational_detail::is_compatible_integer<T, IntType>::value, rational &
  162. >::type operator=(const T& n) { return assign(static_cast<IntType>(n), static_cast<IntType>(1)); }
  163. // Assign in place
  164. template <class T, class U>
  165. BOOST_CXX14_CONSTEXPR typename enable_if_c<
  166. rational_detail::is_compatible_integer<T, IntType>::value && rational_detail::is_compatible_integer<U, IntType>::value, rational &
  167. >::type assign(const T& n, const U& d)
  168. {
  169. return *this = rational<IntType>(static_cast<IntType>(n), static_cast<IntType>(d));
  170. }
  171. //
  172. // The following overloads should probably *not* be provided -
  173. // but are provided for backwards compatibity reasons only.
  174. // These allow for construction/assignment from types that
  175. // are wider than IntType only if there is an implicit
  176. // conversion from T to IntType, they will throw a bad_rational
  177. // if the conversion results in loss of precision or undefined behaviour.
  178. //
  179. template <class T>
  180. BOOST_CXX14_CONSTEXPR rational(const T& n, typename enable_if_c<
  181. std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer
  182. && !rational_detail::is_compatible_integer<T, IntType>::value
  183. && (std::numeric_limits<T>::radix == std::numeric_limits<IntType>::radix)
  184. && is_convertible<T, IntType>::value
  185. >::type const* = 0)
  186. {
  187. assign(n, static_cast<T>(1));
  188. }
  189. template <class T, class U>
  190. BOOST_CXX14_CONSTEXPR rational(const T& n, const U& d, typename enable_if_c<
  191. (!rational_detail::is_compatible_integer<T, IntType>::value
  192. || !rational_detail::is_compatible_integer<U, IntType>::value)
  193. && std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer
  194. && (std::numeric_limits<T>::radix == std::numeric_limits<IntType>::radix)
  195. && is_convertible<T, IntType>::value &&
  196. std::numeric_limits<U>::is_specialized && std::numeric_limits<U>::is_integer
  197. && (std::numeric_limits<U>::radix == std::numeric_limits<IntType>::radix)
  198. && is_convertible<U, IntType>::value
  199. >::type const* = 0)
  200. {
  201. assign(n, d);
  202. }
  203. template <class T>
  204. BOOST_CXX14_CONSTEXPR typename enable_if_c<
  205. std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer
  206. && !rational_detail::is_compatible_integer<T, IntType>::value
  207. && (std::numeric_limits<T>::radix == std::numeric_limits<IntType>::radix)
  208. && is_convertible<T, IntType>::value,
  209. rational &
  210. >::type operator=(const T& n) { return assign(n, static_cast<T>(1)); }
  211. template <class T, class U>
  212. BOOST_CXX14_CONSTEXPR typename enable_if_c<
  213. (!rational_detail::is_compatible_integer<T, IntType>::value
  214. || !rational_detail::is_compatible_integer<U, IntType>::value)
  215. && std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer
  216. && (std::numeric_limits<T>::radix == std::numeric_limits<IntType>::radix)
  217. && is_convertible<T, IntType>::value &&
  218. std::numeric_limits<U>::is_specialized && std::numeric_limits<U>::is_integer
  219. && (std::numeric_limits<U>::radix == std::numeric_limits<IntType>::radix)
  220. && is_convertible<U, IntType>::value,
  221. rational &
  222. >::type assign(const T& n, const U& d)
  223. {
  224. if(!is_safe_narrowing_conversion(n) || !is_safe_narrowing_conversion(d))
  225. BOOST_THROW_EXCEPTION(bad_rational());
  226. return *this = rational<IntType>(static_cast<IntType>(n), static_cast<IntType>(d));
  227. }
  228. // Access to representation
  229. BOOST_CONSTEXPR
  230. const IntType& numerator() const { return num; }
  231. BOOST_CONSTEXPR
  232. const IntType& denominator() const { return den; }
  233. // Arithmetic assignment operators
  234. BOOST_CXX14_CONSTEXPR rational& operator+= (const rational& r);
  235. BOOST_CXX14_CONSTEXPR rational& operator-= (const rational& r);
  236. BOOST_CXX14_CONSTEXPR rational& operator*= (const rational& r);
  237. BOOST_CXX14_CONSTEXPR rational& operator/= (const rational& r);
  238. template <class T>
  239. BOOST_CXX14_CONSTEXPR typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, rational&>::type operator+= (const T& i)
  240. {
  241. num += i * den;
  242. return *this;
  243. }
  244. template <class T>
  245. BOOST_CXX14_CONSTEXPR typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, rational&>::type operator-= (const T& i)
  246. {
  247. num -= i * den;
  248. return *this;
  249. }
  250. template <class T>
  251. BOOST_CXX14_CONSTEXPR typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, rational&>::type operator*= (const T& i)
  252. {
  253. // Avoid overflow and preserve normalization
  254. IntType gcd = integer::gcd(static_cast<IntType>(i), den);
  255. num *= i / gcd;
  256. den /= gcd;
  257. return *this;
  258. }
  259. template <class T>
  260. BOOST_CXX14_CONSTEXPR typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, rational&>::type operator/= (const T& i)
  261. {
  262. // Avoid repeated construction
  263. IntType const zero(0);
  264. if(i == zero) BOOST_THROW_EXCEPTION(bad_rational());
  265. if(num == zero) return *this;
  266. // Avoid overflow and preserve normalization
  267. IntType const gcd = integer::gcd(num, static_cast<IntType>(i));
  268. num /= gcd;
  269. den *= i / gcd;
  270. if(den < zero) {
  271. num = -num;
  272. den = -den;
  273. }
  274. return *this;
  275. }
  276. // Increment and decrement
  277. BOOST_CXX14_CONSTEXPR const rational& operator++() { num += den; return *this; }
  278. BOOST_CXX14_CONSTEXPR const rational& operator--() { num -= den; return *this; }
  279. BOOST_CXX14_CONSTEXPR rational operator++(int)
  280. {
  281. rational t(*this);
  282. ++(*this);
  283. return t;
  284. }
  285. BOOST_CXX14_CONSTEXPR rational operator--(int)
  286. {
  287. rational t(*this);
  288. --(*this);
  289. return t;
  290. }
  291. // Operator not
  292. BOOST_CONSTEXPR
  293. bool operator!() const { return !num; }
  294. // Boolean conversion
  295. #if BOOST_WORKAROUND(__MWERKS__,<=0x3003)
  296. // The "ISO C++ Template Parser" option in CW 8.3 chokes on the
  297. // following, hence we selectively disable that option for the
  298. // offending memfun.
  299. #pragma parse_mfunc_templ off
  300. #endif
  301. BOOST_CONSTEXPR
  302. operator bool_type() const { return operator !() ? 0 : &helper::parts; }
  303. #if BOOST_WORKAROUND(__MWERKS__,<=0x3003)
  304. #pragma parse_mfunc_templ reset
  305. #endif
  306. // Comparison operators
  307. BOOST_CXX14_CONSTEXPR bool operator< (const rational& r) const;
  308. BOOST_CXX14_CONSTEXPR bool operator> (const rational& r) const { return r < *this; }
  309. BOOST_CONSTEXPR
  310. bool operator== (const rational& r) const;
  311. template <class T>
  312. BOOST_CXX14_CONSTEXPR typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, bool>::type operator< (const T& i) const
  313. {
  314. // Avoid repeated construction
  315. int_type const zero(0);
  316. // Break value into mixed-fraction form, w/ always-nonnegative remainder
  317. BOOST_ASSERT(this->den > zero);
  318. int_type q = this->num / this->den, r = this->num % this->den;
  319. while(r < zero) { r += this->den; --q; }
  320. // Compare with just the quotient, since the remainder always bumps the
  321. // value up. [Since q = floor(n/d), and if n/d < i then q < i, if n/d == i
  322. // then q == i, if n/d == i + r/d then q == i, and if n/d >= i + 1 then
  323. // q >= i + 1 > i; therefore n/d < i iff q < i.]
  324. return q < i;
  325. }
  326. template <class T>
  327. BOOST_CXX14_CONSTEXPR typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, bool>::type operator>(const T& i) const
  328. {
  329. return operator==(i) ? false : !operator<(i);
  330. }
  331. template <class T>
  332. BOOST_CONSTEXPR typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, bool>::type operator== (const T& i) const
  333. {
  334. return ((den == IntType(1)) && (num == i));
  335. }
  336. private:
  337. // Implementation - numerator and denominator (normalized).
  338. // Other possibilities - separate whole-part, or sign, fields?
  339. IntType num;
  340. IntType den;
  341. // Helper functions
  342. static BOOST_CONSTEXPR
  343. int_type inner_gcd( param_type a, param_type b, int_type const &zero =
  344. int_type(0) )
  345. { return b == zero ? a : inner_gcd(b, a % b, zero); }
  346. static BOOST_CONSTEXPR
  347. int_type inner_abs( param_type x, int_type const &zero = int_type(0) )
  348. { return x < zero ? -x : +x; }
  349. // Representation note: Fractions are kept in normalized form at all
  350. // times. normalized form is defined as gcd(num,den) == 1 and den > 0.
  351. // In particular, note that the implementation of abs() below relies
  352. // on den always being positive.
  353. BOOST_CXX14_CONSTEXPR bool test_invariant() const;
  354. BOOST_CXX14_CONSTEXPR void normalize();
  355. static BOOST_CONSTEXPR
  356. bool is_normalized( param_type n, param_type d, int_type const &zero =
  357. int_type(0), int_type const &one = int_type(1) )
  358. {
  359. return d > zero && ( n != zero || d == one ) && inner_abs( inner_gcd(n,
  360. d, zero), zero ) == one;
  361. }
  362. //
  363. // Conversion checks:
  364. //
  365. // (1) From an unsigned type with more digits than IntType:
  366. //
  367. template <class T>
  368. BOOST_CONSTEXPR static typename boost::enable_if_c<(std::numeric_limits<T>::digits > std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == false), bool>::type is_safe_narrowing_conversion(const T& val)
  369. {
  370. return val < (T(1) << std::numeric_limits<IntType>::digits);
  371. }
  372. //
  373. // (2) From a signed type with more digits than IntType, and IntType also signed:
  374. //
  375. template <class T>
  376. BOOST_CONSTEXPR static typename boost::enable_if_c<(std::numeric_limits<T>::digits > std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == true) && (std::numeric_limits<IntType>::is_signed == true), bool>::type is_safe_narrowing_conversion(const T& val)
  377. {
  378. // Note that this check assumes IntType has a 2's complement representation,
  379. // we don't want to try to convert a std::numeric_limits<IntType>::min() to
  380. // a T because that conversion may not be allowed (this happens when IntType
  381. // is from Boost.Multiprecision).
  382. return (val < (T(1) << std::numeric_limits<IntType>::digits)) && (val >= -(T(1) << std::numeric_limits<IntType>::digits));
  383. }
  384. //
  385. // (3) From a signed type with more digits than IntType, and IntType unsigned:
  386. //
  387. template <class T>
  388. BOOST_CONSTEXPR static typename boost::enable_if_c<(std::numeric_limits<T>::digits > std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == true) && (std::numeric_limits<IntType>::is_signed == false), bool>::type is_safe_narrowing_conversion(const T& val)
  389. {
  390. return (val < (T(1) << std::numeric_limits<IntType>::digits)) && (val >= 0);
  391. }
  392. //
  393. // (4) From a signed type with fewer digits than IntType, and IntType unsigned:
  394. //
  395. template <class T>
  396. BOOST_CONSTEXPR static typename boost::enable_if_c<(std::numeric_limits<T>::digits <= std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == true) && (std::numeric_limits<IntType>::is_signed == false), bool>::type is_safe_narrowing_conversion(const T& val)
  397. {
  398. return val >= 0;
  399. }
  400. //
  401. // (5) From an unsigned type with fewer digits than IntType, and IntType signed:
  402. //
  403. template <class T>
  404. BOOST_CONSTEXPR static typename boost::enable_if_c<(std::numeric_limits<T>::digits <= std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == false) && (std::numeric_limits<IntType>::is_signed == true), bool>::type is_safe_narrowing_conversion(const T&)
  405. {
  406. return true;
  407. }
  408. //
  409. // (6) From an unsigned type with fewer digits than IntType, and IntType unsigned:
  410. //
  411. template <class T>
  412. BOOST_CONSTEXPR static typename boost::enable_if_c<(std::numeric_limits<T>::digits <= std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == false) && (std::numeric_limits<IntType>::is_signed == false), bool>::type is_safe_narrowing_conversion(const T&)
  413. {
  414. return true;
  415. }
  416. //
  417. // (7) From an signed type with fewer digits than IntType, and IntType signed:
  418. //
  419. template <class T>
  420. BOOST_CONSTEXPR static typename boost::enable_if_c<(std::numeric_limits<T>::digits <= std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == true) && (std::numeric_limits<IntType>::is_signed == true), bool>::type is_safe_narrowing_conversion(const T&)
  421. {
  422. return true;
  423. }
  424. };
  425. // Unary plus and minus
  426. template <typename IntType>
  427. BOOST_CONSTEXPR
  428. inline rational<IntType> operator+ (const rational<IntType>& r)
  429. {
  430. return r;
  431. }
  432. template <typename IntType>
  433. BOOST_CXX14_CONSTEXPR
  434. inline rational<IntType> operator- (const rational<IntType>& r)
  435. {
  436. return rational<IntType>(static_cast<IntType>(-r.numerator()), r.denominator());
  437. }
  438. // Arithmetic assignment operators
  439. template <typename IntType>
  440. BOOST_CXX14_CONSTEXPR rational<IntType>& rational<IntType>::operator+= (const rational<IntType>& r)
  441. {
  442. // This calculation avoids overflow, and minimises the number of expensive
  443. // calculations. Thanks to Nickolay Mladenov for this algorithm.
  444. //
  445. // Proof:
  446. // We have to compute a/b + c/d, where gcd(a,b)=1 and gcd(b,c)=1.
  447. // Let g = gcd(b,d), and b = b1*g, d=d1*g. Then gcd(b1,d1)=1
  448. //
  449. // The result is (a*d1 + c*b1) / (b1*d1*g).
  450. // Now we have to normalize this ratio.
  451. // Let's assume h | gcd((a*d1 + c*b1), (b1*d1*g)), and h > 1
  452. // If h | b1 then gcd(h,d1)=1 and hence h|(a*d1+c*b1) => h|a.
  453. // But since gcd(a,b1)=1 we have h=1.
  454. // Similarly h|d1 leads to h=1.
  455. // So we have that h | gcd((a*d1 + c*b1) , (b1*d1*g)) => h|g
  456. // Finally we have gcd((a*d1 + c*b1), (b1*d1*g)) = gcd((a*d1 + c*b1), g)
  457. // Which proves that instead of normalizing the result, it is better to
  458. // divide num and den by gcd((a*d1 + c*b1), g)
  459. // Protect against self-modification
  460. IntType r_num = r.num;
  461. IntType r_den = r.den;
  462. IntType g = integer::gcd(den, r_den);
  463. den /= g; // = b1 from the calculations above
  464. num = num * (r_den / g) + r_num * den;
  465. g = integer::gcd(num, g);
  466. num /= g;
  467. den *= r_den/g;
  468. return *this;
  469. }
  470. template <typename IntType>
  471. BOOST_CXX14_CONSTEXPR rational<IntType>& rational<IntType>::operator-= (const rational<IntType>& r)
  472. {
  473. // Protect against self-modification
  474. IntType r_num = r.num;
  475. IntType r_den = r.den;
  476. // This calculation avoids overflow, and minimises the number of expensive
  477. // calculations. It corresponds exactly to the += case above
  478. IntType g = integer::gcd(den, r_den);
  479. den /= g;
  480. num = num * (r_den / g) - r_num * den;
  481. g = integer::gcd(num, g);
  482. num /= g;
  483. den *= r_den/g;
  484. return *this;
  485. }
  486. template <typename IntType>
  487. BOOST_CXX14_CONSTEXPR rational<IntType>& rational<IntType>::operator*= (const rational<IntType>& r)
  488. {
  489. // Protect against self-modification
  490. IntType r_num = r.num;
  491. IntType r_den = r.den;
  492. // Avoid overflow and preserve normalization
  493. IntType gcd1 = integer::gcd(num, r_den);
  494. IntType gcd2 = integer::gcd(r_num, den);
  495. num = (num/gcd1) * (r_num/gcd2);
  496. den = (den/gcd2) * (r_den/gcd1);
  497. return *this;
  498. }
  499. template <typename IntType>
  500. BOOST_CXX14_CONSTEXPR rational<IntType>& rational<IntType>::operator/= (const rational<IntType>& r)
  501. {
  502. // Protect against self-modification
  503. IntType r_num = r.num;
  504. IntType r_den = r.den;
  505. // Avoid repeated construction
  506. IntType zero(0);
  507. // Trap division by zero
  508. if (r_num == zero)
  509. BOOST_THROW_EXCEPTION(bad_rational());
  510. if (num == zero)
  511. return *this;
  512. // Avoid overflow and preserve normalization
  513. IntType gcd1 = integer::gcd(num, r_num);
  514. IntType gcd2 = integer::gcd(r_den, den);
  515. num = (num/gcd1) * (r_den/gcd2);
  516. den = (den/gcd2) * (r_num/gcd1);
  517. if (den < zero) {
  518. num = -num;
  519. den = -den;
  520. }
  521. return *this;
  522. }
  523. //
  524. // Non-member operators: previously these were provided by Boost.Operator, but these had a number of
  525. // drawbacks, most notably, that in order to allow inter-operability with IntType code such as this:
  526. //
  527. // rational<int> r(3);
  528. // assert(r == 3.5); // compiles and passes!!
  529. //
  530. // Happens to be allowed as well :-(
  531. //
  532. // There are three possible cases for each operator:
  533. // 1) rational op rational.
  534. // 2) rational op integer
  535. // 3) integer op rational
  536. // Cases (1) and (2) are folded into the one function.
  537. //
  538. template <class IntType, class Arg>
  539. BOOST_CXX14_CONSTEXPR
  540. inline typename boost::enable_if_c <
  541. rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type
  542. operator + (const rational<IntType>& a, const Arg& b)
  543. {
  544. rational<IntType> t(a);
  545. return t += b;
  546. }
  547. template <class Arg, class IntType>
  548. BOOST_CXX14_CONSTEXPR
  549. inline typename boost::enable_if_c <
  550. rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type
  551. operator + (const Arg& b, const rational<IntType>& a)
  552. {
  553. rational<IntType> t(a);
  554. return t += b;
  555. }
  556. template <class IntType, class Arg>
  557. BOOST_CXX14_CONSTEXPR
  558. inline typename boost::enable_if_c <
  559. rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type
  560. operator - (const rational<IntType>& a, const Arg& b)
  561. {
  562. rational<IntType> t(a);
  563. return t -= b;
  564. }
  565. template <class Arg, class IntType>
  566. BOOST_CXX14_CONSTEXPR
  567. inline typename boost::enable_if_c <
  568. rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type
  569. operator - (const Arg& b, const rational<IntType>& a)
  570. {
  571. rational<IntType> t(a);
  572. return -(t -= b);
  573. }
  574. template <class IntType, class Arg>
  575. BOOST_CXX14_CONSTEXPR
  576. inline typename boost::enable_if_c <
  577. rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type
  578. operator * (const rational<IntType>& a, const Arg& b)
  579. {
  580. rational<IntType> t(a);
  581. return t *= b;
  582. }
  583. template <class Arg, class IntType>
  584. BOOST_CXX14_CONSTEXPR
  585. inline typename boost::enable_if_c <
  586. rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type
  587. operator * (const Arg& b, const rational<IntType>& a)
  588. {
  589. rational<IntType> t(a);
  590. return t *= b;
  591. }
  592. template <class IntType, class Arg>
  593. BOOST_CXX14_CONSTEXPR
  594. inline typename boost::enable_if_c <
  595. rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type
  596. operator / (const rational<IntType>& a, const Arg& b)
  597. {
  598. rational<IntType> t(a);
  599. return t /= b;
  600. }
  601. template <class Arg, class IntType>
  602. BOOST_CXX14_CONSTEXPR
  603. inline typename boost::enable_if_c <
  604. rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type
  605. operator / (const Arg& b, const rational<IntType>& a)
  606. {
  607. rational<IntType> t(b);
  608. return t /= a;
  609. }
  610. template <class IntType, class Arg>
  611. BOOST_CXX14_CONSTEXPR
  612. inline typename boost::enable_if_c <
  613. rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, bool>::type
  614. operator <= (const rational<IntType>& a, const Arg& b)
  615. {
  616. return !(a > b);
  617. }
  618. template <class Arg, class IntType>
  619. BOOST_CXX14_CONSTEXPR
  620. inline typename boost::enable_if_c <
  621. rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type
  622. operator <= (const Arg& b, const rational<IntType>& a)
  623. {
  624. return a >= b;
  625. }
  626. template <class IntType, class Arg>
  627. BOOST_CXX14_CONSTEXPR
  628. inline typename boost::enable_if_c <
  629. rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, bool>::type
  630. operator >= (const rational<IntType>& a, const Arg& b)
  631. {
  632. return !(a < b);
  633. }
  634. template <class Arg, class IntType>
  635. BOOST_CXX14_CONSTEXPR
  636. inline typename boost::enable_if_c <
  637. rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type
  638. operator >= (const Arg& b, const rational<IntType>& a)
  639. {
  640. return a <= b;
  641. }
  642. template <class IntType, class Arg>
  643. BOOST_CONSTEXPR
  644. inline typename boost::enable_if_c <
  645. rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, bool>::type
  646. operator != (const rational<IntType>& a, const Arg& b)
  647. {
  648. return !(a == b);
  649. }
  650. template <class Arg, class IntType>
  651. BOOST_CONSTEXPR
  652. inline typename boost::enable_if_c <
  653. rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type
  654. operator != (const Arg& b, const rational<IntType>& a)
  655. {
  656. return !(b == a);
  657. }
  658. template <class Arg, class IntType>
  659. BOOST_CXX14_CONSTEXPR
  660. inline typename boost::enable_if_c <
  661. rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type
  662. operator < (const Arg& b, const rational<IntType>& a)
  663. {
  664. return a > b;
  665. }
  666. template <class Arg, class IntType>
  667. BOOST_CXX14_CONSTEXPR
  668. inline typename boost::enable_if_c <
  669. rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type
  670. operator > (const Arg& b, const rational<IntType>& a)
  671. {
  672. return a < b;
  673. }
  674. template <class Arg, class IntType>
  675. BOOST_CONSTEXPR
  676. inline typename boost::enable_if_c <
  677. rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type
  678. operator == (const Arg& b, const rational<IntType>& a)
  679. {
  680. return a == b;
  681. }
  682. // Comparison operators
  683. template <typename IntType>
  684. BOOST_CXX14_CONSTEXPR
  685. bool rational<IntType>::operator< (const rational<IntType>& r) const
  686. {
  687. // Avoid repeated construction
  688. int_type const zero( 0 );
  689. // This should really be a class-wide invariant. The reason for these
  690. // checks is that for 2's complement systems, INT_MIN has no corresponding
  691. // positive, so negating it during normalization keeps it INT_MIN, which
  692. // is bad for later calculations that assume a positive denominator.
  693. BOOST_ASSERT( this->den > zero );
  694. BOOST_ASSERT( r.den > zero );
  695. // Determine relative order by expanding each value to its simple continued
  696. // fraction representation using the Euclidian GCD algorithm.
  697. struct { int_type n, d, q, r; }
  698. ts = { this->num, this->den, static_cast<int_type>(this->num / this->den),
  699. static_cast<int_type>(this->num % this->den) },
  700. rs = { r.num, r.den, static_cast<int_type>(r.num / r.den),
  701. static_cast<int_type>(r.num % r.den) };
  702. unsigned reverse = 0u;
  703. // Normalize negative moduli by repeatedly adding the (positive) denominator
  704. // and decrementing the quotient. Later cycles should have all positive
  705. // values, so this only has to be done for the first cycle. (The rules of
  706. // C++ require a nonnegative quotient & remainder for a nonnegative dividend
  707. // & positive divisor.)
  708. while ( ts.r < zero ) { ts.r += ts.d; --ts.q; }
  709. while ( rs.r < zero ) { rs.r += rs.d; --rs.q; }
  710. // Loop through and compare each variable's continued-fraction components
  711. for ( ;; )
  712. {
  713. // The quotients of the current cycle are the continued-fraction
  714. // components. Comparing two c.f. is comparing their sequences,
  715. // stopping at the first difference.
  716. if ( ts.q != rs.q )
  717. {
  718. // Since reciprocation changes the relative order of two variables,
  719. // and c.f. use reciprocals, the less/greater-than test reverses
  720. // after each index. (Start w/ non-reversed @ whole-number place.)
  721. return reverse ? ts.q > rs.q : ts.q < rs.q;
  722. }
  723. // Prepare the next cycle
  724. reverse ^= 1u;
  725. if ( (ts.r == zero) || (rs.r == zero) )
  726. {
  727. // At least one variable's c.f. expansion has ended
  728. break;
  729. }
  730. ts.n = ts.d; ts.d = ts.r;
  731. ts.q = ts.n / ts.d; ts.r = ts.n % ts.d;
  732. rs.n = rs.d; rs.d = rs.r;
  733. rs.q = rs.n / rs.d; rs.r = rs.n % rs.d;
  734. }
  735. // Compare infinity-valued components for otherwise equal sequences
  736. if ( ts.r == rs.r )
  737. {
  738. // Both remainders are zero, so the next (and subsequent) c.f.
  739. // components for both sequences are infinity. Therefore, the sequences
  740. // and their corresponding values are equal.
  741. return false;
  742. }
  743. else
  744. {
  745. #ifdef BOOST_MSVC
  746. #pragma warning(push)
  747. #pragma warning(disable:4800)
  748. #endif
  749. // Exactly one of the remainders is zero, so all following c.f.
  750. // components of that variable are infinity, while the other variable
  751. // has a finite next c.f. component. So that other variable has the
  752. // lesser value (modulo the reversal flag!).
  753. return ( ts.r != zero ) != static_cast<bool>( reverse );
  754. #ifdef BOOST_MSVC
  755. #pragma warning(pop)
  756. #endif
  757. }
  758. }
  759. template <typename IntType>
  760. BOOST_CONSTEXPR
  761. inline bool rational<IntType>::operator== (const rational<IntType>& r) const
  762. {
  763. return ((num == r.num) && (den == r.den));
  764. }
  765. // Invariant check
  766. template <typename IntType>
  767. BOOST_CXX14_CONSTEXPR
  768. inline bool rational<IntType>::test_invariant() const
  769. {
  770. return ( this->den > int_type(0) ) && ( integer::gcd(this->num, this->den) ==
  771. int_type(1) );
  772. }
  773. // Normalisation
  774. template <typename IntType>
  775. BOOST_CXX14_CONSTEXPR void rational<IntType>::normalize()
  776. {
  777. // Avoid repeated construction
  778. IntType zero(0);
  779. if (den == zero)
  780. BOOST_THROW_EXCEPTION(bad_rational());
  781. // Handle the case of zero separately, to avoid division by zero
  782. if (num == zero) {
  783. den = IntType(1);
  784. return;
  785. }
  786. IntType g = integer::gcd(num, den);
  787. num /= g;
  788. den /= g;
  789. if (den < -(std::numeric_limits<IntType>::max)()) {
  790. BOOST_THROW_EXCEPTION(bad_rational("bad rational: non-zero singular denominator"));
  791. }
  792. // Ensure that the denominator is positive
  793. if (den < zero) {
  794. num = -num;
  795. den = -den;
  796. }
  797. BOOST_ASSERT( this->test_invariant() );
  798. }
  799. #ifndef BOOST_NO_IOSTREAM
  800. namespace detail {
  801. // A utility class to reset the format flags for an istream at end
  802. // of scope, even in case of exceptions
  803. struct resetter {
  804. resetter(std::istream& is) : is_(is), f_(is.flags()) {}
  805. ~resetter() { is_.flags(f_); }
  806. std::istream& is_;
  807. std::istream::fmtflags f_; // old GNU c++ lib has no ios_base
  808. };
  809. }
  810. // Input and output
  811. template <typename IntType>
  812. std::istream& operator>> (std::istream& is, rational<IntType>& r)
  813. {
  814. using std::ios;
  815. IntType n = IntType(0), d = IntType(1);
  816. char c = 0;
  817. detail::resetter sentry(is);
  818. if ( is >> n )
  819. {
  820. if ( is.get(c) )
  821. {
  822. if ( c == '/' )
  823. {
  824. if ( is >> std::noskipws >> d )
  825. try {
  826. r.assign( n, d );
  827. } catch ( bad_rational & ) { // normalization fail
  828. try { is.setstate(ios::failbit); }
  829. catch ( ... ) {} // don't throw ios_base::failure...
  830. if ( is.exceptions() & ios::failbit )
  831. throw; // ...but the original exception instead
  832. // ELSE: suppress the exception, use just error flags
  833. }
  834. }
  835. else
  836. is.setstate( ios::failbit );
  837. }
  838. }
  839. return is;
  840. }
  841. // Add manipulators for output format?
  842. template <typename IntType>
  843. std::ostream& operator<< (std::ostream& os, const rational<IntType>& r)
  844. {
  845. // The slash directly precedes the denominator, which has no prefixes.
  846. std::ostringstream ss;
  847. ss.copyfmt( os );
  848. ss.tie( NULL );
  849. ss.exceptions( std::ios::goodbit );
  850. ss.width( 0 );
  851. ss << std::noshowpos << std::noshowbase << '/' << r.denominator();
  852. // The numerator holds the showpos, internal, and showbase flags.
  853. std::string const tail = ss.str();
  854. std::streamsize const w =
  855. os.width() - static_cast<std::streamsize>( tail.size() );
  856. ss.clear();
  857. ss.str( "" );
  858. ss.flags( os.flags() );
  859. ss << std::setw( w < 0 || (os.flags() & std::ios::adjustfield) !=
  860. std::ios::internal ? 0 : w ) << r.numerator();
  861. return os << ss.str() + tail;
  862. }
  863. #endif // BOOST_NO_IOSTREAM
  864. // Type conversion
  865. template <typename T, typename IntType>
  866. BOOST_CONSTEXPR
  867. inline T rational_cast(const rational<IntType>& src)
  868. {
  869. return static_cast<T>(src.numerator())/static_cast<T>(src.denominator());
  870. }
  871. // Do not use any abs() defined on IntType - it isn't worth it, given the
  872. // difficulties involved (Koenig lookup required, there may not *be* an abs()
  873. // defined, etc etc).
  874. template <typename IntType>
  875. BOOST_CXX14_CONSTEXPR
  876. inline rational<IntType> abs(const rational<IntType>& r)
  877. {
  878. return r.numerator() >= IntType(0)? r: -r;
  879. }
  880. namespace integer {
  881. template <typename IntType>
  882. struct gcd_evaluator< rational<IntType> >
  883. {
  884. typedef rational<IntType> result_type,
  885. first_argument_type, second_argument_type;
  886. result_type operator() ( first_argument_type const &a
  887. , second_argument_type const &b
  888. ) const
  889. {
  890. return result_type(integer::gcd(a.numerator(), b.numerator()),
  891. integer::lcm(a.denominator(), b.denominator()));
  892. }
  893. };
  894. template <typename IntType>
  895. struct lcm_evaluator< rational<IntType> >
  896. {
  897. typedef rational<IntType> result_type,
  898. first_argument_type, second_argument_type;
  899. result_type operator() ( first_argument_type const &a
  900. , second_argument_type const &b
  901. ) const
  902. {
  903. return result_type(integer::lcm(a.numerator(), b.numerator()),
  904. integer::gcd(a.denominator(), b.denominator()));
  905. }
  906. };
  907. } // namespace integer
  908. } // namespace boost
  909. #endif // BOOST_RATIONAL_HPP