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 for most recent version including 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 Jul 01 Recode gcd(), avoiding std::swap (Helmut Zeisel)
21 // 03 Mar 01 Workarounds for Intel C++ 5.0 (David Abrahams)
22 // 05 Feb 01 Update operator>> to tighten up input syntax
23 // 05 Feb 01 Final tidy up of gcd code prior to the new release
24 // 27 Jan 01 Recode abs() without relying on abs(IntType)
25 // 21 Jan 01 Include Nickolay Mladenov's operator+= algorithm,
26 // tidy up a number of areas, use newer features of operators.hpp
27 // (reduces space overhead to zero), add operator!,
28 // introduce explicit mixed-mode arithmetic operations
29 // 12 Jan 01 Include fixes to handle a user-defined IntType better
30 // 19 Nov 00 Throw on divide by zero in operator /= (John (EBo) David)
31 // 23 Jun 00 Incorporate changes from Mark Rodgers for Borland C++
32 // 22 Jun 00 Change _MSC_VER to BOOST_MSVC so other compilers are not
33 // affected (Beman Dawes)
34 // 6 Mar 00 Fix operator-= normalization, #include <string> (Jens Maurer)
35 // 14 Dec 99 Modifications based on comments from the boost list
36 // 09 Dec 99 Initial Version (Paul Moore)
38 #ifndef BOOST_RATIONAL_HPP
39 #define BOOST_RATIONAL_HPP
41 #include <iostream> // for std::istream and std::ostream
42 #include <iomanip> // for std::noskipws
43 #include <stdexcept> // for std::domain_error
44 #include <string> // for std::string implicit constructor
45 #include <boost/operators.hpp> // for boost::addable etc
46 #include <cstdlib> // for std::abs
47 #include <boost/call_traits.hpp> // for boost::call_traits
48 #include <boost/config.hpp> // for BOOST_NO_STDC_NAMESPACE, BOOST_MSVC
52 // Note: We use n and m as temporaries in this function, so there is no value
53 // in using const IntType& as we would only need to make a copy anyway...
54 template <typename IntType>
55 IntType gcd(IntType n, IntType m)
57 // Avoid repeated construction
60 // This is abs() - given the existence of broken compilers with Koenig
61 // lookup issues and other problems, I code this explicitly. (Remember,
62 // IntType may be a user-defined type).
68 // As n and m are now positive, we can be sure that %= returns a
69 // positive value (the standard guarantees this for built-in types,
70 // and we require it of user-defined types).
81 template <typename IntType>
82 IntType lcm(IntType n, IntType m)
84 // Avoid repeated construction
87 if (n == zero || m == zero)
98 class bad_rational : public std::domain_error
101 explicit bad_rational() : std::domain_error("bad rational: zero denominator") {}
104 template <typename IntType>
107 template <typename IntType>
108 rational<IntType> abs(const rational<IntType>& r);
110 template <typename IntType>
112 less_than_comparable < rational<IntType>,
113 equality_comparable < rational<IntType>,
114 less_than_comparable2 < rational<IntType>, IntType,
115 equality_comparable2 < rational<IntType>, IntType,
116 addable < rational<IntType>,
117 subtractable < rational<IntType>,
118 multipliable < rational<IntType>,
119 dividable < rational<IntType>,
120 addable2 < rational<IntType>, IntType,
121 subtractable2 < rational<IntType>, IntType,
122 multipliable2 < rational<IntType>, IntType,
123 dividable2 < rational<IntType>, IntType,
124 incrementable < rational<IntType>,
125 decrementable < rational<IntType>
126 > > > > > > > > > > > > > >
128 typedef IntType int_type;
129 typedef typename boost::call_traits<IntType>::param_type param_type;
132 rational() : num(0), den(1) {}
133 rational(param_type n) : num(n), den(1) {}
134 rational(param_type n, param_type d) : num(n), den(d) { normalize(); }
136 // Default copy constructor and assignment are fine
138 // Add assignment from IntType
139 rational& operator=(param_type n) { return assign(n, 1); }
142 rational& assign(param_type n, param_type d);
144 // Access to representation
145 IntType numerator() const { return num; }
146 IntType denominator() const { return den; }
148 // Arithmetic assignment operators
149 rational& operator+= (const rational& r);
150 rational& operator-= (const rational& r);
151 rational& operator*= (const rational& r);
152 rational& operator/= (const rational& r);
154 rational& operator+= (param_type i);
155 rational& operator-= (param_type i);
156 rational& operator*= (param_type i);
157 rational& operator/= (param_type i);
159 // Increment and decrement
160 const rational& operator++();
161 const rational& operator--();
164 bool operator!() const { return !num; }
166 // Comparison operators
167 bool operator< (const rational& r) const;
168 bool operator== (const rational& r) const;
170 bool operator< (param_type i) const;
171 bool operator> (param_type i) const;
172 bool operator== (param_type i) const;
175 // Implementation - numerator and denominator (normalized).
176 // Other possibilities - separate whole-part, or sign, fields?
180 // Representation note: Fractions are kept in normalized form at all
181 // times. normalized form is defined as gcd(num,den) == 1 and den > 0.
182 // In particular, note that the implementation of abs() below relies
183 // on den always being positive.
188 template <typename IntType>
189 inline rational<IntType>& rational<IntType>::assign(param_type n, param_type d)
197 // Unary plus and minus
198 template <typename IntType>
199 inline rational<IntType> operator+ (const rational<IntType>& r)
204 template <typename IntType>
205 inline rational<IntType> operator- (const rational<IntType>& r)
207 return rational<IntType>(-r.numerator(), r.denominator());
210 // Arithmetic assignment operators
211 template <typename IntType>
212 rational<IntType>& rational<IntType>::operator+= (const rational<IntType>& r)
214 // This calculation avoids overflow, and minimises the number of expensive
215 // calculations. Thanks to Nickolay Mladenov for this algorithm.
218 // We have to compute a/b + c/d, where gcd(a,b)=1 and gcd(b,c)=1.
219 // Let g = gcd(b,d), and b = b1*g, d=d1*g. Then gcd(b1,d1)=1
221 // The result is (a*d1 + c*b1) / (b1*d1*g).
222 // Now we have to normalize this ratio.
223 // Let's assume h | gcd((a*d1 + c*b1), (b1*d1*g)), and h > 1
224 // If h | b1 then gcd(h,d1)=1 and hence h|(a*d1+c*b1) => h|a.
225 // But since gcd(a,b1)=1 we have h=1.
226 // Similarly h|d1 leads to h=1.
227 // So we have that h | gcd((a*d1 + c*b1) , (b1*d1*g)) => h|g
228 // Finally we have gcd((a*d1 + c*b1), (b1*d1*g)) = gcd((a*d1 + c*b1), g)
229 // Which proves that instead of normalizing the result, it is better to
230 // divide num and den by gcd((a*d1 + c*b1), g)
232 // Protect against self-modification
233 IntType r_num = r.num;
234 IntType r_den = r.den;
236 IntType g = gcd(den, r_den);
237 den /= g; // = b1 from the calculations above
238 num = num * (r_den / g) + r_num * den;
246 template <typename IntType>
247 rational<IntType>& rational<IntType>::operator-= (const rational<IntType>& r)
249 // Protect against self-modification
250 IntType r_num = r.num;
251 IntType r_den = r.den;
253 // This calculation avoids overflow, and minimises the number of expensive
254 // calculations. It corresponds exactly to the += case above
255 IntType g = gcd(den, r_den);
257 num = num * (r_den / g) - r_num * den;
265 template <typename IntType>
266 rational<IntType>& rational<IntType>::operator*= (const rational<IntType>& r)
268 // Protect against self-modification
269 IntType r_num = r.num;
270 IntType r_den = r.den;
272 // Avoid overflow and preserve normalization
273 IntType gcd1 = gcd<IntType>(num, r_den);
274 IntType gcd2 = gcd<IntType>(r_num, den);
275 num = (num/gcd1) * (r_num/gcd2);
276 den = (den/gcd2) * (r_den/gcd1);
280 template <typename IntType>
281 rational<IntType>& rational<IntType>::operator/= (const rational<IntType>& r)
283 // Protect against self-modification
284 IntType r_num = r.num;
285 IntType r_den = r.den;
287 // Avoid repeated construction
290 // Trap division by zero
292 throw bad_rational();
296 // Avoid overflow and preserve normalization
297 IntType gcd1 = gcd<IntType>(num, r_num);
298 IntType gcd2 = gcd<IntType>(r_den, den);
299 num = (num/gcd1) * (r_den/gcd2);
300 den = (den/gcd2) * (r_num/gcd1);
309 // Mixed-mode operators
310 template <typename IntType>
311 inline rational<IntType>&
312 rational<IntType>::operator+= (param_type i)
314 return operator+= (rational<IntType>(i));
317 template <typename IntType>
318 inline rational<IntType>&
319 rational<IntType>::operator-= (param_type i)
321 return operator-= (rational<IntType>(i));
324 template <typename IntType>
325 inline rational<IntType>&
326 rational<IntType>::operator*= (param_type i)
328 return operator*= (rational<IntType>(i));
331 template <typename IntType>
332 inline rational<IntType>&
333 rational<IntType>::operator/= (param_type i)
335 return operator/= (rational<IntType>(i));
338 // Intel C++ seems to choke on this unless i is a reference parameter, matching
339 // the reference parameter in the operator-() generated by subtractable
340 template <typename IntType, typename T>
341 inline rational<IntType>
342 operator- (const T& i, const rational<IntType>& r)
344 IntType ii = i; // Must be able to implicitly convert T -> IntType
345 return rational<IntType>(ii) -= r;
348 // Intel C++ seems to choke on this unless i is a reference parameter, matching
349 // the reference parameter in the operator-() generated by subtractable
350 template <typename IntType, typename T>
351 inline rational<IntType>
352 operator/ (const T& i, const rational<IntType>& r)
354 IntType ii = i; // Must be able to implicitly convert T -> IntType
355 return rational<IntType>(ii) /= r;
358 // Increment and decrement
359 template <typename IntType>
360 inline const rational<IntType>& rational<IntType>::operator++()
362 // This can never denormalise the fraction
367 template <typename IntType>
368 inline const rational<IntType>& rational<IntType>::operator--()
370 // This can never denormalise the fraction
375 // Comparison operators
376 template <typename IntType>
377 bool rational<IntType>::operator< (const rational<IntType>& r) const
379 // Avoid repeated construction
382 // If the two values have different signs, we don't need to do the
383 // expensive calculations below. We take advantage here of the fact
384 // that the denominator is always positive.
385 if (num < zero && r.num >= zero) // -ve < +ve
387 if (num >= zero && r.num <= zero) // +ve or zero is not < -ve or zero
391 IntType gcd1 = gcd<IntType>(num, r.num);
392 IntType gcd2 = gcd<IntType>(r.den, den);
393 return (num/gcd1) * (r.den/gcd2) < (den/gcd2) * (r.num/gcd1);
396 template <typename IntType>
397 bool rational<IntType>::operator< (param_type i) const
399 // Avoid repeated construction
402 // If the two values have different signs, we don't need to do the
403 // expensive calculations below. We take advantage here of the fact
404 // that the denominator is always positive.
405 if (num < zero && i >= zero) // -ve < +ve
407 if (num >= zero && i <= zero) // +ve or zero is not < -ve or zero
410 // Now, use the fact that n/d truncates towards zero as long as n and d
411 // are both positive.
412 // Divide instead of multiplying to avoid overflow issues. Of course,
413 // division may be slower, but accuracy is more important than speed...
415 return (num/den) < i;
417 return -i < (-num/den);
420 template <typename IntType>
421 bool rational<IntType>::operator> (param_type i) const
423 // Trap equality first
424 if (num == i && den == IntType(1))
427 // Otherwise, we can use operator<
428 return !operator<(i);
431 template <typename IntType>
432 inline bool rational<IntType>::operator== (const rational<IntType>& r) const
434 return ((num == r.num) && (den == r.den));
437 template <typename IntType>
438 inline bool rational<IntType>::operator== (param_type i) const
440 return ((den == IntType(1)) && (num == i));
444 template <typename IntType>
445 void rational<IntType>::normalize()
447 // Avoid repeated construction
451 throw bad_rational();
453 // Handle the case of zero separately, to avoid division by zero
459 IntType g = gcd<IntType>(num, den);
464 // Ensure that the denominator is positive
473 // A utility class to reset the format flags for an istream at end
474 // of scope, even in case of exceptions
476 resetter(std::istream& is) : is_(is), f_(is.flags()) {}
477 ~resetter() { is_.flags(f_); }
479 std::istream::fmtflags f_; // old GNU c++ lib has no ios_base
485 template <typename IntType>
486 std::istream& operator>> (std::istream& is, rational<IntType>& r)
488 IntType n = IntType(0), d = IntType(1);
490 detail::resetter sentry(is);
496 is.clear(std::istream::badbit); // old GNU c++ lib has no ios_base
498 #if !defined(__GNUC__) || (defined(__GNUC__) && (__GNUC__ >= 3)) || defined __SGI_STL_PORT
501 is.unsetf(ios::skipws); // compiles, but seems to have no effect.
511 // Add manipulators for output format?
512 template <typename IntType>
513 std::ostream& operator<< (std::ostream& os, const rational<IntType>& r)
515 os << r.numerator() << '/' << r.denominator();
520 template <typename T, typename IntType>
521 inline T rational_cast(const rational<IntType>& src)
523 return static_cast<T>(src.numerator())/src.denominator();
526 // Do not use any abs() defined on IntType - it isn't worth it, given the
527 // difficulties involved (Koenig lookup required, there may not *be* an abs()
528 // defined, etc etc).
529 template <typename IntType>
530 inline rational<IntType> abs(const rational<IntType>& r)
532 if (r.numerator() >= IntType(0))
535 return rational<IntType>(-r.numerator(), r.denominator());
540 #endif // BOOST_RATIONAL_HPP