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 // 27 Dec 05 Add Boolean conversion operator (Daryle Walker)
21 // 28 Sep 02 Use _left versions of operators from operators.hpp
22 // 05 Jul 01 Recode gcd(), avoiding std::swap (Helmut Zeisel)
23 // 03 Mar 01 Workarounds for Intel C++ 5.0 (David Abrahams)
24 // 05 Feb 01 Update operator>> to tighten up input syntax
25 // 05 Feb 01 Final tidy up of gcd code prior to the new release
26 // 27 Jan 01 Recode abs() without relying on abs(IntType)
27 // 21 Jan 01 Include Nickolay Mladenov's operator+= algorithm,
28 // tidy up a number of areas, use newer features of operators.hpp
29 // (reduces space overhead to zero), add operator!,
30 // introduce explicit mixed-mode arithmetic operations
31 // 12 Jan 01 Include fixes to handle a user-defined IntType better
32 // 19 Nov 00 Throw on divide by zero in operator /= (John (EBo) David)
33 // 23 Jun 00 Incorporate changes from Mark Rodgers for Borland C++
34 // 22 Jun 00 Change _MSC_VER to BOOST_MSVC so other compilers are not
35 // affected (Beman Dawes)
36 // 6 Mar 00 Fix operator-= normalization, #include <string> (Jens Maurer)
37 // 14 Dec 99 Modifications based on comments from the boost list
38 // 09 Dec 99 Initial Version (Paul Moore)
40 #ifndef BOOST_RATIONAL_HPP
41 #define BOOST_RATIONAL_HPP
43 #include <iostream> // for std::istream and std::ostream
44 #include <iomanip> // for std::noskipws
45 #include <stdexcept> // for std::domain_error
46 #include <string> // for std::string implicit constructor
47 #include <boost/operators.hpp> // for boost::addable etc
48 #include <cstdlib> // for std::abs
49 #include <boost/call_traits.hpp> // for boost::call_traits
50 #include <boost/config.hpp> // for BOOST_NO_STDC_NAMESPACE, BOOST_MSVC
54 // Note: We use n and m as temporaries in this function, so there is no value
55 // in using const IntType& as we would only need to make a copy anyway...
56 template <typename IntType>
57 IntType gcd(IntType n, IntType m)
59 // Avoid repeated construction
62 // This is abs() - given the existence of broken compilers with Koenig
63 // lookup issues and other problems, I code this explicitly. (Remember,
64 // IntType may be a user-defined type).
70 // As n and m are now positive, we can be sure that %= returns a
71 // positive value (the standard guarantees this for built-in types,
72 // and we require it of user-defined types).
83 template <typename IntType>
84 IntType lcm(IntType n, IntType m)
86 // Avoid repeated construction
89 if (n == zero || m == zero)
100 class bad_rational : public std::domain_error
103 explicit bad_rational() : std::domain_error("bad rational: zero denominator") {}
106 template <typename IntType>
109 template <typename IntType>
110 rational<IntType> abs(const rational<IntType>& r);
112 template <typename IntType>
114 less_than_comparable < rational<IntType>,
115 equality_comparable < rational<IntType>,
116 less_than_comparable2 < rational<IntType>, IntType,
117 equality_comparable2 < rational<IntType>, IntType,
118 addable < rational<IntType>,
119 subtractable < rational<IntType>,
120 multipliable < rational<IntType>,
121 dividable < rational<IntType>,
122 addable2 < rational<IntType>, IntType,
123 subtractable2 < rational<IntType>, IntType,
124 subtractable2_left < rational<IntType>, IntType,
125 multipliable2 < rational<IntType>, IntType,
126 dividable2 < rational<IntType>, IntType,
127 dividable2_left < rational<IntType>, IntType,
128 incrementable < rational<IntType>,
129 decrementable < rational<IntType>
130 > > > > > > > > > > > > > > > >
132 typedef typename boost::call_traits<IntType>::param_type param_type;
134 struct helper { IntType parts[2]; };
135 typedef IntType (helper::* bool_type)[2];
138 typedef IntType int_type;
139 rational() : num(0), den(1) {}
140 rational(param_type n) : num(n), den(1) {}
141 rational(param_type n, param_type d) : num(n), den(d) { normalize(); }
143 // Default copy constructor and assignment are fine
145 // Add assignment from IntType
146 rational& operator=(param_type n) { return assign(n, 1); }
149 rational& assign(param_type n, param_type d);
151 // Access to representation
152 IntType numerator() const { return num; }
153 IntType denominator() const { return den; }
155 // Arithmetic assignment operators
156 rational& operator+= (const rational& r);
157 rational& operator-= (const rational& r);
158 rational& operator*= (const rational& r);
159 rational& operator/= (const rational& r);
161 rational& operator+= (param_type i);
162 rational& operator-= (param_type i);
163 rational& operator*= (param_type i);
164 rational& operator/= (param_type i);
166 // Increment and decrement
167 const rational& operator++();
168 const rational& operator--();
171 bool operator!() const { return !num; }
173 // Boolean conversion
174 operator bool_type() const { return operator !() ? 0 : &helper::parts; }
176 // Comparison operators
177 bool operator< (const rational& r) const;
178 bool operator== (const rational& r) const;
180 bool operator< (param_type i) const;
181 bool operator> (param_type i) const;
182 bool operator== (param_type i) const;
185 // Implementation - numerator and denominator (normalized).
186 // Other possibilities - separate whole-part, or sign, fields?
190 // Representation note: Fractions are kept in normalized form at all
191 // times. normalized form is defined as gcd(num,den) == 1 and den > 0.
192 // In particular, note that the implementation of abs() below relies
193 // on den always being positive.
198 template <typename IntType>
199 inline rational<IntType>& rational<IntType>::assign(param_type n, param_type d)
207 // Unary plus and minus
208 template <typename IntType>
209 inline rational<IntType> operator+ (const rational<IntType>& r)
214 template <typename IntType>
215 inline rational<IntType> operator- (const rational<IntType>& r)
217 return rational<IntType>(-r.numerator(), r.denominator());
220 // Arithmetic assignment operators
221 template <typename IntType>
222 rational<IntType>& rational<IntType>::operator+= (const rational<IntType>& r)
224 // This calculation avoids overflow, and minimises the number of expensive
225 // calculations. Thanks to Nickolay Mladenov for this algorithm.
228 // We have to compute a/b + c/d, where gcd(a,b)=1 and gcd(b,c)=1.
229 // Let g = gcd(b,d), and b = b1*g, d=d1*g. Then gcd(b1,d1)=1
231 // The result is (a*d1 + c*b1) / (b1*d1*g).
232 // Now we have to normalize this ratio.
233 // Let's assume h | gcd((a*d1 + c*b1), (b1*d1*g)), and h > 1
234 // If h | b1 then gcd(h,d1)=1 and hence h|(a*d1+c*b1) => h|a.
235 // But since gcd(a,b1)=1 we have h=1.
236 // Similarly h|d1 leads to h=1.
237 // So we have that h | gcd((a*d1 + c*b1) , (b1*d1*g)) => h|g
238 // Finally we have gcd((a*d1 + c*b1), (b1*d1*g)) = gcd((a*d1 + c*b1), g)
239 // Which proves that instead of normalizing the result, it is better to
240 // divide num and den by gcd((a*d1 + c*b1), g)
242 // Protect against self-modification
243 IntType r_num = r.num;
244 IntType r_den = r.den;
246 IntType g = gcd(den, r_den);
247 den /= g; // = b1 from the calculations above
248 num = num * (r_den / g) + r_num * den;
256 template <typename IntType>
257 rational<IntType>& rational<IntType>::operator-= (const rational<IntType>& r)
259 // Protect against self-modification
260 IntType r_num = r.num;
261 IntType r_den = r.den;
263 // This calculation avoids overflow, and minimises the number of expensive
264 // calculations. It corresponds exactly to the += case above
265 IntType g = gcd(den, r_den);
267 num = num * (r_den / g) - r_num * den;
275 template <typename IntType>
276 rational<IntType>& rational<IntType>::operator*= (const rational<IntType>& r)
278 // Protect against self-modification
279 IntType r_num = r.num;
280 IntType r_den = r.den;
282 // Avoid overflow and preserve normalization
283 IntType gcd1 = gcd<IntType>(num, r_den);
284 IntType gcd2 = gcd<IntType>(r_num, den);
285 num = (num/gcd1) * (r_num/gcd2);
286 den = (den/gcd2) * (r_den/gcd1);
290 template <typename IntType>
291 rational<IntType>& rational<IntType>::operator/= (const rational<IntType>& r)
293 // Protect against self-modification
294 IntType r_num = r.num;
295 IntType r_den = r.den;
297 // Avoid repeated construction
300 // Trap division by zero
302 throw bad_rational();
306 // Avoid overflow and preserve normalization
307 IntType gcd1 = gcd<IntType>(num, r_num);
308 IntType gcd2 = gcd<IntType>(r_den, den);
309 num = (num/gcd1) * (r_den/gcd2);
310 den = (den/gcd2) * (r_num/gcd1);
319 // Mixed-mode operators
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 template <typename IntType>
342 inline rational<IntType>&
343 rational<IntType>::operator/= (param_type i)
345 return operator/= (rational<IntType>(i));
348 // Increment and decrement
349 template <typename IntType>
350 inline const rational<IntType>& rational<IntType>::operator++()
352 // This can never denormalise the fraction
357 template <typename IntType>
358 inline const rational<IntType>& rational<IntType>::operator--()
360 // This can never denormalise the fraction
365 // Comparison operators
366 template <typename IntType>
367 bool rational<IntType>::operator< (const rational<IntType>& r) const
369 // Avoid repeated construction
372 // If the two values have different signs, we don't need to do the
373 // expensive calculations below. We take advantage here of the fact
374 // that the denominator is always positive.
375 if (num < zero && r.num >= zero) // -ve < +ve
377 if (num >= zero && r.num <= zero) // +ve or zero is not < -ve or zero
381 IntType gcd1 = gcd<IntType>(num, r.num);
382 IntType gcd2 = gcd<IntType>(r.den, den);
383 return (num/gcd1) * (r.den/gcd2) < (den/gcd2) * (r.num/gcd1);
386 template <typename IntType>
387 bool rational<IntType>::operator< (param_type i) const
389 // Avoid repeated construction
392 // If the two values have different signs, we don't need to do the
393 // expensive calculations below. We take advantage here of the fact
394 // that the denominator is always positive.
395 if (num < zero && i >= zero) // -ve < +ve
397 if (num >= zero && i <= zero) // +ve or zero is not < -ve or zero
400 // Now, use the fact that n/d truncates towards zero as long as n and d
401 // are both positive.
402 // Divide instead of multiplying to avoid overflow issues. Of course,
403 // division may be slower, but accuracy is more important than speed...
405 return (num/den) < i;
407 return -i < (-num/den);
410 template <typename IntType>
411 bool rational<IntType>::operator> (param_type i) const
413 // Trap equality first
414 if (num == i && den == IntType(1))
417 // Otherwise, we can use operator<
418 return !operator<(i);
421 template <typename IntType>
422 inline bool rational<IntType>::operator== (const rational<IntType>& r) const
424 return ((num == r.num) && (den == r.den));
427 template <typename IntType>
428 inline bool rational<IntType>::operator== (param_type i) const
430 return ((den == IntType(1)) && (num == i));
434 template <typename IntType>
435 void rational<IntType>::normalize()
437 // Avoid repeated construction
441 throw bad_rational();
443 // Handle the case of zero separately, to avoid division by zero
449 IntType g = gcd<IntType>(num, den);
454 // Ensure that the denominator is positive
463 // A utility class to reset the format flags for an istream at end
464 // of scope, even in case of exceptions
466 resetter(std::istream& is) : is_(is), f_(is.flags()) {}
467 ~resetter() { is_.flags(f_); }
469 std::istream::fmtflags f_; // old GNU c++ lib has no ios_base
475 template <typename IntType>
476 std::istream& operator>> (std::istream& is, rational<IntType>& r)
478 IntType n = IntType(0), d = IntType(1);
480 detail::resetter sentry(is);
486 is.clear(std::istream::badbit); // old GNU c++ lib has no ios_base
488 #if !defined(__GNUC__) || (defined(__GNUC__) && (__GNUC__ >= 3)) || defined __SGI_STL_PORT
491 is.unsetf(ios::skipws); // compiles, but seems to have no effect.
501 // Add manipulators for output format?
502 template <typename IntType>
503 std::ostream& operator<< (std::ostream& os, const rational<IntType>& r)
505 os << r.numerator() << '/' << r.denominator();
510 template <typename T, typename IntType>
511 inline T rational_cast(const rational<IntType>& src)
513 return static_cast<T>(src.numerator())/src.denominator();
516 // Do not use any abs() defined on IntType - it isn't worth it, given the
517 // difficulties involved (Koenig lookup required, there may not *be* an abs()
518 // defined, etc etc).
519 template <typename IntType>
520 inline rational<IntType> abs(const rational<IntType>& r)
522 if (r.numerator() >= IntType(0))
525 return rational<IntType>(-r.numerator(), r.denominator());
530 #endif // BOOST_RATIONAL_HPP