rational.hpp 39 KB

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