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 IntType int_type;
132 typedef typename boost::call_traits<IntType>::param_type param_type;
135 rational() : num(0), den(1) {}
136 rational(param_type n) : num(n), den(1) {}
137 rational(param_type n, param_type d) : num(n), den(d) { normalize(); }
139 // Default copy constructor and assignment are fine
141 // Add assignment from IntType
142 rational& operator=(param_type n) { return assign(n, 1); }
145 rational& assign(param_type n, param_type d);
147 // Access to representation
148 IntType numerator() const { return num; }
149 IntType denominator() const { return den; }
151 // Arithmetic assignment operators
152 rational& operator+= (const rational& r);
153 rational& operator-= (const rational& r);
154 rational& operator*= (const rational& r);
155 rational& operator/= (const rational& r);
157 rational& operator+= (param_type i);
158 rational& operator-= (param_type i);
159 rational& operator*= (param_type i);
160 rational& operator/= (param_type i);
162 // Increment and decrement
163 const rational& operator++();
164 const rational& operator--();
167 bool operator!() const { return !num; }
169 // Comparison operators
170 bool operator< (const rational& r) const;
171 bool operator== (const rational& r) const;
173 bool operator< (param_type i) const;
174 bool operator> (param_type i) const;
175 bool operator== (param_type i) const;
178 // Implementation - numerator and denominator (normalized).
179 // Other possibilities - separate whole-part, or sign, fields?
183 // Representation note: Fractions are kept in normalized form at all
184 // times. normalized form is defined as gcd(num,den) == 1 and den > 0.
185 // In particular, note that the implementation of abs() below relies
186 // on den always being positive.
191 template <typename IntType>
192 inline rational<IntType>& rational<IntType>::assign(param_type n, param_type d)
200 // Unary plus and minus
201 template <typename IntType>
202 inline rational<IntType> operator+ (const rational<IntType>& r)
207 template <typename IntType>
208 inline rational<IntType> operator- (const rational<IntType>& r)
210 return rational<IntType>(-r.numerator(), r.denominator());
213 // Arithmetic assignment operators
214 template <typename IntType>
215 rational<IntType>& rational<IntType>::operator+= (const rational<IntType>& r)
217 // This calculation avoids overflow, and minimises the number of expensive
218 // calculations. Thanks to Nickolay Mladenov for this algorithm.
221 // We have to compute a/b + c/d, where gcd(a,b)=1 and gcd(b,c)=1.
222 // Let g = gcd(b,d), and b = b1*g, d=d1*g. Then gcd(b1,d1)=1
224 // The result is (a*d1 + c*b1) / (b1*d1*g).
225 // Now we have to normalize this ratio.
226 // Let's assume h | gcd((a*d1 + c*b1), (b1*d1*g)), and h > 1
227 // If h | b1 then gcd(h,d1)=1 and hence h|(a*d1+c*b1) => h|a.
228 // But since gcd(a,b1)=1 we have h=1.
229 // Similarly h|d1 leads to h=1.
230 // So we have that h | gcd((a*d1 + c*b1) , (b1*d1*g)) => h|g
231 // Finally we have gcd((a*d1 + c*b1), (b1*d1*g)) = gcd((a*d1 + c*b1), g)
232 // Which proves that instead of normalizing the result, it is better to
233 // divide num and den by gcd((a*d1 + c*b1), g)
235 // Protect against self-modification
236 IntType r_num = r.num;
237 IntType r_den = r.den;
239 IntType g = gcd(den, r_den);
240 den /= g; // = b1 from the calculations above
241 num = num * (r_den / g) + r_num * den;
249 template <typename IntType>
250 rational<IntType>& rational<IntType>::operator-= (const rational<IntType>& r)
252 // Protect against self-modification
253 IntType r_num = r.num;
254 IntType r_den = r.den;
256 // This calculation avoids overflow, and minimises the number of expensive
257 // calculations. It corresponds exactly to the += case above
258 IntType g = gcd(den, r_den);
260 num = num * (r_den / g) - r_num * den;
268 template <typename IntType>
269 rational<IntType>& rational<IntType>::operator*= (const rational<IntType>& r)
271 // Protect against self-modification
272 IntType r_num = r.num;
273 IntType r_den = r.den;
275 // Avoid overflow and preserve normalization
276 IntType gcd1 = gcd<IntType>(num, r_den);
277 IntType gcd2 = gcd<IntType>(r_num, den);
278 num = (num/gcd1) * (r_num/gcd2);
279 den = (den/gcd2) * (r_den/gcd1);
283 template <typename IntType>
284 rational<IntType>& rational<IntType>::operator/= (const rational<IntType>& r)
286 // Protect against self-modification
287 IntType r_num = r.num;
288 IntType r_den = r.den;
290 // Avoid repeated construction
293 // Trap division by zero
295 throw bad_rational();
299 // Avoid overflow and preserve normalization
300 IntType gcd1 = gcd<IntType>(num, r_num);
301 IntType gcd2 = gcd<IntType>(r_den, den);
302 num = (num/gcd1) * (r_den/gcd2);
303 den = (den/gcd2) * (r_num/gcd1);
312 // Mixed-mode operators
313 template <typename IntType>
314 inline rational<IntType>&
315 rational<IntType>::operator+= (param_type i)
317 return operator+= (rational<IntType>(i));
320 template <typename IntType>
321 inline rational<IntType>&
322 rational<IntType>::operator-= (param_type i)
324 return operator-= (rational<IntType>(i));
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 // Increment and decrement
342 template <typename IntType>
343 inline const rational<IntType>& rational<IntType>::operator++()
345 // This can never denormalise the fraction
350 template <typename IntType>
351 inline const rational<IntType>& rational<IntType>::operator--()
353 // This can never denormalise the fraction
358 // Comparison operators
359 template <typename IntType>
360 bool rational<IntType>::operator< (const rational<IntType>& r) const
362 // Avoid repeated construction
365 // If the two values have different signs, we don't need to do the
366 // expensive calculations below. We take advantage here of the fact
367 // that the denominator is always positive.
368 if (num < zero && r.num >= zero) // -ve < +ve
370 if (num >= zero && r.num <= zero) // +ve or zero is not < -ve or zero
374 IntType gcd1 = gcd<IntType>(num, r.num);
375 IntType gcd2 = gcd<IntType>(r.den, den);
376 return (num/gcd1) * (r.den/gcd2) < (den/gcd2) * (r.num/gcd1);
379 template <typename IntType>
380 bool rational<IntType>::operator< (param_type i) const
382 // Avoid repeated construction
385 // If the two values have different signs, we don't need to do the
386 // expensive calculations below. We take advantage here of the fact
387 // that the denominator is always positive.
388 if (num < zero && i >= zero) // -ve < +ve
390 if (num >= zero && i <= zero) // +ve or zero is not < -ve or zero
393 // Now, use the fact that n/d truncates towards zero as long as n and d
394 // are both positive.
395 // Divide instead of multiplying to avoid overflow issues. Of course,
396 // division may be slower, but accuracy is more important than speed...
398 return (num/den) < i;
400 return -i < (-num/den);
403 template <typename IntType>
404 bool rational<IntType>::operator> (param_type i) const
406 // Trap equality first
407 if (num == i && den == IntType(1))
410 // Otherwise, we can use operator<
411 return !operator<(i);
414 template <typename IntType>
415 inline bool rational<IntType>::operator== (const rational<IntType>& r) const
417 return ((num == r.num) && (den == r.den));
420 template <typename IntType>
421 inline bool rational<IntType>::operator== (param_type i) const
423 return ((den == IntType(1)) && (num == i));
427 template <typename IntType>
428 void rational<IntType>::normalize()
430 // Avoid repeated construction
434 throw bad_rational();
436 // Handle the case of zero separately, to avoid division by zero
442 IntType g = gcd<IntType>(num, den);
447 // Ensure that the denominator is positive
456 // A utility class to reset the format flags for an istream at end
457 // of scope, even in case of exceptions
459 resetter(std::istream& is) : is_(is), f_(is.flags()) {}
460 ~resetter() { is_.flags(f_); }
462 std::istream::fmtflags f_; // old GNU c++ lib has no ios_base
468 template <typename IntType>
469 std::istream& operator>> (std::istream& is, rational<IntType>& r)
471 IntType n = IntType(0), d = IntType(1);
473 detail::resetter sentry(is);
479 is.clear(std::istream::badbit); // old GNU c++ lib has no ios_base
481 #if !defined(__GNUC__) || (defined(__GNUC__) && (__GNUC__ >= 3)) || defined __SGI_STL_PORT
484 is.unsetf(ios::skipws); // compiles, but seems to have no effect.
494 // Add manipulators for output format?
495 template <typename IntType>
496 std::ostream& operator<< (std::ostream& os, const rational<IntType>& r)
498 os << r.numerator() << '/' << r.denominator();
503 template <typename T, typename IntType>
504 inline T rational_cast(const rational<IntType>& src)
506 return static_cast<T>(src.numerator())/src.denominator();
509 // Do not use any abs() defined on IntType - it isn't worth it, given the
510 // difficulties involved (Koenig lookup required, there may not *be* an abs()
511 // defined, etc etc).
512 template <typename IntType>
513 inline rational<IntType> abs(const rational<IntType>& r)
515 if (r.numerator() >= IntType(0))
518 return rational<IntType>(-r.numerator(), r.denominator());
523 #endif // BOOST_RATIONAL_HPP