rational.hpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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. // 05 Nov 06 Change rational_cast to not depend on division between different
  20. // types (Daryle Walker)
  21. // 04 Nov 06 Off-load GCD and LCM to Boost.Math; add some invariant checks;
  22. // add std::numeric_limits<> requirement to help GCD (Daryle Walker)
  23. // 31 Oct 06 Recoded both operator< to use round-to-negative-infinity
  24. // divisions; the rational-value version now uses continued fraction
  25. // expansion to avoid overflows, for bug #798357 (Daryle Walker)
  26. // 20 Oct 06 Fix operator bool_type for CW 8.3 (Joaquín M López Muñoz)
  27. // 18 Oct 06 Use EXPLICIT_TEMPLATE_TYPE helper macros from Boost.Config
  28. // (Joaquín M López Muñoz)
  29. // 27 Dec 05 Add Boolean conversion operator (Daryle Walker)
  30. // 28 Sep 02 Use _left versions of operators from operators.hpp
  31. // 05 Jul 01 Recode gcd(), avoiding std::swap (Helmut Zeisel)
  32. // 03 Mar 01 Workarounds for Intel C++ 5.0 (David Abrahams)
  33. // 05 Feb 01 Update operator>> to tighten up input syntax
  34. // 05 Feb 01 Final tidy up of gcd code prior to the new release
  35. // 27 Jan 01 Recode abs() without relying on abs(IntType)
  36. // 21 Jan 01 Include Nickolay Mladenov's operator+= algorithm,
  37. // tidy up a number of areas, use newer features of operators.hpp
  38. // (reduces space overhead to zero), add operator!,
  39. // introduce explicit mixed-mode arithmetic operations
  40. // 12 Jan 01 Include fixes to handle a user-defined IntType better
  41. // 19 Nov 00 Throw on divide by zero in operator /= (John (EBo) David)
  42. // 23 Jun 00 Incorporate changes from Mark Rodgers for Borland C++
  43. // 22 Jun 00 Change _MSC_VER to BOOST_MSVC so other compilers are not
  44. // affected (Beman Dawes)
  45. // 6 Mar 00 Fix operator-= normalization, #include <string> (Jens Maurer)
  46. // 14 Dec 99 Modifications based on comments from the boost list
  47. // 09 Dec 99 Initial Version (Paul Moore)
  48. #ifndef BOOST_RATIONAL_HPP
  49. #define BOOST_RATIONAL_HPP
  50. #include <iostream> // for std::istream and std::ostream
  51. #include <ios> // for std::noskipws
  52. #include <stdexcept> // for std::domain_error
  53. #include <string> // for std::string implicit constructor
  54. #include <boost/operators.hpp> // for boost::addable etc
  55. #include <cstdlib> // for std::abs
  56. #include <boost/call_traits.hpp> // for boost::call_traits
  57. #include <boost/config.hpp> // for BOOST_NO_STDC_NAMESPACE, BOOST_MSVC
  58. #include <boost/detail/workaround.hpp> // for BOOST_WORKAROUND
  59. #include <boost/assert.hpp> // for BOOST_ASSERT
  60. #include <boost/math/common_factor_rt.hpp> // for boost::math::gcd, lcm
  61. #include <limits> // for std::numeric_limits
  62. #include <boost/static_assert.hpp> // for BOOST_STATIC_ASSERT
  63. // Control whether depreciated GCD and LCM functions are included (default: yes)
  64. #ifndef BOOST_CONTROL_RATIONAL_HAS_GCD
  65. #define BOOST_CONTROL_RATIONAL_HAS_GCD 1
  66. #endif
  67. namespace boost {
  68. #if BOOST_CONTROL_RATIONAL_HAS_GCD
  69. template <typename IntType>
  70. IntType gcd(IntType n, IntType m)
  71. {
  72. // Defer to the version in Boost.Math
  73. return math::gcd( n, m );
  74. }
  75. template <typename IntType>
  76. IntType lcm(IntType n, IntType m)
  77. {
  78. // Defer to the version in Boost.Math
  79. return math::lcm( n, m );
  80. }
  81. #endif // BOOST_CONTROL_RATIONAL_HAS_GCD
  82. class bad_rational : public std::domain_error
  83. {
  84. public:
  85. explicit bad_rational() : std::domain_error("bad rational: zero denominator") {}
  86. };
  87. template <typename IntType>
  88. class rational;
  89. template <typename IntType>
  90. rational<IntType> abs(const rational<IntType>& r);
  91. template <typename IntType>
  92. class rational :
  93. less_than_comparable < rational<IntType>,
  94. equality_comparable < rational<IntType>,
  95. less_than_comparable2 < rational<IntType>, IntType,
  96. equality_comparable2 < rational<IntType>, IntType,
  97. addable < rational<IntType>,
  98. subtractable < rational<IntType>,
  99. multipliable < rational<IntType>,
  100. dividable < rational<IntType>,
  101. addable2 < rational<IntType>, IntType,
  102. subtractable2 < rational<IntType>, IntType,
  103. subtractable2_left < rational<IntType>, IntType,
  104. multipliable2 < rational<IntType>, IntType,
  105. dividable2 < rational<IntType>, IntType,
  106. dividable2_left < rational<IntType>, IntType,
  107. incrementable < rational<IntType>,
  108. decrementable < rational<IntType>
  109. > > > > > > > > > > > > > > > >
  110. {
  111. // Class-wide pre-conditions
  112. BOOST_STATIC_ASSERT( ::std::numeric_limits<IntType>::is_specialized );
  113. // Helper types
  114. typedef typename boost::call_traits<IntType>::param_type param_type;
  115. struct helper { IntType parts[2]; };
  116. typedef IntType (helper::* bool_type)[2];
  117. public:
  118. typedef IntType int_type;
  119. rational() : num(0), den(1) {}
  120. rational(param_type n) : num(n), den(1) {}
  121. rational(param_type n, param_type d) : num(n), den(d) { normalize(); }
  122. // Default copy constructor and assignment are fine
  123. // Add assignment from IntType
  124. rational& operator=(param_type n) { return assign(n, 1); }
  125. // Assign in place
  126. rational& assign(param_type n, param_type d);
  127. // Access to representation
  128. IntType numerator() const { return num; }
  129. IntType denominator() const { return den; }
  130. // Arithmetic assignment operators
  131. rational& operator+= (const rational& r);
  132. rational& operator-= (const rational& r);
  133. rational& operator*= (const rational& r);
  134. rational& operator/= (const rational& r);
  135. rational& operator+= (param_type i);
  136. rational& operator-= (param_type i);
  137. rational& operator*= (param_type i);
  138. rational& operator/= (param_type i);
  139. // Increment and decrement
  140. const rational& operator++();
  141. const rational& operator--();
  142. // Operator not
  143. bool operator!() const { return !num; }
  144. // Boolean conversion
  145. #if BOOST_WORKAROUND(__MWERKS__,<=0x3003)
  146. // The "ISO C++ Template Parser" option in CW 8.3 chokes on the
  147. // following, hence we selectively disable that option for the
  148. // offending memfun.
  149. #pragma parse_mfunc_templ off
  150. #endif
  151. operator bool_type() const { return operator !() ? 0 : &helper::parts; }
  152. #if BOOST_WORKAROUND(__MWERKS__,<=0x3003)
  153. #pragma parse_mfunc_templ reset
  154. #endif
  155. // Comparison operators
  156. bool operator< (const rational& r) const;
  157. bool operator== (const rational& r) const;
  158. bool operator< (param_type i) const;
  159. bool operator> (param_type i) const;
  160. bool operator== (param_type i) const;
  161. private:
  162. // Implementation - numerator and denominator (normalized).
  163. // Other possibilities - separate whole-part, or sign, fields?
  164. IntType num;
  165. IntType den;
  166. // Representation note: Fractions are kept in normalized form at all
  167. // times. normalized form is defined as gcd(num,den) == 1 and den > 0.
  168. // In particular, note that the implementation of abs() below relies
  169. // on den always being positive.
  170. bool test_invariant() const;
  171. void normalize();
  172. };
  173. // Assign in place
  174. template <typename IntType>
  175. inline rational<IntType>& rational<IntType>::assign(param_type n, param_type d)
  176. {
  177. num = n;
  178. den = d;
  179. normalize();
  180. return *this;
  181. }
  182. // Unary plus and minus
  183. template <typename IntType>
  184. inline rational<IntType> operator+ (const rational<IntType>& r)
  185. {
  186. return r;
  187. }
  188. template <typename IntType>
  189. inline rational<IntType> operator- (const rational<IntType>& r)
  190. {
  191. return rational<IntType>(-r.numerator(), r.denominator());
  192. }
  193. // Arithmetic assignment operators
  194. template <typename IntType>
  195. rational<IntType>& rational<IntType>::operator+= (const rational<IntType>& r)
  196. {
  197. // This calculation avoids overflow, and minimises the number of expensive
  198. // calculations. Thanks to Nickolay Mladenov for this algorithm.
  199. //
  200. // Proof:
  201. // We have to compute a/b + c/d, where gcd(a,b)=1 and gcd(b,c)=1.
  202. // Let g = gcd(b,d), and b = b1*g, d=d1*g. Then gcd(b1,d1)=1
  203. //
  204. // The result is (a*d1 + c*b1) / (b1*d1*g).
  205. // Now we have to normalize this ratio.
  206. // Let's assume h | gcd((a*d1 + c*b1), (b1*d1*g)), and h > 1
  207. // If h | b1 then gcd(h,d1)=1 and hence h|(a*d1+c*b1) => h|a.
  208. // But since gcd(a,b1)=1 we have h=1.
  209. // Similarly h|d1 leads to h=1.
  210. // So we have that h | gcd((a*d1 + c*b1) , (b1*d1*g)) => h|g
  211. // Finally we have gcd((a*d1 + c*b1), (b1*d1*g)) = gcd((a*d1 + c*b1), g)
  212. // Which proves that instead of normalizing the result, it is better to
  213. // divide num and den by gcd((a*d1 + c*b1), g)
  214. // Protect against self-modification
  215. IntType r_num = r.num;
  216. IntType r_den = r.den;
  217. IntType g = math::gcd(den, r_den);
  218. den /= g; // = b1 from the calculations above
  219. num = num * (r_den / g) + r_num * den;
  220. g = math::gcd(num, g);
  221. num /= g;
  222. den *= r_den/g;
  223. return *this;
  224. }
  225. template <typename IntType>
  226. rational<IntType>& rational<IntType>::operator-= (const rational<IntType>& r)
  227. {
  228. // Protect against self-modification
  229. IntType r_num = r.num;
  230. IntType r_den = r.den;
  231. // This calculation avoids overflow, and minimises the number of expensive
  232. // calculations. It corresponds exactly to the += case above
  233. IntType g = math::gcd(den, r_den);
  234. den /= g;
  235. num = num * (r_den / g) - r_num * den;
  236. g = math::gcd(num, g);
  237. num /= g;
  238. den *= r_den/g;
  239. return *this;
  240. }
  241. template <typename IntType>
  242. rational<IntType>& rational<IntType>::operator*= (const rational<IntType>& r)
  243. {
  244. // Protect against self-modification
  245. IntType r_num = r.num;
  246. IntType r_den = r.den;
  247. // Avoid overflow and preserve normalization
  248. IntType gcd1 = math::gcd(num, r_den);
  249. IntType gcd2 = math::gcd(r_num, den);
  250. num = (num/gcd1) * (r_num/gcd2);
  251. den = (den/gcd2) * (r_den/gcd1);
  252. return *this;
  253. }
  254. template <typename IntType>
  255. rational<IntType>& rational<IntType>::operator/= (const rational<IntType>& r)
  256. {
  257. // Protect against self-modification
  258. IntType r_num = r.num;
  259. IntType r_den = r.den;
  260. // Avoid repeated construction
  261. IntType zero(0);
  262. // Trap division by zero
  263. if (r_num == zero)
  264. throw bad_rational();
  265. if (num == zero)
  266. return *this;
  267. // Avoid overflow and preserve normalization
  268. IntType gcd1 = math::gcd(num, r_num);
  269. IntType gcd2 = math::gcd(r_den, den);
  270. num = (num/gcd1) * (r_den/gcd2);
  271. den = (den/gcd2) * (r_num/gcd1);
  272. if (den < zero) {
  273. num = -num;
  274. den = -den;
  275. }
  276. return *this;
  277. }
  278. // Mixed-mode operators
  279. template <typename IntType>
  280. inline rational<IntType>&
  281. rational<IntType>::operator+= (param_type i)
  282. {
  283. return operator+= (rational<IntType>(i));
  284. }
  285. template <typename IntType>
  286. inline rational<IntType>&
  287. rational<IntType>::operator-= (param_type i)
  288. {
  289. return operator-= (rational<IntType>(i));
  290. }
  291. template <typename IntType>
  292. inline rational<IntType>&
  293. rational<IntType>::operator*= (param_type i)
  294. {
  295. return operator*= (rational<IntType>(i));
  296. }
  297. template <typename IntType>
  298. inline rational<IntType>&
  299. rational<IntType>::operator/= (param_type i)
  300. {
  301. return operator/= (rational<IntType>(i));
  302. }
  303. // Increment and decrement
  304. template <typename IntType>
  305. inline const rational<IntType>& rational<IntType>::operator++()
  306. {
  307. // This can never denormalise the fraction
  308. num += den;
  309. return *this;
  310. }
  311. template <typename IntType>
  312. inline const rational<IntType>& rational<IntType>::operator--()
  313. {
  314. // This can never denormalise the fraction
  315. num -= den;
  316. return *this;
  317. }
  318. // Comparison operators
  319. template <typename IntType>
  320. bool rational<IntType>::operator< (const rational<IntType>& r) const
  321. {
  322. // Avoid repeated construction
  323. int_type const zero( 0 );
  324. // This should really be a class-wide invariant. The reason for these
  325. // checks is that for 2's complement systems, INT_MIN has no corresponding
  326. // positive, so negating it during normalization keeps it INT_MIN, which
  327. // is bad for later calculations that assume a positive denominator.
  328. BOOST_ASSERT( this->den > zero );
  329. BOOST_ASSERT( r.den > zero );
  330. // Determine relative order by expanding each value to its simple continued
  331. // fraction representation using the Euclidian GCD algorithm.
  332. struct { int_type n, d, q, r; } ts = { this->num, this->den, this->num /
  333. this->den, this->num % this->den }, rs = { r.num, r.den, r.num / r.den,
  334. r.num % r.den };
  335. unsigned reverse = 0u;
  336. // Normalize negative moduli by repeatedly adding the (positive) denominator
  337. // and decrementing the quotient. Later cycles should have all positive
  338. // values, so this only has to be done for the first cycle. (The rules of
  339. // C++ require a nonnegative quotient & remainder for a nonnegative dividend
  340. // & positive divisor.)
  341. while ( ts.r < zero ) { ts.r += ts.d; --ts.q; }
  342. while ( rs.r < zero ) { rs.r += rs.d; --rs.q; }
  343. // Loop through and compare each variable's continued-fraction components
  344. while ( true )
  345. {
  346. // The quotients of the current cycle are the continued-fraction
  347. // components. Comparing two c.f. is comparing their sequences,
  348. // stopping at the first difference.
  349. if ( ts.q != rs.q )
  350. {
  351. // Since reciprocation changes the relative order of two variables,
  352. // and c.f. use reciprocals, the less/greater-than test reverses
  353. // after each index. (Start w/ non-reversed @ whole-number place.)
  354. return reverse ? ts.q > rs.q : ts.q < rs.q;
  355. }
  356. // Prepare the next cycle
  357. reverse ^= 1u;
  358. if ( (ts.r == zero) || (rs.r == zero) )
  359. {
  360. // At least one variable's c.f. expansion has ended
  361. break;
  362. }
  363. ts.n = ts.d; ts.d = ts.r;
  364. ts.q = ts.n / ts.d; ts.r = ts.n % ts.d;
  365. rs.n = rs.d; rs.d = rs.r;
  366. rs.q = rs.n / rs.d; rs.r = rs.n % rs.d;
  367. }
  368. // Compare infinity-valued components for otherwise equal sequences
  369. if ( ts.r == rs.r )
  370. {
  371. // Both remainders are zero, so the next (and subsequent) c.f.
  372. // components for both sequences are infinity. Therefore, the sequences
  373. // and their corresponding values are equal.
  374. return false;
  375. }
  376. else
  377. {
  378. #ifdef BOOST_MSVC
  379. #pragma warning(push)
  380. #pragma warning(disable:4800)
  381. #endif
  382. // Exactly one of the remainders is zero, so all following c.f.
  383. // components of that variable are infinity, while the other variable
  384. // has a finite next c.f. component. So that other variable has the
  385. // lesser value (modulo the reversal flag!).
  386. return ( ts.r != zero ) != static_cast<bool>( reverse );
  387. #ifdef BOOST_MSVC
  388. #pragma warning(pop)
  389. #endif
  390. }
  391. }
  392. template <typename IntType>
  393. bool rational<IntType>::operator< (param_type i) const
  394. {
  395. // Avoid repeated construction
  396. int_type const zero( 0 );
  397. // Break value into mixed-fraction form, w/ always-nonnegative remainder
  398. BOOST_ASSERT( this->den > zero );
  399. int_type q = this->num / this->den, r = this->num % this->den;
  400. while ( r < zero ) { r += this->den; --q; }
  401. // Compare with just the quotient, since the remainder always bumps the
  402. // value up. [Since q = floor(n/d), and if n/d < i then q < i, if n/d == i
  403. // then q == i, if n/d == i + r/d then q == i, and if n/d >= i + 1 then
  404. // q >= i + 1 > i; therefore n/d < i iff q < i.]
  405. return q < i;
  406. }
  407. template <typename IntType>
  408. bool rational<IntType>::operator> (param_type i) const
  409. {
  410. // Trap equality first
  411. if (num == i && den == IntType(1))
  412. return false;
  413. // Otherwise, we can use operator<
  414. return !operator<(i);
  415. }
  416. template <typename IntType>
  417. inline bool rational<IntType>::operator== (const rational<IntType>& r) const
  418. {
  419. return ((num == r.num) && (den == r.den));
  420. }
  421. template <typename IntType>
  422. inline bool rational<IntType>::operator== (param_type i) const
  423. {
  424. return ((den == IntType(1)) && (num == i));
  425. }
  426. // Invariant check
  427. template <typename IntType>
  428. inline bool rational<IntType>::test_invariant() const
  429. {
  430. return ( this->den > int_type(0) ) && ( math::gcd(this->num, this->den) ==
  431. int_type(1) );
  432. }
  433. // Normalisation
  434. template <typename IntType>
  435. void rational<IntType>::normalize()
  436. {
  437. // Avoid repeated construction
  438. IntType zero(0);
  439. if (den == zero)
  440. throw bad_rational();
  441. // Handle the case of zero separately, to avoid division by zero
  442. if (num == zero) {
  443. den = IntType(1);
  444. return;
  445. }
  446. IntType g = math::gcd(num, den);
  447. num /= g;
  448. den /= g;
  449. // Ensure that the denominator is positive
  450. if (den < zero) {
  451. num = -num;
  452. den = -den;
  453. }
  454. BOOST_ASSERT( this->test_invariant() );
  455. }
  456. namespace detail {
  457. // A utility class to reset the format flags for an istream at end
  458. // of scope, even in case of exceptions
  459. struct resetter {
  460. resetter(std::istream& is) : is_(is), f_(is.flags()) {}
  461. ~resetter() { is_.flags(f_); }
  462. std::istream& is_;
  463. std::istream::fmtflags f_; // old GNU c++ lib has no ios_base
  464. };
  465. }
  466. // Input and output
  467. template <typename IntType>
  468. std::istream& operator>> (std::istream& is, rational<IntType>& r)
  469. {
  470. IntType n = IntType(0), d = IntType(1);
  471. char c = 0;
  472. detail::resetter sentry(is);
  473. is >> n;
  474. c = is.get();
  475. if (c != '/')
  476. is.clear(std::istream::badbit); // old GNU c++ lib has no ios_base
  477. #if !defined(__GNUC__) || (defined(__GNUC__) && (__GNUC__ >= 3)) || defined __SGI_STL_PORT
  478. is >> std::noskipws;
  479. #else
  480. is.unsetf(ios::skipws); // compiles, but seems to have no effect.
  481. #endif
  482. is >> d;
  483. if (is)
  484. r.assign(n, d);
  485. return is;
  486. }
  487. // Add manipulators for output format?
  488. template <typename IntType>
  489. std::ostream& operator<< (std::ostream& os, const rational<IntType>& r)
  490. {
  491. os << r.numerator() << '/' << r.denominator();
  492. return os;
  493. }
  494. // Type conversion
  495. template <typename T, typename IntType>
  496. inline T rational_cast(
  497. const rational<IntType>& src BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE(T))
  498. {
  499. return static_cast<T>(src.numerator())/static_cast<T>(src.denominator());
  500. }
  501. // Do not use any abs() defined on IntType - it isn't worth it, given the
  502. // difficulties involved (Koenig lookup required, there may not *be* an abs()
  503. // defined, etc etc).
  504. template <typename IntType>
  505. inline rational<IntType> abs(const rational<IntType>& r)
  506. {
  507. if (r.numerator() >= IntType(0))
  508. return r;
  509. return rational<IntType>(-r.numerator(), r.denominator());
  510. }
  511. } // namespace boost
  512. #endif // BOOST_RATIONAL_HPP