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 // See http://www.boost.org/libs/rational for documentation.
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
17 // Nickolay Mladenov, for the implementation of operator+=
20 // 05 Nov 06 Change rational_cast to not depend on division between different
21 // types (Daryle Walker)
22 // 04 Nov 06 Off-load GCD and LCM to Boost.Math; add some invariant checks;
23 // add std::numeric_limits<> requirement to help GCD (Daryle Walker)
24 // 31 Oct 06 Recoded both operator< to use round-to-negative-infinity
25 // divisions; the rational-value version now uses continued fraction
26 // expansion to avoid overflows, for bug #798357 (Daryle Walker)
27 // 20 Oct 06 Fix operator bool_type for CW 8.3 (Joaquín M López Muñoz)
28 // 18 Oct 06 Use EXPLICIT_TEMPLATE_TYPE helper macros from Boost.Config
29 // (Joaquín M López Muñoz)
30 // 27 Dec 05 Add Boolean conversion operator (Daryle Walker)
31 // 28 Sep 02 Use _left versions of operators from operators.hpp
32 // 05 Jul 01 Recode gcd(), avoiding std::swap (Helmut Zeisel)
33 // 03 Mar 01 Workarounds for Intel C++ 5.0 (David Abrahams)
34 // 05 Feb 01 Update operator>> to tighten up input syntax
35 // 05 Feb 01 Final tidy up of gcd code prior to the new release
36 // 27 Jan 01 Recode abs() without relying on abs(IntType)
37 // 21 Jan 01 Include Nickolay Mladenov's operator+= algorithm,
38 // tidy up a number of areas, use newer features of operators.hpp
39 // (reduces space overhead to zero), add operator!,
40 // introduce explicit mixed-mode arithmetic operations
41 // 12 Jan 01 Include fixes to handle a user-defined IntType better
42 // 19 Nov 00 Throw on divide by zero in operator /= (John (EBo) David)
43 // 23 Jun 00 Incorporate changes from Mark Rodgers for Borland C++
44 // 22 Jun 00 Change _MSC_VER to BOOST_MSVC so other compilers are not
45 // affected (Beman Dawes)
46 // 6 Mar 00 Fix operator-= normalization, #include <string> (Jens Maurer)
47 // 14 Dec 99 Modifications based on comments from the boost list
48 // 09 Dec 99 Initial Version (Paul Moore)
50 #ifndef BOOST_RATIONAL_HPP
51 #define BOOST_RATIONAL_HPP
53 #include <iostream> // for std::istream and std::ostream
54 #include <iomanip> // for std::noskipws
55 #include <stdexcept> // for std::domain_error
56 #include <string> // for std::string implicit constructor
57 #include <boost/operators.hpp> // for boost::addable etc
58 #include <cstdlib> // for std::abs
59 #include <boost/call_traits.hpp> // for boost::call_traits
60 #include <boost/config.hpp> // for BOOST_NO_STDC_NAMESPACE, BOOST_MSVC
61 #include <boost/detail/workaround.hpp> // for BOOST_WORKAROUND
62 #include <boost/assert.hpp> // for BOOST_ASSERT
63 #include <boost/math/common_factor_rt.hpp> // for boost::math::gcd, lcm
64 #include <limits> // for std::numeric_limits
65 #include <boost/static_assert.hpp> // for BOOST_STATIC_ASSERT
67 // Control whether depreciated GCD and LCM functions are included (default: yes)
68 #ifndef BOOST_CONTROL_RATIONAL_HAS_GCD
69 #define BOOST_CONTROL_RATIONAL_HAS_GCD 1
74 #if BOOST_CONTROL_RATIONAL_HAS_GCD
75 template <typename IntType>
76 IntType gcd(IntType n, IntType m)
78 // Defer to the version in Boost.Math
79 return math::gcd( n, m );
82 template <typename IntType>
83 IntType lcm(IntType n, IntType m)
85 // Defer to the version in Boost.Math
86 return math::lcm( n, m );
88 #endif // BOOST_CONTROL_RATIONAL_HAS_GCD
90 class bad_rational : public std::domain_error
93 explicit bad_rational() : std::domain_error("bad rational: zero denominator") {}
96 template <typename IntType>
99 template <typename IntType>
100 rational<IntType> abs(const rational<IntType>& r);
102 template <typename IntType>
104 less_than_comparable < rational<IntType>,
105 equality_comparable < rational<IntType>,
106 less_than_comparable2 < rational<IntType>, IntType,
107 equality_comparable2 < rational<IntType>, IntType,
108 addable < rational<IntType>,
109 subtractable < rational<IntType>,
110 multipliable < rational<IntType>,
111 dividable < rational<IntType>,
112 addable2 < rational<IntType>, IntType,
113 subtractable2 < rational<IntType>, IntType,
114 subtractable2_left < rational<IntType>, IntType,
115 multipliable2 < rational<IntType>, IntType,
116 dividable2 < rational<IntType>, IntType,
117 dividable2_left < rational<IntType>, IntType,
118 incrementable < rational<IntType>,
119 decrementable < rational<IntType>
120 > > > > > > > > > > > > > > > >
122 // Class-wide pre-conditions
123 BOOST_STATIC_ASSERT( ::std::numeric_limits<IntType>::is_specialized );
126 typedef typename boost::call_traits<IntType>::param_type param_type;
128 struct helper { IntType parts[2]; };
129 typedef IntType (helper::* bool_type)[2];
132 typedef IntType int_type;
133 rational() : num(0), den(1) {}
134 rational(param_type n) : num(n), den(1) {}
135 rational(param_type n, param_type d) : num(n), den(d) { normalize(); }
137 // Default copy constructor and assignment are fine
139 // Add assignment from IntType
140 rational& operator=(param_type n) { return assign(n, 1); }
143 rational& assign(param_type n, param_type d);
145 // Access to representation
146 IntType numerator() const { return num; }
147 IntType denominator() const { return den; }
149 // Arithmetic assignment operators
150 rational& operator+= (const rational& r);
151 rational& operator-= (const rational& r);
152 rational& operator*= (const rational& r);
153 rational& operator/= (const rational& r);
155 rational& operator+= (param_type i);
156 rational& operator-= (param_type i);
157 rational& operator*= (param_type i);
158 rational& operator/= (param_type i);
160 // Increment and decrement
161 const rational& operator++();
162 const rational& operator--();
165 bool operator!() const { return !num; }
167 // Boolean conversion
169 #if BOOST_WORKAROUND(__MWERKS__,<=0x3003)
170 // The "ISO C++ Template Parser" option in CW 8.3 chokes on the
171 // following, hence we selectively disable that option for the
173 #pragma parse_mfunc_templ off
176 operator bool_type() const { return operator !() ? 0 : &helper::parts; }
178 #if BOOST_WORKAROUND(__MWERKS__,<=0x3003)
179 #pragma parse_mfunc_templ reset
182 // Comparison operators
183 bool operator< (const rational& r) const;
184 bool operator== (const rational& r) const;
186 bool operator< (param_type i) const;
187 bool operator> (param_type i) const;
188 bool operator== (param_type i) const;
191 // Implementation - numerator and denominator (normalized).
192 // Other possibilities - separate whole-part, or sign, fields?
196 // Representation note: Fractions are kept in normalized form at all
197 // times. normalized form is defined as gcd(num,den) == 1 and den > 0.
198 // In particular, note that the implementation of abs() below relies
199 // on den always being positive.
200 bool test_invariant() const;
205 template <typename IntType>
206 inline rational<IntType>& rational<IntType>::assign(param_type n, param_type d)
214 // Unary plus and minus
215 template <typename IntType>
216 inline rational<IntType> operator+ (const rational<IntType>& r)
221 template <typename IntType>
222 inline rational<IntType> operator- (const rational<IntType>& r)
224 return rational<IntType>(-r.numerator(), r.denominator());
227 // Arithmetic assignment operators
228 template <typename IntType>
229 rational<IntType>& rational<IntType>::operator+= (const rational<IntType>& r)
231 // This calculation avoids overflow, and minimises the number of expensive
232 // calculations. Thanks to Nickolay Mladenov for this algorithm.
235 // We have to compute a/b + c/d, where gcd(a,b)=1 and gcd(b,c)=1.
236 // Let g = gcd(b,d), and b = b1*g, d=d1*g. Then gcd(b1,d1)=1
238 // The result is (a*d1 + c*b1) / (b1*d1*g).
239 // Now we have to normalize this ratio.
240 // Let's assume h | gcd((a*d1 + c*b1), (b1*d1*g)), and h > 1
241 // If h | b1 then gcd(h,d1)=1 and hence h|(a*d1+c*b1) => h|a.
242 // But since gcd(a,b1)=1 we have h=1.
243 // Similarly h|d1 leads to h=1.
244 // So we have that h | gcd((a*d1 + c*b1) , (b1*d1*g)) => h|g
245 // Finally we have gcd((a*d1 + c*b1), (b1*d1*g)) = gcd((a*d1 + c*b1), g)
246 // Which proves that instead of normalizing the result, it is better to
247 // divide num and den by gcd((a*d1 + c*b1), g)
249 // Protect against self-modification
250 IntType r_num = r.num;
251 IntType r_den = r.den;
253 IntType g = math::gcd(den, r_den);
254 den /= g; // = b1 from the calculations above
255 num = num * (r_den / g) + r_num * den;
256 g = math::gcd(num, g);
263 template <typename IntType>
264 rational<IntType>& rational<IntType>::operator-= (const rational<IntType>& r)
266 // Protect against self-modification
267 IntType r_num = r.num;
268 IntType r_den = r.den;
270 // This calculation avoids overflow, and minimises the number of expensive
271 // calculations. It corresponds exactly to the += case above
272 IntType g = math::gcd(den, r_den);
274 num = num * (r_den / g) - r_num * den;
275 g = math::gcd(num, g);
282 template <typename IntType>
283 rational<IntType>& rational<IntType>::operator*= (const rational<IntType>& r)
285 // Protect against self-modification
286 IntType r_num = r.num;
287 IntType r_den = r.den;
289 // Avoid overflow and preserve normalization
290 IntType gcd1 = math::gcd(num, r_den);
291 IntType gcd2 = math::gcd(r_num, den);
292 num = (num/gcd1) * (r_num/gcd2);
293 den = (den/gcd2) * (r_den/gcd1);
297 template <typename IntType>
298 rational<IntType>& rational<IntType>::operator/= (const rational<IntType>& r)
300 // Protect against self-modification
301 IntType r_num = r.num;
302 IntType r_den = r.den;
304 // Avoid repeated construction
307 // Trap division by zero
309 throw bad_rational();
313 // Avoid overflow and preserve normalization
314 IntType gcd1 = math::gcd(num, r_num);
315 IntType gcd2 = math::gcd(r_den, den);
316 num = (num/gcd1) * (r_den/gcd2);
317 den = (den/gcd2) * (r_num/gcd1);
326 // Mixed-mode operators
327 template <typename IntType>
328 inline rational<IntType>&
329 rational<IntType>::operator+= (param_type i)
331 return operator+= (rational<IntType>(i));
334 template <typename IntType>
335 inline rational<IntType>&
336 rational<IntType>::operator-= (param_type i)
338 return operator-= (rational<IntType>(i));
341 template <typename IntType>
342 inline rational<IntType>&
343 rational<IntType>::operator*= (param_type i)
345 return operator*= (rational<IntType>(i));
348 template <typename IntType>
349 inline rational<IntType>&
350 rational<IntType>::operator/= (param_type i)
352 return operator/= (rational<IntType>(i));
355 // Increment and decrement
356 template <typename IntType>
357 inline const rational<IntType>& rational<IntType>::operator++()
359 // This can never denormalise the fraction
364 template <typename IntType>
365 inline const rational<IntType>& rational<IntType>::operator--()
367 // This can never denormalise the fraction
372 // Comparison operators
373 template <typename IntType>
374 bool rational<IntType>::operator< (const rational<IntType>& r) const
376 // Avoid repeated construction
377 int_type const zero( 0 );
379 // This should really be a class-wide invariant. The reason for these
380 // checks is that for 2's complement systems, INT_MIN has no corresponding
381 // positive, so negating it during normalization keeps it INT_MIN, which
382 // is bad for later calculations that assume a positive denominator.
383 BOOST_ASSERT( this->den > zero );
384 BOOST_ASSERT( r.den > zero );
386 // Determine relative order by expanding each value to its simple continued
387 // fraction representation using the Euclidian GCD algorithm.
388 struct { int_type n, d, q, r; } ts = { this->num, this->den, this->num /
389 this->den, this->num % this->den }, rs = { r.num, r.den, r.num / r.den,
391 unsigned reverse = 0u;
393 // Normalize negative moduli by repeatedly adding the (positive) denominator
394 // and decrementing the quotient. Later cycles should have all positive
395 // values, so this only has to be done for the first cycle. (The rules of
396 // C++ require a nonnegative quotient & remainder for a nonnegative dividend
397 // & positive divisor.)
398 while ( ts.r < zero ) { ts.r += ts.d; --ts.q; }
399 while ( rs.r < zero ) { rs.r += rs.d; --rs.q; }
401 // Loop through and compare each variable's continued-fraction components
404 // The quotients of the current cycle are the continued-fraction
405 // components. Comparing two c.f. is comparing their sequences,
406 // stopping at the first difference.
409 // Since reciprocation changes the relative order of two variables,
410 // and c.f. use reciprocals, the less/greater-than test reverses
411 // after each index. (Start w/ non-reversed @ whole-number place.)
412 return reverse ? ts.q > rs.q : ts.q < rs.q;
415 // Prepare the next cycle
418 if ( (ts.r == zero) || (rs.r == zero) )
420 // At least one variable's c.f. expansion has ended
424 ts.n = ts.d; ts.d = ts.r;
425 ts.q = ts.n / ts.d; ts.r = ts.n % ts.d;
426 rs.n = rs.d; rs.d = rs.r;
427 rs.q = rs.n / rs.d; rs.r = rs.n % rs.d;
430 // Compare infinity-valued components for otherwise equal sequences
433 // Both remainders are zero, so the next (and subsequent) c.f.
434 // components for both sequences are infinity. Therefore, the sequences
435 // and their corresponding values are equal.
440 // Exactly one of the remainders is zero, so all following c.f.
441 // components of that variable are infinity, while the other variable
442 // has a finite next c.f. component. So that other variable has the
443 // lesser value (modulo the reversal flag!).
444 return ( ts.r != zero ) != static_cast<bool>( reverse );
448 template <typename IntType>
449 bool rational<IntType>::operator< (param_type i) const
451 // Avoid repeated construction
452 int_type const zero( 0 );
454 // Break value into mixed-fraction form, w/ always-nonnegative remainder
455 BOOST_ASSERT( this->den > zero );
456 int_type q = this->num / this->den, r = this->num % this->den;
457 while ( r < zero ) { r += this->den; --q; }
459 // Compare with just the quotient, since the remainder always bumps the
460 // value up. [Since q = floor(n/d), and if n/d < i then q < i, if n/d == i
461 // then q == i, if n/d == i + r/d then q == i, and if n/d >= i + 1 then
462 // q >= i + 1 > i; therefore n/d < i iff q < i.]
466 template <typename IntType>
467 bool rational<IntType>::operator> (param_type i) const
469 // Trap equality first
470 if (num == i && den == IntType(1))
473 // Otherwise, we can use operator<
474 return !operator<(i);
477 template <typename IntType>
478 inline bool rational<IntType>::operator== (const rational<IntType>& r) const
480 return ((num == r.num) && (den == r.den));
483 template <typename IntType>
484 inline bool rational<IntType>::operator== (param_type i) const
486 return ((den == IntType(1)) && (num == i));
490 template <typename IntType>
491 inline bool rational<IntType>::test_invariant() const
493 return ( this->den > int_type(0) ) && ( math::gcd(this->num, this->den) ==
498 template <typename IntType>
499 void rational<IntType>::normalize()
501 // Avoid repeated construction
505 throw bad_rational();
507 // Handle the case of zero separately, to avoid division by zero
513 IntType g = math::gcd(num, den);
518 // Ensure that the denominator is positive
524 BOOST_ASSERT( this->test_invariant() );
529 // A utility class to reset the format flags for an istream at end
530 // of scope, even in case of exceptions
532 resetter(std::istream& is) : is_(is), f_(is.flags()) {}
533 ~resetter() { is_.flags(f_); }
535 std::istream::fmtflags f_; // old GNU c++ lib has no ios_base
541 template <typename IntType>
542 std::istream& operator>> (std::istream& is, rational<IntType>& r)
544 IntType n = IntType(0), d = IntType(1);
546 detail::resetter sentry(is);
552 is.clear(std::istream::badbit); // old GNU c++ lib has no ios_base
554 #if !defined(__GNUC__) || (defined(__GNUC__) && (__GNUC__ >= 3)) || defined __SGI_STL_PORT
557 is.unsetf(ios::skipws); // compiles, but seems to have no effect.
567 // Add manipulators for output format?
568 template <typename IntType>
569 std::ostream& operator<< (std::ostream& os, const rational<IntType>& r)
571 os << r.numerator() << '/' << r.denominator();
576 template <typename T, typename IntType>
577 inline T rational_cast(
578 const rational<IntType>& src BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE(T))
580 return static_cast<T>(src.numerator())/static_cast<T>(src.denominator());
583 // Do not use any abs() defined on IntType - it isn't worth it, given the
584 // difficulties involved (Koenig lookup required, there may not *be* an abs()
585 // defined, etc etc).
586 template <typename IntType>
587 inline rational<IntType> abs(const rational<IntType>& r)
589 if (r.numerator() >= IntType(0))
592 return rational<IntType>(-r.numerator(), r.denominator());
597 #endif // BOOST_RATIONAL_HPP