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 // 28 Sep 02 Use _left versions of operators from operators.hpp
21 // 05 Jul 01 Recode gcd(), avoiding std::swap (Helmut Zeisel)
22 // 03 Mar 01 Workarounds for Intel C++ 5.0 (David Abrahams)
23 // 05 Feb 01 Update operator>> to tighten up input syntax
24 // 05 Feb 01 Final tidy up of gcd code prior to the new release
25 // 27 Jan 01 Recode abs() without relying on abs(IntType)
26 // 21 Jan 01 Include Nickolay Mladenov's operator+= algorithm,
27 // tidy up a number of areas, use newer features of operators.hpp
28 // (reduces space overhead to zero), add operator!,
29 // introduce explicit mixed-mode arithmetic operations
30 // 12 Jan 01 Include fixes to handle a user-defined IntType better
31 // 19 Nov 00 Throw on divide by zero in operator /= (John (EBo) David)
32 // 23 Jun 00 Incorporate changes from Mark Rodgers for Borland C++
33 // 22 Jun 00 Change _MSC_VER to BOOST_MSVC so other compilers are not
34 // affected (Beman Dawes)
35 // 6 Mar 00 Fix operator-= normalization, #include <string> (Jens Maurer)
36 // 14 Dec 99 Modifications based on comments from the boost list
37 // 09 Dec 99 Initial Version (Paul Moore)
39 #ifndef BOOST_RATIONAL_HPP
40 #define BOOST_RATIONAL_HPP
42 #include <iostream> // for std::istream and std::ostream
43 #include <iomanip> // for std::noskipws
44 #include <stdexcept> // for std::domain_error
45 #include <string> // for std::string implicit constructor
46 #include <boost/operators.hpp> // for boost::addable etc
47 #include <cstdlib> // for std::abs
48 #include <boost/call_traits.hpp> // for boost::call_traits
49 #include <boost/config.hpp> // for BOOST_NO_STDC_NAMESPACE, BOOST_MSVC
53 // Note: We use n and m as temporaries in this function, so there is no value
54 // in using const IntType& as we would only need to make a copy anyway...
55 template <typename IntType>
56 IntType gcd(IntType n, IntType m)
58 // Avoid repeated construction
61 // This is abs() - given the existence of broken compilers with Koenig
62 // lookup issues and other problems, I code this explicitly. (Remember,
63 // IntType may be a user-defined type).
69 // As n and m are now positive, we can be sure that %= returns a
70 // positive value (the standard guarantees this for built-in types,
71 // and we require it of user-defined types).
82 template <typename IntType>
83 IntType lcm(IntType n, IntType m)
85 // Avoid repeated construction
88 if (n == zero || m == zero)
99 class bad_rational : public std::domain_error
102 explicit bad_rational() : std::domain_error("bad rational: zero denominator") {}
105 template <typename IntType>
108 template <typename IntType>
109 rational<IntType> abs(const rational<IntType>& r);
111 template <typename IntType>
113 less_than_comparable < rational<IntType>,
114 equality_comparable < rational<IntType>,
115 less_than_comparable2 < rational<IntType>, IntType,
116 equality_comparable2 < rational<IntType>, IntType,
117 addable < rational<IntType>,
118 subtractable < rational<IntType>,
119 multipliable < rational<IntType>,
120 dividable < rational<IntType>,
121 addable2 < rational<IntType>, IntType,
122 subtractable2 < rational<IntType>, IntType,
123 subtractable2_left < rational<IntType>, IntType,
124 multipliable2 < rational<IntType>, IntType,
125 dividable2 < rational<IntType>, IntType,
126 dividable2_left < rational<IntType>, IntType,
127 incrementable < rational<IntType>,
128 decrementable < rational<IntType>
129 > > > > > > > > > > > > > > > >
131 typedef typename boost::call_traits<IntType>::param_type param_type;
133 typedef IntType int_type;
134 rational() : num(0), den(1) {}
135 rational(param_type n) : num(n), den(1) {}
136 rational(param_type n, param_type d) : num(n), den(d) { normalize(); }
138 // Default copy constructor and assignment are fine
140 // Add assignment from IntType
141 rational& operator=(param_type n) { return assign(n, 1); }
144 rational& assign(param_type n, param_type d);
146 // Access to representation
147 IntType numerator() const { return num; }
148 IntType denominator() const { return den; }
150 // Arithmetic assignment operators
151 rational& operator+= (const rational& r);
152 rational& operator-= (const rational& r);
153 rational& operator*= (const rational& r);
154 rational& operator/= (const rational& r);
156 rational& operator+= (param_type i);
157 rational& operator-= (param_type i);
158 rational& operator*= (param_type i);
159 rational& operator/= (param_type i);
161 // Increment and decrement
162 const rational& operator++();
163 const rational& operator--();
166 bool operator!() const { return !num; }
168 // Comparison operators
169 bool operator< (const rational& r) const;
170 bool operator== (const rational& r) const;
172 bool operator< (param_type i) const;
173 bool operator> (param_type i) const;
174 bool operator== (param_type i) const;
177 // Implementation - numerator and denominator (normalized).
178 // Other possibilities - separate whole-part, or sign, fields?
182 // Representation note: Fractions are kept in normalized form at all
183 // times. normalized form is defined as gcd(num,den) == 1 and den > 0.
184 // In particular, note that the implementation of abs() below relies
185 // on den always being positive.
190 template <typename IntType>
191 inline rational<IntType>& rational<IntType>::assign(param_type n, param_type d)
199 // Unary plus and minus
200 template <typename IntType>
201 inline rational<IntType> operator+ (const rational<IntType>& r)
206 template <typename IntType>
207 inline rational<IntType> operator- (const rational<IntType>& r)
209 return rational<IntType>(-r.numerator(), r.denominator());
212 // Arithmetic assignment operators
213 template <typename IntType>
214 rational<IntType>& rational<IntType>::operator+= (const rational<IntType>& r)
216 // This calculation avoids overflow, and minimises the number of expensive
217 // calculations. Thanks to Nickolay Mladenov for this algorithm.
220 // We have to compute a/b + c/d, where gcd(a,b)=1 and gcd(b,c)=1.
221 // Let g = gcd(b,d), and b = b1*g, d=d1*g. Then gcd(b1,d1)=1
223 // The result is (a*d1 + c*b1) / (b1*d1*g).
224 // Now we have to normalize this ratio.
225 // Let's assume h | gcd((a*d1 + c*b1), (b1*d1*g)), and h > 1
226 // If h | b1 then gcd(h,d1)=1 and hence h|(a*d1+c*b1) => h|a.
227 // But since gcd(a,b1)=1 we have h=1.
228 // Similarly h|d1 leads to h=1.
229 // So we have that h | gcd((a*d1 + c*b1) , (b1*d1*g)) => h|g
230 // Finally we have gcd((a*d1 + c*b1), (b1*d1*g)) = gcd((a*d1 + c*b1), g)
231 // Which proves that instead of normalizing the result, it is better to
232 // divide num and den by gcd((a*d1 + c*b1), g)
234 // Protect against self-modification
235 IntType r_num = r.num;
236 IntType r_den = r.den;
238 IntType g = gcd(den, r_den);
239 den /= g; // = b1 from the calculations above
240 num = num * (r_den / g) + r_num * den;
248 template <typename IntType>
249 rational<IntType>& rational<IntType>::operator-= (const rational<IntType>& r)
251 // Protect against self-modification
252 IntType r_num = r.num;
253 IntType r_den = r.den;
255 // This calculation avoids overflow, and minimises the number of expensive
256 // calculations. It corresponds exactly to the += case above
257 IntType g = gcd(den, r_den);
259 num = num * (r_den / g) - r_num * den;
267 template <typename IntType>
268 rational<IntType>& rational<IntType>::operator*= (const rational<IntType>& r)
270 // Protect against self-modification
271 IntType r_num = r.num;
272 IntType r_den = r.den;
274 // Avoid overflow and preserve normalization
275 IntType gcd1 = gcd<IntType>(num, r_den);
276 IntType gcd2 = gcd<IntType>(r_num, den);
277 num = (num/gcd1) * (r_num/gcd2);
278 den = (den/gcd2) * (r_den/gcd1);
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 repeated construction
292 // Trap division by zero
294 throw bad_rational();
298 // Avoid overflow and preserve normalization
299 IntType gcd1 = gcd<IntType>(num, r_num);
300 IntType gcd2 = gcd<IntType>(r_den, den);
301 num = (num/gcd1) * (r_den/gcd2);
302 den = (den/gcd2) * (r_num/gcd1);
311 // Mixed-mode operators
312 template <typename IntType>
313 inline rational<IntType>&
314 rational<IntType>::operator+= (param_type i)
316 return operator+= (rational<IntType>(i));
319 template <typename IntType>
320 inline rational<IntType>&
321 rational<IntType>::operator-= (param_type i)
323 return operator-= (rational<IntType>(i));
326 template <typename IntType>
327 inline rational<IntType>&
328 rational<IntType>::operator*= (param_type i)
330 return operator*= (rational<IntType>(i));
333 template <typename IntType>
334 inline rational<IntType>&
335 rational<IntType>::operator/= (param_type i)
337 return operator/= (rational<IntType>(i));
340 // Increment and decrement
341 template <typename IntType>
342 inline const rational<IntType>& rational<IntType>::operator++()
344 // This can never denormalise the fraction
349 template <typename IntType>
350 inline const rational<IntType>& rational<IntType>::operator--()
352 // This can never denormalise the fraction
357 // Comparison operators
358 template <typename IntType>
359 bool rational<IntType>::operator< (const rational<IntType>& r) const
361 // Avoid repeated construction
364 // If the two values have different signs, we don't need to do the
365 // expensive calculations below. We take advantage here of the fact
366 // that the denominator is always positive.
367 if (num < zero && r.num >= zero) // -ve < +ve
369 if (num >= zero && r.num <= zero) // +ve or zero is not < -ve or zero
373 IntType gcd1 = gcd<IntType>(num, r.num);
374 IntType gcd2 = gcd<IntType>(r.den, den);
375 return (num/gcd1) * (r.den/gcd2) < (den/gcd2) * (r.num/gcd1);
378 template <typename IntType>
379 bool rational<IntType>::operator< (param_type i) const
381 // Avoid repeated construction
384 // If the two values have different signs, we don't need to do the
385 // expensive calculations below. We take advantage here of the fact
386 // that the denominator is always positive.
387 if (num < zero && i >= zero) // -ve < +ve
389 if (num >= zero && i <= zero) // +ve or zero is not < -ve or zero
392 // Now, use the fact that n/d truncates towards zero as long as n and d
393 // are both positive.
394 // Divide instead of multiplying to avoid overflow issues. Of course,
395 // division may be slower, but accuracy is more important than speed...
397 return (num/den) < i;
399 return -i < (-num/den);
402 template <typename IntType>
403 bool rational<IntType>::operator> (param_type i) const
405 // Trap equality first
406 if (num == i && den == IntType(1))
409 // Otherwise, we can use operator<
410 return !operator<(i);
413 template <typename IntType>
414 inline bool rational<IntType>::operator== (const rational<IntType>& r) const
416 return ((num == r.num) && (den == r.den));
419 template <typename IntType>
420 inline bool rational<IntType>::operator== (param_type i) const
422 return ((den == IntType(1)) && (num == i));
426 template <typename IntType>
427 void rational<IntType>::normalize()
429 // Avoid repeated construction
433 throw bad_rational();
435 // Handle the case of zero separately, to avoid division by zero
441 IntType g = gcd<IntType>(num, den);
446 // Ensure that the denominator is positive
455 // A utility class to reset the format flags for an istream at end
456 // of scope, even in case of exceptions
458 resetter(std::istream& is) : is_(is), f_(is.flags()) {}
459 ~resetter() { is_.flags(f_); }
461 std::istream::fmtflags f_; // old GNU c++ lib has no ios_base
467 template <typename IntType>
468 std::istream& operator>> (std::istream& is, rational<IntType>& r)
470 IntType n = IntType(0), d = IntType(1);
472 detail::resetter sentry(is);
478 is.clear(std::istream::badbit); // old GNU c++ lib has no ios_base
480 #if !defined(__GNUC__) || (defined(__GNUC__) && (__GNUC__ >= 3)) || defined __SGI_STL_PORT
483 is.unsetf(ios::skipws); // compiles, but seems to have no effect.
493 // Add manipulators for output format?
494 template <typename IntType>
495 std::ostream& operator<< (std::ostream& os, const rational<IntType>& r)
497 os << r.numerator() << '/' << r.denominator();
502 template <typename T, typename IntType>
503 inline T rational_cast(const rational<IntType>& src)
505 return static_cast<T>(src.numerator())/src.denominator();
508 // Do not use any abs() defined on IntType - it isn't worth it, given the
509 // difficulties involved (Koenig lookup required, there may not *be* an abs()
510 // defined, etc etc).
511 template <typename IntType>
512 inline rational<IntType> abs(const rational<IntType>& r)
514 if (r.numerator() >= IntType(0))
517 return rational<IntType>(-r.numerator(), r.denominator());
522 #endif // BOOST_RATIONAL_HPP