rational.hpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  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. 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. 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. 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. 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. 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. 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. 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. rational& operator+= (const rational& r);
  235. rational& operator-= (const rational& r);
  236. rational& operator*= (const rational& r);
  237. rational& operator/= (const rational& r);
  238. template <class T>
  239. 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. 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. 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. 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. const rational& operator++() { num += den; return *this; }
  278. const rational& operator--() { num -= den; return *this; }
  279. rational operator++(int)
  280. {
  281. rational t(*this);
  282. ++(*this);
  283. return t;
  284. }
  285. 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. bool operator< (const rational& r) const;
  308. bool operator> (const rational& r) const { return r < *this; }
  309. BOOST_CONSTEXPR
  310. bool operator== (const rational& r) const;
  311. template <class T>
  312. 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. 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. bool test_invariant() const;
  354. 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. inline rational<IntType> operator- (const rational<IntType>& r)
  434. {
  435. return rational<IntType>(static_cast<IntType>(-r.numerator()), r.denominator());
  436. }
  437. // Arithmetic assignment operators
  438. template <typename IntType>
  439. rational<IntType>& rational<IntType>::operator+= (const rational<IntType>& r)
  440. {
  441. // This calculation avoids overflow, and minimises the number of expensive
  442. // calculations. Thanks to Nickolay Mladenov for this algorithm.
  443. //
  444. // Proof:
  445. // We have to compute a/b + c/d, where gcd(a,b)=1 and gcd(b,c)=1.
  446. // Let g = gcd(b,d), and b = b1*g, d=d1*g. Then gcd(b1,d1)=1
  447. //
  448. // The result is (a*d1 + c*b1) / (b1*d1*g).
  449. // Now we have to normalize this ratio.
  450. // Let's assume h | gcd((a*d1 + c*b1), (b1*d1*g)), and h > 1
  451. // If h | b1 then gcd(h,d1)=1 and hence h|(a*d1+c*b1) => h|a.
  452. // But since gcd(a,b1)=1 we have h=1.
  453. // Similarly h|d1 leads to h=1.
  454. // So we have that h | gcd((a*d1 + c*b1) , (b1*d1*g)) => h|g
  455. // Finally we have gcd((a*d1 + c*b1), (b1*d1*g)) = gcd((a*d1 + c*b1), g)
  456. // Which proves that instead of normalizing the result, it is better to
  457. // divide num and den by gcd((a*d1 + c*b1), g)
  458. // Protect against self-modification
  459. IntType r_num = r.num;
  460. IntType r_den = r.den;
  461. IntType g = integer::gcd(den, r_den);
  462. den /= g; // = b1 from the calculations above
  463. num = num * (r_den / g) + r_num * den;
  464. g = integer::gcd(num, g);
  465. num /= g;
  466. den *= r_den/g;
  467. return *this;
  468. }
  469. template <typename IntType>
  470. rational<IntType>& rational<IntType>::operator-= (const rational<IntType>& r)
  471. {
  472. // Protect against self-modification
  473. IntType r_num = r.num;
  474. IntType r_den = r.den;
  475. // This calculation avoids overflow, and minimises the number of expensive
  476. // calculations. It corresponds exactly to the += case above
  477. IntType g = integer::gcd(den, r_den);
  478. den /= g;
  479. num = num * (r_den / g) - r_num * den;
  480. g = integer::gcd(num, g);
  481. num /= g;
  482. den *= r_den/g;
  483. return *this;
  484. }
  485. template <typename IntType>
  486. rational<IntType>& rational<IntType>::operator*= (const rational<IntType>& r)
  487. {
  488. // Protect against self-modification
  489. IntType r_num = r.num;
  490. IntType r_den = r.den;
  491. // Avoid overflow and preserve normalization
  492. IntType gcd1 = integer::gcd(num, r_den);
  493. IntType gcd2 = integer::gcd(r_num, den);
  494. num = (num/gcd1) * (r_num/gcd2);
  495. den = (den/gcd2) * (r_den/gcd1);
  496. return *this;
  497. }
  498. template <typename IntType>
  499. rational<IntType>& rational<IntType>::operator/= (const rational<IntType>& r)
  500. {
  501. // Protect against self-modification
  502. IntType r_num = r.num;
  503. IntType r_den = r.den;
  504. // Avoid repeated construction
  505. IntType zero(0);
  506. // Trap division by zero
  507. if (r_num == zero)
  508. BOOST_THROW_EXCEPTION(bad_rational());
  509. if (num == zero)
  510. return *this;
  511. // Avoid overflow and preserve normalization
  512. IntType gcd1 = integer::gcd(num, r_num);
  513. IntType gcd2 = integer::gcd(r_den, den);
  514. num = (num/gcd1) * (r_den/gcd2);
  515. den = (den/gcd2) * (r_num/gcd1);
  516. if (den < zero) {
  517. num = -num;
  518. den = -den;
  519. }
  520. return *this;
  521. }
  522. //
  523. // Non-member operators: previously these were provided by Boost.Operator, but these had a number of
  524. // drawbacks, most notably, that in order to allow inter-operability with IntType code such as this:
  525. //
  526. // rational<int> r(3);
  527. // assert(r == 3.5); // compiles and passes!!
  528. //
  529. // Happens to be allowed as well :-(
  530. //
  531. // There are three possible cases for each operator:
  532. // 1) rational op rational.
  533. // 2) rational op integer
  534. // 3) integer op rational
  535. // Cases (1) and (2) are folded into the one function.
  536. //
  537. template <class IntType, class Arg>
  538. inline typename boost::enable_if_c <
  539. rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type
  540. operator + (const rational<IntType>& a, const Arg& b)
  541. {
  542. rational<IntType> t(a);
  543. return t += b;
  544. }
  545. template <class Arg, class IntType>
  546. inline typename boost::enable_if_c <
  547. rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type
  548. operator + (const Arg& b, const rational<IntType>& a)
  549. {
  550. rational<IntType> t(a);
  551. return t += b;
  552. }
  553. template <class IntType, class Arg>
  554. inline typename boost::enable_if_c <
  555. rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type
  556. operator - (const rational<IntType>& a, const Arg& b)
  557. {
  558. rational<IntType> t(a);
  559. return t -= b;
  560. }
  561. template <class Arg, class IntType>
  562. inline typename boost::enable_if_c <
  563. rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type
  564. operator - (const Arg& b, const rational<IntType>& a)
  565. {
  566. rational<IntType> t(a);
  567. return -(t -= b);
  568. }
  569. template <class IntType, class Arg>
  570. inline typename boost::enable_if_c <
  571. rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type
  572. operator * (const rational<IntType>& a, const Arg& b)
  573. {
  574. rational<IntType> t(a);
  575. return t *= b;
  576. }
  577. template <class Arg, class IntType>
  578. inline typename boost::enable_if_c <
  579. rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type
  580. operator * (const Arg& b, const rational<IntType>& a)
  581. {
  582. rational<IntType> t(a);
  583. return t *= b;
  584. }
  585. template <class IntType, class Arg>
  586. inline typename boost::enable_if_c <
  587. rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type
  588. operator / (const rational<IntType>& a, const Arg& b)
  589. {
  590. rational<IntType> t(a);
  591. return t /= b;
  592. }
  593. template <class Arg, class IntType>
  594. inline typename boost::enable_if_c <
  595. rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type
  596. operator / (const Arg& b, const rational<IntType>& a)
  597. {
  598. rational<IntType> t(b);
  599. return t /= a;
  600. }
  601. template <class IntType, class Arg>
  602. inline typename boost::enable_if_c <
  603. rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, bool>::type
  604. operator <= (const rational<IntType>& a, const Arg& b)
  605. {
  606. return !(a > b);
  607. }
  608. template <class Arg, class IntType>
  609. inline typename boost::enable_if_c <
  610. rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type
  611. operator <= (const Arg& b, const rational<IntType>& a)
  612. {
  613. return a >= b;
  614. }
  615. template <class IntType, class Arg>
  616. inline typename boost::enable_if_c <
  617. rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, bool>::type
  618. operator >= (const rational<IntType>& a, const Arg& b)
  619. {
  620. return !(a < b);
  621. }
  622. template <class Arg, class IntType>
  623. inline typename boost::enable_if_c <
  624. rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type
  625. operator >= (const Arg& b, const rational<IntType>& a)
  626. {
  627. return a <= b;
  628. }
  629. template <class IntType, class Arg>
  630. inline typename boost::enable_if_c <
  631. rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, bool>::type
  632. operator != (const rational<IntType>& a, const Arg& b)
  633. {
  634. return !(a == b);
  635. }
  636. template <class Arg, class IntType>
  637. inline typename boost::enable_if_c <
  638. rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type
  639. operator != (const Arg& b, const rational<IntType>& a)
  640. {
  641. return !(b == a);
  642. }
  643. template <class Arg, class IntType>
  644. inline typename boost::enable_if_c <
  645. rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type
  646. operator < (const Arg& b, const rational<IntType>& a)
  647. {
  648. return a > b;
  649. }
  650. template <class Arg, class IntType>
  651. inline typename boost::enable_if_c <
  652. rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type
  653. operator > (const Arg& b, const rational<IntType>& a)
  654. {
  655. return a < b;
  656. }
  657. template <class Arg, class IntType>
  658. inline typename boost::enable_if_c <
  659. rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type
  660. operator == (const Arg& b, const rational<IntType>& a)
  661. {
  662. return a == b;
  663. }
  664. // Comparison operators
  665. template <typename IntType>
  666. bool rational<IntType>::operator< (const rational<IntType>& r) const
  667. {
  668. // Avoid repeated construction
  669. int_type const zero( 0 );
  670. // This should really be a class-wide invariant. The reason for these
  671. // checks is that for 2's complement systems, INT_MIN has no corresponding
  672. // positive, so negating it during normalization keeps it INT_MIN, which
  673. // is bad for later calculations that assume a positive denominator.
  674. BOOST_ASSERT( this->den > zero );
  675. BOOST_ASSERT( r.den > zero );
  676. // Determine relative order by expanding each value to its simple continued
  677. // fraction representation using the Euclidian GCD algorithm.
  678. struct { int_type n, d, q, r; }
  679. ts = { this->num, this->den, static_cast<int_type>(this->num / this->den),
  680. static_cast<int_type>(this->num % this->den) },
  681. rs = { r.num, r.den, static_cast<int_type>(r.num / r.den),
  682. static_cast<int_type>(r.num % r.den) };
  683. unsigned reverse = 0u;
  684. // Normalize negative moduli by repeatedly adding the (positive) denominator
  685. // and decrementing the quotient. Later cycles should have all positive
  686. // values, so this only has to be done for the first cycle. (The rules of
  687. // C++ require a nonnegative quotient & remainder for a nonnegative dividend
  688. // & positive divisor.)
  689. while ( ts.r < zero ) { ts.r += ts.d; --ts.q; }
  690. while ( rs.r < zero ) { rs.r += rs.d; --rs.q; }
  691. // Loop through and compare each variable's continued-fraction components
  692. for ( ;; )
  693. {
  694. // The quotients of the current cycle are the continued-fraction
  695. // components. Comparing two c.f. is comparing their sequences,
  696. // stopping at the first difference.
  697. if ( ts.q != rs.q )
  698. {
  699. // Since reciprocation changes the relative order of two variables,
  700. // and c.f. use reciprocals, the less/greater-than test reverses
  701. // after each index. (Start w/ non-reversed @ whole-number place.)
  702. return reverse ? ts.q > rs.q : ts.q < rs.q;
  703. }
  704. // Prepare the next cycle
  705. reverse ^= 1u;
  706. if ( (ts.r == zero) || (rs.r == zero) )
  707. {
  708. // At least one variable's c.f. expansion has ended
  709. break;
  710. }
  711. ts.n = ts.d; ts.d = ts.r;
  712. ts.q = ts.n / ts.d; ts.r = ts.n % ts.d;
  713. rs.n = rs.d; rs.d = rs.r;
  714. rs.q = rs.n / rs.d; rs.r = rs.n % rs.d;
  715. }
  716. // Compare infinity-valued components for otherwise equal sequences
  717. if ( ts.r == rs.r )
  718. {
  719. // Both remainders are zero, so the next (and subsequent) c.f.
  720. // components for both sequences are infinity. Therefore, the sequences
  721. // and their corresponding values are equal.
  722. return false;
  723. }
  724. else
  725. {
  726. #ifdef BOOST_MSVC
  727. #pragma warning(push)
  728. #pragma warning(disable:4800)
  729. #endif
  730. // Exactly one of the remainders is zero, so all following c.f.
  731. // components of that variable are infinity, while the other variable
  732. // has a finite next c.f. component. So that other variable has the
  733. // lesser value (modulo the reversal flag!).
  734. return ( ts.r != zero ) != static_cast<bool>( reverse );
  735. #ifdef BOOST_MSVC
  736. #pragma warning(pop)
  737. #endif
  738. }
  739. }
  740. template <typename IntType>
  741. BOOST_CONSTEXPR
  742. inline bool rational<IntType>::operator== (const rational<IntType>& r) const
  743. {
  744. return ((num == r.num) && (den == r.den));
  745. }
  746. // Invariant check
  747. template <typename IntType>
  748. inline bool rational<IntType>::test_invariant() const
  749. {
  750. return ( this->den > int_type(0) ) && ( integer::gcd(this->num, this->den) ==
  751. int_type(1) );
  752. }
  753. // Normalisation
  754. template <typename IntType>
  755. void rational<IntType>::normalize()
  756. {
  757. // Avoid repeated construction
  758. IntType zero(0);
  759. if (den == zero)
  760. BOOST_THROW_EXCEPTION(bad_rational());
  761. // Handle the case of zero separately, to avoid division by zero
  762. if (num == zero) {
  763. den = IntType(1);
  764. return;
  765. }
  766. IntType g = integer::gcd(num, den);
  767. num /= g;
  768. den /= g;
  769. if (den < -(std::numeric_limits<IntType>::max)()) {
  770. BOOST_THROW_EXCEPTION(bad_rational("bad rational: non-zero singular denominator"));
  771. }
  772. // Ensure that the denominator is positive
  773. if (den < zero) {
  774. num = -num;
  775. den = -den;
  776. }
  777. BOOST_ASSERT( this->test_invariant() );
  778. }
  779. #ifndef BOOST_NO_IOSTREAM
  780. namespace detail {
  781. // A utility class to reset the format flags for an istream at end
  782. // of scope, even in case of exceptions
  783. struct resetter {
  784. resetter(std::istream& is) : is_(is), f_(is.flags()) {}
  785. ~resetter() { is_.flags(f_); }
  786. std::istream& is_;
  787. std::istream::fmtflags f_; // old GNU c++ lib has no ios_base
  788. };
  789. }
  790. // Input and output
  791. template <typename IntType>
  792. std::istream& operator>> (std::istream& is, rational<IntType>& r)
  793. {
  794. using std::ios;
  795. IntType n = IntType(0), d = IntType(1);
  796. char c = 0;
  797. detail::resetter sentry(is);
  798. if ( is >> n )
  799. {
  800. if ( is.get(c) )
  801. {
  802. if ( c == '/' )
  803. {
  804. if ( is >> std::noskipws >> d )
  805. try {
  806. r.assign( n, d );
  807. } catch ( bad_rational & ) { // normalization fail
  808. try { is.setstate(ios::failbit); }
  809. catch ( ... ) {} // don't throw ios_base::failure...
  810. if ( is.exceptions() & ios::failbit )
  811. throw; // ...but the original exception instead
  812. // ELSE: suppress the exception, use just error flags
  813. }
  814. }
  815. else
  816. is.setstate( ios::failbit );
  817. }
  818. }
  819. return is;
  820. }
  821. // Add manipulators for output format?
  822. template <typename IntType>
  823. std::ostream& operator<< (std::ostream& os, const rational<IntType>& r)
  824. {
  825. // The slash directly precedes the denominator, which has no prefixes.
  826. std::ostringstream ss;
  827. ss.copyfmt( os );
  828. ss.tie( NULL );
  829. ss.exceptions( std::ios::goodbit );
  830. ss.width( 0 );
  831. ss << std::noshowpos << std::noshowbase << '/' << r.denominator();
  832. // The numerator holds the showpos, internal, and showbase flags.
  833. std::string const tail = ss.str();
  834. std::streamsize const w =
  835. os.width() - static_cast<std::streamsize>( tail.size() );
  836. ss.clear();
  837. ss.str( "" );
  838. ss.flags( os.flags() );
  839. ss << std::setw( w < 0 || (os.flags() & std::ios::adjustfield) !=
  840. std::ios::internal ? 0 : w ) << r.numerator();
  841. return os << ss.str() + tail;
  842. }
  843. #endif // BOOST_NO_IOSTREAM
  844. // Type conversion
  845. template <typename T, typename IntType>
  846. BOOST_CONSTEXPR
  847. inline T rational_cast(const rational<IntType>& src)
  848. {
  849. return static_cast<T>(src.numerator())/static_cast<T>(src.denominator());
  850. }
  851. // Do not use any abs() defined on IntType - it isn't worth it, given the
  852. // difficulties involved (Koenig lookup required, there may not *be* an abs()
  853. // defined, etc etc).
  854. template <typename IntType>
  855. inline rational<IntType> abs(const rational<IntType>& r)
  856. {
  857. return r.numerator() >= IntType(0)? r: -r;
  858. }
  859. namespace integer {
  860. template <typename IntType>
  861. struct gcd_evaluator< rational<IntType> >
  862. {
  863. typedef rational<IntType> result_type,
  864. first_argument_type, second_argument_type;
  865. result_type operator() ( first_argument_type const &a
  866. , second_argument_type const &b
  867. ) const
  868. {
  869. return result_type(integer::gcd(a.numerator(), b.numerator()),
  870. integer::lcm(a.denominator(), b.denominator()));
  871. }
  872. };
  873. template <typename IntType>
  874. struct lcm_evaluator< rational<IntType> >
  875. {
  876. typedef rational<IntType> result_type,
  877. first_argument_type, second_argument_type;
  878. result_type operator() ( first_argument_type const &a
  879. , second_argument_type const &b
  880. ) const
  881. {
  882. return result_type(integer::lcm(a.numerator(), b.numerator()),
  883. integer::gcd(a.denominator(), b.denominator()));
  884. }
  885. };
  886. } // namespace integer
  887. } // namespace boost
  888. #endif // BOOST_RATIONAL_HPP