Chris@16: // Boost rational.hpp header file ------------------------------------------// Chris@16: Chris@16: // (C) Copyright Paul Moore 1999. Permission to copy, use, modify, sell and Chris@16: // distribute this software is granted provided this copyright notice appears Chris@16: // in all copies. This software is provided "as is" without express or Chris@16: // implied warranty, and with no claim as to its suitability for any purpose. Chris@16: Chris@16: // boostinspect:nolicense (don't complain about the lack of a Boost license) Chris@16: // (Paul Moore hasn't been in contact for years, so there's no way to change the Chris@16: // license.) Chris@16: Chris@16: // See http://www.boost.org/libs/rational for documentation. Chris@16: Chris@16: // Credits: Chris@16: // Thanks to the boost mailing list in general for useful comments. Chris@16: // Particular contributions included: Chris@16: // Andrew D Jewell, for reminding me to take care to avoid overflow Chris@16: // Ed Brey, for many comments, including picking up on some dreadful typos Chris@16: // Stephen Silver contributed the test suite and comments on user-defined Chris@16: // IntType Chris@16: // Nickolay Mladenov, for the implementation of operator+= Chris@16: Chris@16: // Revision History Chris@101: // 02 Sep 13 Remove unneeded forward declarations; tweak private helper Chris@101: // function (Daryle Walker) Chris@101: // 30 Aug 13 Improve exception safety of "assign"; start modernizing I/O code Chris@101: // (Daryle Walker) Chris@101: // 27 Aug 13 Add cross-version constructor template, plus some private helper Chris@101: // functions; add constructor to exception class to take custom Chris@101: // messages (Daryle Walker) Chris@101: // 25 Aug 13 Add constexpr qualification wherever possible (Daryle Walker) Chris@101: // 05 May 12 Reduced use of implicit gcd (Mario Lang) Chris@16: // 05 Nov 06 Change rational_cast to not depend on division between different Chris@16: // types (Daryle Walker) Chris@16: // 04 Nov 06 Off-load GCD and LCM to Boost.Math; add some invariant checks; Chris@16: // add std::numeric_limits<> requirement to help GCD (Daryle Walker) Chris@16: // 31 Oct 06 Recoded both operator< to use round-to-negative-infinity Chris@16: // divisions; the rational-value version now uses continued fraction Chris@16: // expansion to avoid overflows, for bug #798357 (Daryle Walker) Chris@16: // 20 Oct 06 Fix operator bool_type for CW 8.3 (Joaquín M López Muñoz) Chris@16: // 18 Oct 06 Use EXPLICIT_TEMPLATE_TYPE helper macros from Boost.Config Chris@16: // (Joaquín M López Muñoz) Chris@16: // 27 Dec 05 Add Boolean conversion operator (Daryle Walker) Chris@16: // 28 Sep 02 Use _left versions of operators from operators.hpp Chris@16: // 05 Jul 01 Recode gcd(), avoiding std::swap (Helmut Zeisel) Chris@16: // 03 Mar 01 Workarounds for Intel C++ 5.0 (David Abrahams) Chris@16: // 05 Feb 01 Update operator>> to tighten up input syntax Chris@16: // 05 Feb 01 Final tidy up of gcd code prior to the new release Chris@16: // 27 Jan 01 Recode abs() without relying on abs(IntType) Chris@16: // 21 Jan 01 Include Nickolay Mladenov's operator+= algorithm, Chris@16: // tidy up a number of areas, use newer features of operators.hpp Chris@16: // (reduces space overhead to zero), add operator!, Chris@16: // introduce explicit mixed-mode arithmetic operations Chris@16: // 12 Jan 01 Include fixes to handle a user-defined IntType better Chris@16: // 19 Nov 00 Throw on divide by zero in operator /= (John (EBo) David) Chris@16: // 23 Jun 00 Incorporate changes from Mark Rodgers for Borland C++ Chris@16: // 22 Jun 00 Change _MSC_VER to BOOST_MSVC so other compilers are not Chris@16: // affected (Beman Dawes) Chris@16: // 6 Mar 00 Fix operator-= normalization, #include (Jens Maurer) Chris@16: // 14 Dec 99 Modifications based on comments from the boost list Chris@16: // 09 Dec 99 Initial Version (Paul Moore) Chris@16: Chris@16: #ifndef BOOST_RATIONAL_HPP Chris@16: #define BOOST_RATIONAL_HPP Chris@16: Chris@101: #include // for BOOST_NO_STDC_NAMESPACE, BOOST_MSVC, etc Chris@101: #ifndef BOOST_NO_IOSTREAM Chris@101: #include // for std::setw Chris@101: #include // for std::noskipws, streamsize Chris@101: #include // for std::istream Chris@101: #include // for std::ostream Chris@101: #include // for std::ostringstream Chris@101: #endif Chris@101: #include // for NULL Chris@16: #include // for std::domain_error Chris@16: #include // for std::string implicit constructor Chris@16: #include // for boost::addable etc Chris@16: #include // for std::abs Chris@16: #include // for boost::call_traits Chris@16: #include // for BOOST_WORKAROUND Chris@16: #include // for BOOST_ASSERT Chris@101: #include // for boost::integer::gcd, lcm Chris@16: #include // for std::numeric_limits Chris@16: #include // for BOOST_STATIC_ASSERT Chris@16: Chris@16: // Control whether depreciated GCD and LCM functions are included (default: yes) Chris@16: #ifndef BOOST_CONTROL_RATIONAL_HAS_GCD Chris@16: #define BOOST_CONTROL_RATIONAL_HAS_GCD 1 Chris@16: #endif Chris@16: Chris@16: namespace boost { Chris@16: Chris@16: #if BOOST_CONTROL_RATIONAL_HAS_GCD Chris@16: template Chris@16: IntType gcd(IntType n, IntType m) Chris@16: { Chris@16: // Defer to the version in Boost.Math Chris@101: return integer::gcd( n, m ); Chris@16: } Chris@16: Chris@16: template Chris@16: IntType lcm(IntType n, IntType m) Chris@16: { Chris@16: // Defer to the version in Boost.Math Chris@101: return integer::lcm( n, m ); Chris@16: } Chris@16: #endif // BOOST_CONTROL_RATIONAL_HAS_GCD Chris@16: Chris@16: class bad_rational : public std::domain_error Chris@16: { Chris@16: public: Chris@16: explicit bad_rational() : std::domain_error("bad rational: zero denominator") {} Chris@101: explicit bad_rational( char const *what ) : std::domain_error( what ) {} Chris@16: }; Chris@16: Chris@16: template Chris@16: class rational : Chris@16: less_than_comparable < rational, Chris@16: equality_comparable < rational, Chris@16: less_than_comparable2 < rational, IntType, Chris@16: equality_comparable2 < rational, IntType, Chris@16: addable < rational, Chris@16: subtractable < rational, Chris@16: multipliable < rational, Chris@16: dividable < rational, Chris@16: addable2 < rational, IntType, Chris@16: subtractable2 < rational, IntType, Chris@16: subtractable2_left < rational, IntType, Chris@16: multipliable2 < rational, IntType, Chris@16: dividable2 < rational, IntType, Chris@16: dividable2_left < rational, IntType, Chris@16: incrementable < rational, Chris@16: decrementable < rational Chris@16: > > > > > > > > > > > > > > > > Chris@16: { Chris@16: // Class-wide pre-conditions Chris@16: BOOST_STATIC_ASSERT( ::std::numeric_limits::is_specialized ); Chris@16: Chris@16: // Helper types Chris@16: typedef typename boost::call_traits::param_type param_type; Chris@16: Chris@16: struct helper { IntType parts[2]; }; Chris@16: typedef IntType (helper::* bool_type)[2]; Chris@16: Chris@16: public: Chris@101: // Component type Chris@16: typedef IntType int_type; Chris@101: Chris@101: BOOST_CONSTEXPR Chris@16: rational() : num(0), den(1) {} Chris@101: BOOST_CONSTEXPR Chris@16: rational(param_type n) : num(n), den(1) {} Chris@16: rational(param_type n, param_type d) : num(n), den(d) { normalize(); } Chris@16: Chris@101: #ifndef BOOST_NO_MEMBER_TEMPLATES Chris@101: template < typename NewType > Chris@101: BOOST_CONSTEXPR explicit Chris@101: rational( rational const &r ) Chris@101: : num( r.numerator() ), den( is_normalized(int_type( r.numerator() ), Chris@101: int_type( r.denominator() )) ? r.denominator() : Chris@101: throw bad_rational("bad rational: denormalized conversion") ) Chris@101: {} Chris@101: #endif Chris@101: Chris@16: // Default copy constructor and assignment are fine Chris@16: Chris@16: // Add assignment from IntType Chris@101: rational& operator=(param_type i) { num = i; den = 1; return *this; } Chris@16: Chris@16: // Assign in place Chris@16: rational& assign(param_type n, param_type d); Chris@16: Chris@16: // Access to representation Chris@101: BOOST_CONSTEXPR Chris@16: IntType numerator() const { return num; } Chris@101: BOOST_CONSTEXPR Chris@16: IntType denominator() const { return den; } Chris@16: Chris@16: // Arithmetic assignment operators Chris@16: rational& operator+= (const rational& r); Chris@16: rational& operator-= (const rational& r); Chris@16: rational& operator*= (const rational& r); Chris@16: rational& operator/= (const rational& r); Chris@16: Chris@101: rational& operator+= (param_type i) { num += i * den; return *this; } Chris@101: rational& operator-= (param_type i) { num -= i * den; return *this; } Chris@16: rational& operator*= (param_type i); Chris@16: rational& operator/= (param_type i); Chris@16: Chris@16: // Increment and decrement Chris@101: const rational& operator++() { num += den; return *this; } Chris@101: const rational& operator--() { num -= den; return *this; } Chris@16: Chris@16: // Operator not Chris@101: BOOST_CONSTEXPR Chris@16: bool operator!() const { return !num; } Chris@16: Chris@16: // Boolean conversion Chris@16: Chris@16: #if BOOST_WORKAROUND(__MWERKS__,<=0x3003) Chris@16: // The "ISO C++ Template Parser" option in CW 8.3 chokes on the Chris@16: // following, hence we selectively disable that option for the Chris@16: // offending memfun. Chris@16: #pragma parse_mfunc_templ off Chris@16: #endif Chris@16: Chris@101: BOOST_CONSTEXPR Chris@16: operator bool_type() const { return operator !() ? 0 : &helper::parts; } Chris@16: Chris@16: #if BOOST_WORKAROUND(__MWERKS__,<=0x3003) Chris@16: #pragma parse_mfunc_templ reset Chris@16: #endif Chris@16: Chris@16: // Comparison operators Chris@16: bool operator< (const rational& r) const; Chris@101: BOOST_CONSTEXPR Chris@16: bool operator== (const rational& r) const; Chris@16: Chris@16: bool operator< (param_type i) const; Chris@16: bool operator> (param_type i) const; Chris@101: BOOST_CONSTEXPR Chris@16: bool operator== (param_type i) const; Chris@16: Chris@16: private: Chris@16: // Implementation - numerator and denominator (normalized). Chris@16: // Other possibilities - separate whole-part, or sign, fields? Chris@16: IntType num; Chris@16: IntType den; Chris@16: Chris@101: // Helper functions Chris@101: static BOOST_CONSTEXPR Chris@101: int_type inner_gcd( param_type a, param_type b, int_type const &zero = Chris@101: int_type(0) ) Chris@101: { return b == zero ? a : inner_gcd(b, a % b, zero); } Chris@101: Chris@101: static BOOST_CONSTEXPR Chris@101: int_type inner_abs( param_type x, int_type const &zero = int_type(0) ) Chris@101: { return x < zero ? -x : +x; } Chris@101: Chris@16: // Representation note: Fractions are kept in normalized form at all Chris@16: // times. normalized form is defined as gcd(num,den) == 1 and den > 0. Chris@16: // In particular, note that the implementation of abs() below relies Chris@16: // on den always being positive. Chris@16: bool test_invariant() const; Chris@16: void normalize(); Chris@101: Chris@101: static BOOST_CONSTEXPR Chris@101: bool is_normalized( param_type n, param_type d, int_type const &zero = Chris@101: int_type(0), int_type const &one = int_type(1) ) Chris@101: { Chris@101: return d > zero && ( n != zero || d == one ) && inner_abs( inner_gcd(n, Chris@101: d, zero), zero ) == one; Chris@101: } Chris@16: }; Chris@16: Chris@16: // Assign in place Chris@16: template Chris@16: inline rational& rational::assign(param_type n, param_type d) Chris@16: { Chris@101: return *this = rational( n, d ); Chris@16: } Chris@16: Chris@16: // Unary plus and minus Chris@16: template Chris@101: BOOST_CONSTEXPR Chris@16: inline rational operator+ (const rational& r) Chris@16: { Chris@16: return r; Chris@16: } Chris@16: Chris@16: template Chris@16: inline rational operator- (const rational& r) Chris@16: { Chris@16: return rational(-r.numerator(), r.denominator()); Chris@16: } Chris@16: Chris@16: // Arithmetic assignment operators Chris@16: template Chris@16: rational& rational::operator+= (const rational& r) Chris@16: { Chris@16: // This calculation avoids overflow, and minimises the number of expensive Chris@16: // calculations. Thanks to Nickolay Mladenov for this algorithm. Chris@16: // Chris@16: // Proof: Chris@16: // We have to compute a/b + c/d, where gcd(a,b)=1 and gcd(b,c)=1. Chris@16: // Let g = gcd(b,d), and b = b1*g, d=d1*g. Then gcd(b1,d1)=1 Chris@16: // Chris@16: // The result is (a*d1 + c*b1) / (b1*d1*g). Chris@16: // Now we have to normalize this ratio. Chris@16: // Let's assume h | gcd((a*d1 + c*b1), (b1*d1*g)), and h > 1 Chris@16: // If h | b1 then gcd(h,d1)=1 and hence h|(a*d1+c*b1) => h|a. Chris@16: // But since gcd(a,b1)=1 we have h=1. Chris@16: // Similarly h|d1 leads to h=1. Chris@16: // So we have that h | gcd((a*d1 + c*b1) , (b1*d1*g)) => h|g Chris@16: // Finally we have gcd((a*d1 + c*b1), (b1*d1*g)) = gcd((a*d1 + c*b1), g) Chris@16: // Which proves that instead of normalizing the result, it is better to Chris@16: // divide num and den by gcd((a*d1 + c*b1), g) Chris@16: Chris@16: // Protect against self-modification Chris@16: IntType r_num = r.num; Chris@16: IntType r_den = r.den; Chris@16: Chris@101: IntType g = integer::gcd(den, r_den); Chris@16: den /= g; // = b1 from the calculations above Chris@16: num = num * (r_den / g) + r_num * den; Chris@101: g = integer::gcd(num, g); Chris@16: num /= g; Chris@16: den *= r_den/g; Chris@16: Chris@16: return *this; Chris@16: } Chris@16: Chris@16: template Chris@16: rational& rational::operator-= (const rational& r) Chris@16: { Chris@16: // Protect against self-modification Chris@16: IntType r_num = r.num; Chris@16: IntType r_den = r.den; Chris@16: Chris@16: // This calculation avoids overflow, and minimises the number of expensive Chris@16: // calculations. It corresponds exactly to the += case above Chris@101: IntType g = integer::gcd(den, r_den); Chris@16: den /= g; Chris@16: num = num * (r_den / g) - r_num * den; Chris@101: g = integer::gcd(num, g); Chris@16: num /= g; Chris@16: den *= r_den/g; Chris@16: Chris@16: return *this; Chris@16: } Chris@16: Chris@16: template Chris@16: rational& rational::operator*= (const rational& r) Chris@16: { Chris@16: // Protect against self-modification Chris@16: IntType r_num = r.num; Chris@16: IntType r_den = r.den; Chris@16: Chris@16: // Avoid overflow and preserve normalization Chris@101: IntType gcd1 = integer::gcd(num, r_den); Chris@101: IntType gcd2 = integer::gcd(r_num, den); Chris@16: num = (num/gcd1) * (r_num/gcd2); Chris@16: den = (den/gcd2) * (r_den/gcd1); Chris@16: return *this; Chris@16: } Chris@16: Chris@16: template Chris@16: rational& rational::operator/= (const rational& r) Chris@16: { Chris@16: // Protect against self-modification Chris@16: IntType r_num = r.num; Chris@16: IntType r_den = r.den; Chris@16: Chris@16: // Avoid repeated construction Chris@16: IntType zero(0); Chris@16: Chris@16: // Trap division by zero Chris@16: if (r_num == zero) Chris@16: throw bad_rational(); Chris@16: if (num == zero) Chris@16: return *this; Chris@16: Chris@16: // Avoid overflow and preserve normalization Chris@101: IntType gcd1 = integer::gcd(num, r_num); Chris@101: IntType gcd2 = integer::gcd(r_den, den); Chris@16: num = (num/gcd1) * (r_den/gcd2); Chris@16: den = (den/gcd2) * (r_num/gcd1); Chris@16: Chris@16: if (den < zero) { Chris@16: num = -num; Chris@16: den = -den; Chris@16: } Chris@16: return *this; Chris@16: } Chris@16: Chris@16: // Mixed-mode operators Chris@16: template Chris@16: inline rational& Chris@16: rational::operator*= (param_type i) Chris@16: { Chris@101: // Avoid overflow and preserve normalization Chris@101: IntType gcd = integer::gcd(i, den); Chris@101: num *= i / gcd; Chris@101: den /= gcd; Chris@16: Chris@16: return *this; Chris@16: } Chris@16: Chris@16: template Chris@101: rational& Chris@101: rational::operator/= (param_type i) Chris@16: { Chris@101: // Avoid repeated construction Chris@101: IntType const zero(0); Chris@101: Chris@101: if (i == zero) throw bad_rational(); Chris@101: if (num == zero) return *this; Chris@101: Chris@101: // Avoid overflow and preserve normalization Chris@101: IntType const gcd = integer::gcd(num, i); Chris@101: num /= gcd; Chris@101: den *= i / gcd; Chris@101: Chris@101: if (den < zero) { Chris@101: num = -num; Chris@101: den = -den; Chris@101: } Chris@101: Chris@16: return *this; Chris@16: } Chris@16: Chris@16: // Comparison operators Chris@16: template Chris@16: bool rational::operator< (const rational& r) const Chris@16: { Chris@16: // Avoid repeated construction Chris@16: int_type const zero( 0 ); Chris@16: Chris@16: // This should really be a class-wide invariant. The reason for these Chris@16: // checks is that for 2's complement systems, INT_MIN has no corresponding Chris@16: // positive, so negating it during normalization keeps it INT_MIN, which Chris@16: // is bad for later calculations that assume a positive denominator. Chris@16: BOOST_ASSERT( this->den > zero ); Chris@16: BOOST_ASSERT( r.den > zero ); Chris@16: Chris@16: // Determine relative order by expanding each value to its simple continued Chris@16: // fraction representation using the Euclidian GCD algorithm. Chris@16: struct { int_type n, d, q, r; } Chris@16: ts = { this->num, this->den, static_cast(this->num / this->den), Chris@16: static_cast(this->num % this->den) }, Chris@16: rs = { r.num, r.den, static_cast(r.num / r.den), Chris@16: static_cast(r.num % r.den) }; Chris@16: unsigned reverse = 0u; Chris@16: Chris@16: // Normalize negative moduli by repeatedly adding the (positive) denominator Chris@16: // and decrementing the quotient. Later cycles should have all positive Chris@16: // values, so this only has to be done for the first cycle. (The rules of Chris@16: // C++ require a nonnegative quotient & remainder for a nonnegative dividend Chris@16: // & positive divisor.) Chris@16: while ( ts.r < zero ) { ts.r += ts.d; --ts.q; } Chris@16: while ( rs.r < zero ) { rs.r += rs.d; --rs.q; } Chris@16: Chris@16: // Loop through and compare each variable's continued-fraction components Chris@101: for ( ;; ) Chris@16: { Chris@16: // The quotients of the current cycle are the continued-fraction Chris@16: // components. Comparing two c.f. is comparing their sequences, Chris@16: // stopping at the first difference. Chris@16: if ( ts.q != rs.q ) Chris@16: { Chris@16: // Since reciprocation changes the relative order of two variables, Chris@16: // and c.f. use reciprocals, the less/greater-than test reverses Chris@16: // after each index. (Start w/ non-reversed @ whole-number place.) Chris@16: return reverse ? ts.q > rs.q : ts.q < rs.q; Chris@16: } Chris@16: Chris@16: // Prepare the next cycle Chris@16: reverse ^= 1u; Chris@16: Chris@16: if ( (ts.r == zero) || (rs.r == zero) ) Chris@16: { Chris@16: // At least one variable's c.f. expansion has ended Chris@16: break; Chris@16: } Chris@16: Chris@16: ts.n = ts.d; ts.d = ts.r; Chris@16: ts.q = ts.n / ts.d; ts.r = ts.n % ts.d; Chris@16: rs.n = rs.d; rs.d = rs.r; Chris@16: rs.q = rs.n / rs.d; rs.r = rs.n % rs.d; Chris@16: } Chris@16: Chris@16: // Compare infinity-valued components for otherwise equal sequences Chris@16: if ( ts.r == rs.r ) Chris@16: { Chris@16: // Both remainders are zero, so the next (and subsequent) c.f. Chris@16: // components for both sequences are infinity. Therefore, the sequences Chris@16: // and their corresponding values are equal. Chris@16: return false; Chris@16: } Chris@16: else Chris@16: { Chris@16: #ifdef BOOST_MSVC Chris@16: #pragma warning(push) Chris@16: #pragma warning(disable:4800) Chris@16: #endif Chris@16: // Exactly one of the remainders is zero, so all following c.f. Chris@16: // components of that variable are infinity, while the other variable Chris@16: // has a finite next c.f. component. So that other variable has the Chris@16: // lesser value (modulo the reversal flag!). Chris@16: return ( ts.r != zero ) != static_cast( reverse ); Chris@16: #ifdef BOOST_MSVC Chris@16: #pragma warning(pop) Chris@16: #endif Chris@16: } Chris@16: } Chris@16: Chris@16: template Chris@16: bool rational::operator< (param_type i) const Chris@16: { Chris@16: // Avoid repeated construction Chris@16: int_type const zero( 0 ); Chris@16: Chris@16: // Break value into mixed-fraction form, w/ always-nonnegative remainder Chris@16: BOOST_ASSERT( this->den > zero ); Chris@16: int_type q = this->num / this->den, r = this->num % this->den; Chris@16: while ( r < zero ) { r += this->den; --q; } Chris@16: Chris@16: // Compare with just the quotient, since the remainder always bumps the Chris@16: // value up. [Since q = floor(n/d), and if n/d < i then q < i, if n/d == i Chris@16: // then q == i, if n/d == i + r/d then q == i, and if n/d >= i + 1 then Chris@16: // q >= i + 1 > i; therefore n/d < i iff q < i.] Chris@16: return q < i; Chris@16: } Chris@16: Chris@16: template Chris@16: bool rational::operator> (param_type i) const Chris@16: { Chris@101: return operator==(i)? false: !operator<(i); Chris@16: } Chris@16: Chris@16: template Chris@101: BOOST_CONSTEXPR Chris@16: inline bool rational::operator== (const rational& r) const Chris@16: { Chris@16: return ((num == r.num) && (den == r.den)); Chris@16: } Chris@16: Chris@16: template Chris@101: BOOST_CONSTEXPR Chris@16: inline bool rational::operator== (param_type i) const Chris@16: { Chris@16: return ((den == IntType(1)) && (num == i)); Chris@16: } Chris@16: Chris@16: // Invariant check Chris@16: template Chris@16: inline bool rational::test_invariant() const Chris@16: { Chris@101: return ( this->den > int_type(0) ) && ( integer::gcd(this->num, this->den) == Chris@16: int_type(1) ); Chris@16: } Chris@16: Chris@16: // Normalisation Chris@16: template Chris@16: void rational::normalize() Chris@16: { Chris@16: // Avoid repeated construction Chris@16: IntType zero(0); Chris@16: Chris@16: if (den == zero) Chris@16: throw bad_rational(); Chris@16: Chris@16: // Handle the case of zero separately, to avoid division by zero Chris@16: if (num == zero) { Chris@16: den = IntType(1); Chris@16: return; Chris@16: } Chris@16: Chris@101: IntType g = integer::gcd(num, den); Chris@16: Chris@16: num /= g; Chris@16: den /= g; Chris@16: Chris@16: // Ensure that the denominator is positive Chris@16: if (den < zero) { Chris@16: num = -num; Chris@16: den = -den; Chris@16: } Chris@16: Chris@101: // ...But acknowledge that the previous step doesn't always work. Chris@101: // (Nominally, this should be done before the mutating steps, but this Chris@101: // member function is only called during the constructor, so we never have Chris@101: // to worry about zombie objects.) Chris@101: if (den < zero) Chris@101: throw bad_rational( "bad rational: non-zero singular denominator" ); Chris@101: Chris@16: BOOST_ASSERT( this->test_invariant() ); Chris@16: } Chris@16: Chris@101: #ifndef BOOST_NO_IOSTREAM Chris@16: namespace detail { Chris@16: Chris@16: // A utility class to reset the format flags for an istream at end Chris@16: // of scope, even in case of exceptions Chris@16: struct resetter { Chris@16: resetter(std::istream& is) : is_(is), f_(is.flags()) {} Chris@16: ~resetter() { is_.flags(f_); } Chris@16: std::istream& is_; Chris@16: std::istream::fmtflags f_; // old GNU c++ lib has no ios_base Chris@16: }; Chris@16: Chris@16: } Chris@16: Chris@16: // Input and output Chris@16: template Chris@16: std::istream& operator>> (std::istream& is, rational& r) Chris@16: { Chris@101: using std::ios; Chris@101: Chris@16: IntType n = IntType(0), d = IntType(1); Chris@16: char c = 0; Chris@16: detail::resetter sentry(is); Chris@16: Chris@101: if ( is >> n ) Chris@101: { Chris@101: if ( is.get(c) ) Chris@101: { Chris@101: if ( c == '/' ) Chris@101: { Chris@101: if ( is >> std::noskipws >> d ) Chris@101: try { Chris@101: r.assign( n, d ); Chris@101: } catch ( bad_rational & ) { // normalization fail Chris@101: try { is.setstate(ios::failbit); } Chris@101: catch ( ... ) {} // don't throw ios_base::failure... Chris@101: if ( is.exceptions() & ios::failbit ) Chris@101: throw; // ...but the original exception instead Chris@101: // ELSE: suppress the exception, use just error flags Chris@101: } Chris@101: } Chris@101: else Chris@101: is.setstate( ios::failbit ); Chris@101: } Chris@101: } Chris@16: Chris@16: return is; Chris@16: } Chris@16: Chris@16: // Add manipulators for output format? Chris@16: template Chris@16: std::ostream& operator<< (std::ostream& os, const rational& r) Chris@16: { Chris@101: using namespace std; Chris@101: Chris@101: // The slash directly precedes the denominator, which has no prefixes. Chris@101: ostringstream ss; Chris@101: Chris@101: ss.copyfmt( os ); Chris@101: ss.tie( NULL ); Chris@101: ss.exceptions( ios::goodbit ); Chris@101: ss.width( 0 ); Chris@101: ss << noshowpos << noshowbase << '/' << r.denominator(); Chris@101: Chris@101: // The numerator holds the showpos, internal, and showbase flags. Chris@101: string const tail = ss.str(); Chris@101: streamsize const w = os.width() - static_cast( tail.size() ); Chris@101: Chris@101: ss.clear(); Chris@101: ss.str( "" ); Chris@101: ss.flags( os.flags() ); Chris@101: ss << setw( w < 0 || (os.flags() & ios::adjustfield) != ios::internal ? 0 : Chris@101: w ) << r.numerator(); Chris@101: return os << ss.str() + tail; Chris@16: } Chris@101: #endif // BOOST_NO_IOSTREAM Chris@16: Chris@16: // Type conversion Chris@16: template Chris@101: BOOST_CONSTEXPR Chris@101: inline T rational_cast(const rational& src) Chris@16: { Chris@16: return static_cast(src.numerator())/static_cast(src.denominator()); Chris@16: } Chris@16: Chris@16: // Do not use any abs() defined on IntType - it isn't worth it, given the Chris@16: // difficulties involved (Koenig lookup required, there may not *be* an abs() Chris@16: // defined, etc etc). Chris@16: template Chris@16: inline rational abs(const rational& r) Chris@16: { Chris@101: return r.numerator() >= IntType(0)? r: -r; Chris@16: } Chris@16: Chris@16: } // namespace boost Chris@16: Chris@16: #endif // BOOST_RATIONAL_HPP Chris@16: