1 // Boost rational.hpp header file ------------------------------------------//
3 // (C) Copyright Paul Moore 1999. Permission to copy, use, modify, sell and
4 // distribute this software is granted provided this copyright notice appears
5 // in all copies. This software is provided "as is" without express or
6 // implied warranty, and with no claim as to its suitability for any purpose.
8 // boostinspect:nolicense (don't complain about the lack of a Boost license)
9 // (Paul Moore hasn't been in contact for years, so there's no way to change the
12 // See http://www.boost.org/libs/rational for documentation.
15 // Thanks to the boost mailing list in general for useful comments.
16 // Particular contributions included:
17 // Andrew D Jewell, for reminding me to take care to avoid overflow
18 // Ed Brey, for many comments, including picking up on some dreadful typos
19 // Stephen Silver contributed the test suite and comments on user-defined
21 // Nickolay Mladenov, for the implementation of operator+=
24 // 02 Sep 13 Remove unneeded forward declarations; tweak private helper
25 // function (Daryle Walker)
26 // 30 Aug 13 Improve exception safety of "assign"; start modernizing I/O code
28 // 27 Aug 13 Add cross-version constructor template, plus some private helper
29 // functions; add constructor to exception class to take custom
30 // messages (Daryle Walker)
31 // 25 Aug 13 Add constexpr qualification wherever possible (Daryle Walker)
32 // 05 May 12 Reduced use of implicit gcd (Mario Lang)
33 // 05 Nov 06 Change rational_cast to not depend on division between different
34 // types (Daryle Walker)
35 // 04 Nov 06 Off-load GCD and LCM to Boost.Integer; add some invariant checks;
36 // add std::numeric_limits<> requirement to help GCD (Daryle Walker)
37 // 31 Oct 06 Recoded both operator< to use round-to-negative-infinity
38 // divisions; the rational-value version now uses continued fraction
39 // expansion to avoid overflows, for bug #798357 (Daryle Walker)
40 // 20 Oct 06 Fix operator bool_type for CW 8.3 (Joaquín M López Muñoz)
41 // 18 Oct 06 Use EXPLICIT_TEMPLATE_TYPE helper macros from Boost.Config
42 // (Joaquín M López Muñoz)
43 // 27 Dec 05 Add Boolean conversion operator (Daryle Walker)
44 // 28 Sep 02 Use _left versions of operators from operators.hpp
45 // 05 Jul 01 Recode gcd(), avoiding std::swap (Helmut Zeisel)
46 // 03 Mar 01 Workarounds for Intel C++ 5.0 (David Abrahams)
47 // 05 Feb 01 Update operator>> to tighten up input syntax
48 // 05 Feb 01 Final tidy up of gcd code prior to the new release
49 // 27 Jan 01 Recode abs() without relying on abs(IntType)
50 // 21 Jan 01 Include Nickolay Mladenov's operator+= algorithm,
51 // tidy up a number of areas, use newer features of operators.hpp
52 // (reduces space overhead to zero), add operator!,
53 // introduce explicit mixed-mode arithmetic operations
54 // 12 Jan 01 Include fixes to handle a user-defined IntType better
55 // 19 Nov 00 Throw on divide by zero in operator /= (John (EBo) David)
56 // 23 Jun 00 Incorporate changes from Mark Rodgers for Borland C++
57 // 22 Jun 00 Change _MSC_VER to BOOST_MSVC so other compilers are not
58 // affected (Beman Dawes)
59 // 6 Mar 00 Fix operator-= normalization, #include <string> (Jens Maurer)
60 // 14 Dec 99 Modifications based on comments from the boost list
61 // 09 Dec 99 Initial Version (Paul Moore)
63 #ifndef BOOST_RATIONAL_HPP
64 #define BOOST_RATIONAL_HPP
66 #include <boost/config.hpp> // for BOOST_NO_STDC_NAMESPACE, BOOST_MSVC, etc
67 #ifndef BOOST_NO_IOSTREAM
68 #include <iomanip> // for std::setw
69 #include <ios> // for std::noskipws, streamsize
70 #include <istream> // for std::istream
71 #include <ostream> // for std::ostream
72 #include <sstream> // for std::ostringstream
74 #include <cstddef> // for NULL
75 #include <stdexcept> // for std::domain_error
76 #include <string> // for std::string implicit constructor
77 #include <boost/operators.hpp> // for boost::addable etc
78 #include <cstdlib> // for std::abs
79 #include <boost/call_traits.hpp> // for boost::call_traits
80 #include <boost/detail/workaround.hpp> // for BOOST_WORKAROUND
81 #include <boost/assert.hpp> // for BOOST_ASSERT
82 #include <boost/integer/common_factor_rt.hpp> // for boost::integer::gcd, lcm
83 #include <limits> // for std::numeric_limits
84 #include <boost/static_assert.hpp> // for BOOST_STATIC_ASSERT
85 #include <boost/throw_exception.hpp>
86 #include <boost/utility/enable_if.hpp>
87 #include <boost/type_traits/is_convertible.hpp>
88 #include <boost/type_traits/is_class.hpp>
89 #include <boost/type_traits/is_same.hpp>
91 // Control whether depreciated GCD and LCM functions are included (default: yes)
92 #ifndef BOOST_CONTROL_RATIONAL_HAS_GCD
93 #define BOOST_CONTROL_RATIONAL_HAS_GCD 1
98 #if BOOST_CONTROL_RATIONAL_HAS_GCD
99 template <typename IntType>
100 IntType gcd(IntType n, IntType m)
102 // Defer to the version in Boost.Integer
103 return integer::gcd( n, m );
106 template <typename IntType>
107 IntType lcm(IntType n, IntType m)
109 // Defer to the version in Boost.Integer
110 return integer::lcm( n, m );
112 #endif // BOOST_CONTROL_RATIONAL_HAS_GCD
114 namespace rational_detail{
116 template <class FromInt, class ToInt>
117 struct is_compatible_integer
119 BOOST_STATIC_CONSTANT(bool, value = ((std::numeric_limits<FromInt>::is_specialized && std::numeric_limits<FromInt>::is_integer
120 && (std::numeric_limits<FromInt>::digits <= std::numeric_limits<ToInt>::digits)
121 && (std::numeric_limits<FromInt>::radix == std::numeric_limits<ToInt>::radix)
122 && ((std::numeric_limits<FromInt>::is_signed == false) || (std::numeric_limits<ToInt>::is_signed == true))
123 && is_convertible<FromInt, ToInt>::value)
124 || is_same<FromInt, ToInt>::value)
125 || (is_class<ToInt>::value && is_class<FromInt>::value && is_convertible<FromInt, ToInt>::value));
130 class bad_rational : public std::domain_error
133 explicit bad_rational() : std::domain_error("bad rational: zero denominator") {}
134 explicit bad_rational( char const *what ) : std::domain_error( what ) {}
137 template <typename IntType>
140 // Class-wide pre-conditions
141 BOOST_STATIC_ASSERT( ::std::numeric_limits<IntType>::is_specialized );
144 typedef typename boost::call_traits<IntType>::param_type param_type;
146 struct helper { IntType parts[2]; };
147 typedef IntType (helper::* bool_type)[2];
151 typedef IntType int_type;
154 rational() : num(0), den(1) {}
156 BOOST_CONSTEXPR rational(const T& n, typename enable_if_c<
157 rational_detail::is_compatible_integer<T, IntType>::value
158 >::type const* = 0) : num(n), den(1) {}
159 template <class T, class U>
160 rational(const T& n, const U& d, typename enable_if_c<
161 rational_detail::is_compatible_integer<T, IntType>::value && rational_detail::is_compatible_integer<U, IntType>::value
162 >::type const* = 0) : num(n), den(d) {
166 template < typename NewType >
167 BOOST_CONSTEXPR explicit
168 rational(rational<NewType> const &r, typename enable_if_c<rational_detail::is_compatible_integer<NewType, IntType>::value>::type const* = 0)
169 : num(r.numerator()), den(is_normalized(int_type(r.numerator()),
170 int_type(r.denominator())) ? r.denominator() :
171 (BOOST_THROW_EXCEPTION(bad_rational("bad rational: denormalized conversion")), 0)){}
173 template < typename NewType >
174 BOOST_CONSTEXPR explicit
175 rational(rational<NewType> const &r, typename disable_if_c<rational_detail::is_compatible_integer<NewType, IntType>::value>::type const* = 0)
176 : num(r.numerator()), den(is_normalized(int_type(r.numerator()),
177 int_type(r.denominator())) && is_safe_narrowing_conversion(r.denominator()) && is_safe_narrowing_conversion(r.numerator()) ? r.denominator() :
178 (BOOST_THROW_EXCEPTION(bad_rational("bad rational: denormalized conversion")), 0)){}
179 // Default copy constructor and assignment are fine
181 // Add assignment from IntType
183 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)); }
188 template <class T, class U>
189 typename enable_if_c<
190 rational_detail::is_compatible_integer<T, IntType>::value && rational_detail::is_compatible_integer<U, IntType>::value, rational &
191 >::type assign(const T& n, const U& d)
193 return *this = rational<IntType>(static_cast<IntType>(n), static_cast<IntType>(d));
196 // The following overloads should probably *not* be provided -
197 // but are provided for backwards compatibity reasons only.
198 // These allow for construction/assignment from types that
199 // are wider than IntType only if there is an implicit
200 // conversion from T to IntType, they will throw a bad_rational
201 // if the conversion results in loss of precision or undefined behaviour.
204 rational(const T& n, 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
211 assign(n, static_cast<T>(1));
213 template <class T, class U>
214 rational(const T& n, const U& d, typename enable_if_c<
215 (!rational_detail::is_compatible_integer<T, IntType>::value
216 || !rational_detail::is_compatible_integer<U, IntType>::value)
217 && std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer
218 && (std::numeric_limits<T>::radix == std::numeric_limits<IntType>::radix)
219 && is_convertible<T, IntType>::value &&
220 std::numeric_limits<U>::is_specialized && std::numeric_limits<U>::is_integer
221 && (std::numeric_limits<U>::radix == std::numeric_limits<IntType>::radix)
222 && is_convertible<U, IntType>::value
228 typename enable_if_c<
229 std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer
230 && !rational_detail::is_compatible_integer<T, IntType>::value
231 && (std::numeric_limits<T>::radix == std::numeric_limits<IntType>::radix)
232 && is_convertible<T, IntType>::value,
234 >::type operator=(const T& n) { return assign(n, static_cast<T>(1)); }
236 template <class T, class U>
237 typename enable_if_c<
238 (!rational_detail::is_compatible_integer<T, IntType>::value
239 || !rational_detail::is_compatible_integer<U, IntType>::value)
240 && std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer
241 && (std::numeric_limits<T>::radix == std::numeric_limits<IntType>::radix)
242 && is_convertible<T, IntType>::value &&
243 std::numeric_limits<U>::is_specialized && std::numeric_limits<U>::is_integer
244 && (std::numeric_limits<U>::radix == std::numeric_limits<IntType>::radix)
245 && is_convertible<U, IntType>::value,
247 >::type assign(const T& n, const U& d)
249 if(!is_safe_narrowing_conversion(n) || !is_safe_narrowing_conversion(d))
250 BOOST_THROW_EXCEPTION(bad_rational());
251 return *this = rational<IntType>(static_cast<IntType>(n), static_cast<IntType>(d));
254 // Access to representation
256 const IntType& numerator() const { return num; }
258 const IntType& denominator() const { return den; }
260 // Arithmetic assignment operators
261 rational& operator+= (const rational& r);
262 rational& operator-= (const rational& r);
263 rational& operator*= (const rational& r);
264 rational& operator/= (const rational& r);
267 typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, rational&>::type operator+= (const T& i)
273 typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, rational&>::type operator-= (const T& i)
279 typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, rational&>::type operator*= (const T& i)
281 // Avoid overflow and preserve normalization
282 IntType gcd = integer::gcd(static_cast<IntType>(i), den);
288 typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, rational&>::type operator/= (const T& i)
290 // Avoid repeated construction
291 IntType const zero(0);
293 if(i == zero) BOOST_THROW_EXCEPTION(bad_rational());
294 if(num == zero) return *this;
296 // Avoid overflow and preserve normalization
297 IntType const gcd = integer::gcd(num, static_cast<IntType>(i));
309 // Increment and decrement
310 const rational& operator++() { num += den; return *this; }
311 const rational& operator--() { num -= den; return *this; }
313 rational operator++(int)
319 rational operator--(int)
328 bool operator!() const { return !num; }
330 // Boolean conversion
332 #if BOOST_WORKAROUND(__MWERKS__,<=0x3003)
333 // The "ISO C++ Template Parser" option in CW 8.3 chokes on the
334 // following, hence we selectively disable that option for the
336 #pragma parse_mfunc_templ off
340 operator bool_type() const { return operator !() ? 0 : &helper::parts; }
342 #if BOOST_WORKAROUND(__MWERKS__,<=0x3003)
343 #pragma parse_mfunc_templ reset
346 // Comparison operators
347 bool operator< (const rational& r) const;
348 bool operator> (const rational& r) const { return r < *this; }
350 bool operator== (const rational& r) const;
353 typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, bool>::type operator< (const T& i) const
355 // Avoid repeated construction
356 int_type const zero(0);
358 // Break value into mixed-fraction form, w/ always-nonnegative remainder
359 BOOST_ASSERT(this->den > zero);
360 int_type q = this->num / this->den, r = this->num % this->den;
361 while(r < zero) { r += this->den; --q; }
363 // Compare with just the quotient, since the remainder always bumps the
364 // value up. [Since q = floor(n/d), and if n/d < i then q < i, if n/d == i
365 // then q == i, if n/d == i + r/d then q == i, and if n/d >= i + 1 then
366 // q >= i + 1 > i; therefore n/d < i iff q < i.]
370 typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, bool>::type operator>(const T& i) const
372 return operator==(i) ? false : !operator<(i);
375 BOOST_CONSTEXPR typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, bool>::type operator== (const T& i) const
377 return ((den == IntType(1)) && (num == i));
381 // Implementation - numerator and denominator (normalized).
382 // Other possibilities - separate whole-part, or sign, fields?
387 static BOOST_CONSTEXPR
388 int_type inner_gcd( param_type a, param_type b, int_type const &zero =
390 { return b == zero ? a : inner_gcd(b, a % b, zero); }
392 static BOOST_CONSTEXPR
393 int_type inner_abs( param_type x, int_type const &zero = int_type(0) )
394 { return x < zero ? -x : +x; }
396 // Representation note: Fractions are kept in normalized form at all
397 // times. normalized form is defined as gcd(num,den) == 1 and den > 0.
398 // In particular, note that the implementation of abs() below relies
399 // on den always being positive.
400 bool test_invariant() const;
403 static BOOST_CONSTEXPR
404 bool is_normalized( param_type n, param_type d, int_type const &zero =
405 int_type(0), int_type const &one = int_type(1) )
407 return d > zero && ( n != zero || d == one ) && inner_abs( inner_gcd(n,
408 d, zero), zero ) == one;
411 // Conversion checks:
413 // (1) From an unsigned type with more digits than IntType:
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 == false), bool>::type is_safe_narrowing_conversion(const T& val)
418 return val < (T(1) << std::numeric_limits<IntType>::digits);
421 // (2) From a signed type with more digits than IntType, and IntType also signed:
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 == true) && (std::numeric_limits<IntType>::is_signed == true), bool>::type is_safe_narrowing_conversion(const T& val)
426 // Note that this check assumes IntType has a 2's complement representation,
427 // we don't want to try to convert a std::numeric_limits<IntType>::min() to
428 // a T because that conversion may not be allowed (this happens when IntType
429 // is from Boost.Multiprecision).
430 return (val < (T(1) << std::numeric_limits<IntType>::digits)) && (val >= -(T(1) << std::numeric_limits<IntType>::digits));
433 // (3) From a signed type with more digits than IntType, and IntType unsigned:
436 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)
438 return (val < (T(1) << std::numeric_limits<IntType>::digits)) && (val >= 0);
441 // (4) From a signed type with fewer digits than IntType, and IntType unsigned:
444 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)
449 // (5) From an unsigned type with fewer digits than IntType, and IntType signed:
452 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&)
457 // (6) From an unsigned type with fewer digits than IntType, and IntType unsigned:
460 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&)
465 // (7) From an signed type with fewer digits than IntType, and IntType signed:
468 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&)
474 // Unary plus and minus
475 template <typename IntType>
477 inline rational<IntType> operator+ (const rational<IntType>& r)
482 template <typename IntType>
483 inline rational<IntType> operator- (const rational<IntType>& r)
485 return rational<IntType>(static_cast<IntType>(-r.numerator()), r.denominator());
488 // Arithmetic assignment operators
489 template <typename IntType>
490 rational<IntType>& rational<IntType>::operator+= (const rational<IntType>& r)
492 // This calculation avoids overflow, and minimises the number of expensive
493 // calculations. Thanks to Nickolay Mladenov for this algorithm.
496 // We have to compute a/b + c/d, where gcd(a,b)=1 and gcd(b,c)=1.
497 // Let g = gcd(b,d), and b = b1*g, d=d1*g. Then gcd(b1,d1)=1
499 // The result is (a*d1 + c*b1) / (b1*d1*g).
500 // Now we have to normalize this ratio.
501 // Let's assume h | gcd((a*d1 + c*b1), (b1*d1*g)), and h > 1
502 // If h | b1 then gcd(h,d1)=1 and hence h|(a*d1+c*b1) => h|a.
503 // But since gcd(a,b1)=1 we have h=1.
504 // Similarly h|d1 leads to h=1.
505 // So we have that h | gcd((a*d1 + c*b1) , (b1*d1*g)) => h|g
506 // Finally we have gcd((a*d1 + c*b1), (b1*d1*g)) = gcd((a*d1 + c*b1), g)
507 // Which proves that instead of normalizing the result, it is better to
508 // divide num and den by gcd((a*d1 + c*b1), g)
510 // Protect against self-modification
511 IntType r_num = r.num;
512 IntType r_den = r.den;
514 IntType g = integer::gcd(den, r_den);
515 den /= g; // = b1 from the calculations above
516 num = num * (r_den / g) + r_num * den;
517 g = integer::gcd(num, g);
524 template <typename IntType>
525 rational<IntType>& rational<IntType>::operator-= (const rational<IntType>& r)
527 // Protect against self-modification
528 IntType r_num = r.num;
529 IntType r_den = r.den;
531 // This calculation avoids overflow, and minimises the number of expensive
532 // calculations. It corresponds exactly to the += case above
533 IntType g = integer::gcd(den, r_den);
535 num = num * (r_den / g) - r_num * den;
536 g = integer::gcd(num, g);
543 template <typename IntType>
544 rational<IntType>& rational<IntType>::operator*= (const rational<IntType>& r)
546 // Protect against self-modification
547 IntType r_num = r.num;
548 IntType r_den = r.den;
550 // Avoid overflow and preserve normalization
551 IntType gcd1 = integer::gcd(num, r_den);
552 IntType gcd2 = integer::gcd(r_num, den);
553 num = (num/gcd1) * (r_num/gcd2);
554 den = (den/gcd2) * (r_den/gcd1);
558 template <typename IntType>
559 rational<IntType>& rational<IntType>::operator/= (const rational<IntType>& r)
561 // Protect against self-modification
562 IntType r_num = r.num;
563 IntType r_den = r.den;
565 // Avoid repeated construction
568 // Trap division by zero
570 BOOST_THROW_EXCEPTION(bad_rational());
574 // Avoid overflow and preserve normalization
575 IntType gcd1 = integer::gcd(num, r_num);
576 IntType gcd2 = integer::gcd(r_den, den);
577 num = (num/gcd1) * (r_den/gcd2);
578 den = (den/gcd2) * (r_num/gcd1);
589 // Non-member operators: previously these were provided by Boost.Operator, but these had a number of
590 // drawbacks, most notably, that in order to allow inter-operability with IntType code such as this:
592 // rational<int> r(3);
593 // assert(r == 3.5); // compiles and passes!!
595 // Happens to be allowed as well :-(
597 // There are three possible cases for each operator:
598 // 1) rational op rational.
599 // 2) rational op integer
600 // 3) integer op rational
601 // Cases (1) and (2) are folded into the one function.
603 template <class IntType, class Arg>
604 inline typename boost::enable_if_c <
605 rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type
606 operator + (const rational<IntType>& a, const Arg& b)
608 rational<IntType> t(a);
611 template <class Arg, class IntType>
612 inline typename boost::enable_if_c <
613 rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type
614 operator + (const Arg& b, const rational<IntType>& a)
616 rational<IntType> t(a);
620 template <class IntType, class Arg>
621 inline typename boost::enable_if_c <
622 rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type
623 operator - (const rational<IntType>& a, const Arg& b)
625 rational<IntType> t(a);
628 template <class Arg, class IntType>
629 inline typename boost::enable_if_c <
630 rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type
631 operator - (const Arg& b, const rational<IntType>& a)
633 rational<IntType> t(a);
637 template <class IntType, class Arg>
638 inline typename boost::enable_if_c <
639 rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type
640 operator * (const rational<IntType>& a, const Arg& b)
642 rational<IntType> t(a);
645 template <class Arg, class IntType>
646 inline typename boost::enable_if_c <
647 rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type
648 operator * (const Arg& b, const rational<IntType>& a)
650 rational<IntType> t(a);
654 template <class IntType, class Arg>
655 inline typename boost::enable_if_c <
656 rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type
657 operator / (const rational<IntType>& a, const Arg& b)
659 rational<IntType> t(a);
662 template <class Arg, class IntType>
663 inline typename boost::enable_if_c <
664 rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type
665 operator / (const Arg& b, const rational<IntType>& a)
667 rational<IntType> t(b);
671 template <class IntType, class Arg>
672 inline typename boost::enable_if_c <
673 rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, bool>::type
674 operator <= (const rational<IntType>& a, const Arg& b)
678 template <class Arg, class IntType>
679 inline typename boost::enable_if_c <
680 rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type
681 operator <= (const Arg& b, const rational<IntType>& a)
686 template <class IntType, class Arg>
687 inline typename boost::enable_if_c <
688 rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, bool>::type
689 operator >= (const rational<IntType>& a, const Arg& b)
693 template <class Arg, class IntType>
694 inline typename boost::enable_if_c <
695 rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type
696 operator >= (const Arg& b, const rational<IntType>& a)
701 template <class IntType, class Arg>
702 inline typename boost::enable_if_c <
703 rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, bool>::type
704 operator != (const rational<IntType>& a, const Arg& b)
708 template <class Arg, class IntType>
709 inline typename boost::enable_if_c <
710 rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type
711 operator != (const Arg& b, const rational<IntType>& a)
716 template <class Arg, class IntType>
717 inline typename boost::enable_if_c <
718 rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type
719 operator < (const Arg& b, const rational<IntType>& a)
723 template <class Arg, class IntType>
724 inline typename boost::enable_if_c <
725 rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type
726 operator > (const Arg& b, const rational<IntType>& a)
730 template <class Arg, class IntType>
731 inline typename boost::enable_if_c <
732 rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type
733 operator == (const Arg& b, const rational<IntType>& a)
738 // Comparison operators
739 template <typename IntType>
740 bool rational<IntType>::operator< (const rational<IntType>& r) const
742 // Avoid repeated construction
743 int_type const zero( 0 );
745 // This should really be a class-wide invariant. The reason for these
746 // checks is that for 2's complement systems, INT_MIN has no corresponding
747 // positive, so negating it during normalization keeps it INT_MIN, which
748 // is bad for later calculations that assume a positive denominator.
749 BOOST_ASSERT( this->den > zero );
750 BOOST_ASSERT( r.den > zero );
752 // Determine relative order by expanding each value to its simple continued
753 // fraction representation using the Euclidian GCD algorithm.
754 struct { int_type n, d, q, r; }
755 ts = { this->num, this->den, static_cast<int_type>(this->num / this->den),
756 static_cast<int_type>(this->num % this->den) },
757 rs = { r.num, r.den, static_cast<int_type>(r.num / r.den),
758 static_cast<int_type>(r.num % r.den) };
759 unsigned reverse = 0u;
761 // Normalize negative moduli by repeatedly adding the (positive) denominator
762 // and decrementing the quotient. Later cycles should have all positive
763 // values, so this only has to be done for the first cycle. (The rules of
764 // C++ require a nonnegative quotient & remainder for a nonnegative dividend
765 // & positive divisor.)
766 while ( ts.r < zero ) { ts.r += ts.d; --ts.q; }
767 while ( rs.r < zero ) { rs.r += rs.d; --rs.q; }
769 // Loop through and compare each variable's continued-fraction components
772 // The quotients of the current cycle are the continued-fraction
773 // components. Comparing two c.f. is comparing their sequences,
774 // stopping at the first difference.
777 // Since reciprocation changes the relative order of two variables,
778 // and c.f. use reciprocals, the less/greater-than test reverses
779 // after each index. (Start w/ non-reversed @ whole-number place.)
780 return reverse ? ts.q > rs.q : ts.q < rs.q;
783 // Prepare the next cycle
786 if ( (ts.r == zero) || (rs.r == zero) )
788 // At least one variable's c.f. expansion has ended
792 ts.n = ts.d; ts.d = ts.r;
793 ts.q = ts.n / ts.d; ts.r = ts.n % ts.d;
794 rs.n = rs.d; rs.d = rs.r;
795 rs.q = rs.n / rs.d; rs.r = rs.n % rs.d;
798 // Compare infinity-valued components for otherwise equal sequences
801 // Both remainders are zero, so the next (and subsequent) c.f.
802 // components for both sequences are infinity. Therefore, the sequences
803 // and their corresponding values are equal.
809 #pragma warning(push)
810 #pragma warning(disable:4800)
812 // Exactly one of the remainders is zero, so all following c.f.
813 // components of that variable are infinity, while the other variable
814 // has a finite next c.f. component. So that other variable has the
815 // lesser value (modulo the reversal flag!).
816 return ( ts.r != zero ) != static_cast<bool>( reverse );
823 template <typename IntType>
825 inline bool rational<IntType>::operator== (const rational<IntType>& r) const
827 return ((num == r.num) && (den == r.den));
831 template <typename IntType>
832 inline bool rational<IntType>::test_invariant() const
834 return ( this->den > int_type(0) ) && ( integer::gcd(this->num, this->den) ==
839 template <typename IntType>
840 void rational<IntType>::normalize()
842 // Avoid repeated construction
846 BOOST_THROW_EXCEPTION(bad_rational());
848 // Handle the case of zero separately, to avoid division by zero
854 IntType g = integer::gcd(num, den);
859 // Ensure that the denominator is positive
865 // ...But acknowledge that the previous step doesn't always work.
866 // (Nominally, this should be done before the mutating steps, but this
867 // member function is only called during the constructor, so we never have
868 // to worry about zombie objects.)
870 BOOST_THROW_EXCEPTION(bad_rational("bad rational: non-zero singular denominator"));
872 BOOST_ASSERT( this->test_invariant() );
875 #ifndef BOOST_NO_IOSTREAM
878 // A utility class to reset the format flags for an istream at end
879 // of scope, even in case of exceptions
881 resetter(std::istream& is) : is_(is), f_(is.flags()) {}
882 ~resetter() { is_.flags(f_); }
884 std::istream::fmtflags f_; // old GNU c++ lib has no ios_base
890 template <typename IntType>
891 std::istream& operator>> (std::istream& is, rational<IntType>& r)
895 IntType n = IntType(0), d = IntType(1);
897 detail::resetter sentry(is);
905 if ( is >> std::noskipws >> d )
908 } catch ( bad_rational & ) { // normalization fail
909 try { is.setstate(ios::failbit); }
910 catch ( ... ) {} // don't throw ios_base::failure...
911 if ( is.exceptions() & ios::failbit )
912 throw; // ...but the original exception instead
913 // ELSE: suppress the exception, use just error flags
917 is.setstate( ios::failbit );
924 // Add manipulators for output format?
925 template <typename IntType>
926 std::ostream& operator<< (std::ostream& os, const rational<IntType>& r)
928 // The slash directly precedes the denominator, which has no prefixes.
929 std::ostringstream ss;
933 ss.exceptions( std::ios::goodbit );
935 ss << std::noshowpos << std::noshowbase << '/' << r.denominator();
937 // The numerator holds the showpos, internal, and showbase flags.
938 std::string const tail = ss.str();
939 std::streamsize const w =
940 os.width() - static_cast<std::streamsize>( tail.size() );
944 ss.flags( os.flags() );
945 ss << std::setw( w < 0 || (os.flags() & std::ios::adjustfield) !=
946 std::ios::internal ? 0 : w ) << r.numerator();
947 return os << ss.str() + tail;
949 #endif // BOOST_NO_IOSTREAM
952 template <typename T, typename IntType>
954 inline T rational_cast(const rational<IntType>& src)
956 return static_cast<T>(src.numerator())/static_cast<T>(src.denominator());
959 // Do not use any abs() defined on IntType - it isn't worth it, given the
960 // difficulties involved (Koenig lookup required, there may not *be* an abs()
961 // defined, etc etc).
962 template <typename IntType>
963 inline rational<IntType> abs(const rational<IntType>& r)
965 return r.numerator() >= IntType(0)? r: -r;
970 template <typename IntType>
971 struct gcd_evaluator< rational<IntType> >
973 typedef rational<IntType> result_type,
974 first_argument_type, second_argument_type;
975 result_type operator() ( first_argument_type const &a
976 , second_argument_type const &b
979 return result_type(integer::gcd(a.numerator(), b.numerator()),
980 integer::lcm(a.denominator(), b.denominator()));
984 template <typename IntType>
985 struct lcm_evaluator< rational<IntType> >
987 typedef rational<IntType> result_type,
988 first_argument_type, second_argument_type;
989 result_type operator() ( first_argument_type const &a
990 , second_argument_type const &b
993 return result_type(integer::lcm(a.numerator(), b.numerator()),
994 integer::gcd(a.denominator(), b.denominator()));
998 } // namespace integer
1000 } // namespace boost
1002 #endif // BOOST_RATIONAL_HPP