Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/boost_1_33_1/boost/rational.hpp @ 12

Last change on this file since 12 was 12, checked in by landauf, 17 years ago

added boost

File size: 15.2 KB
Line 
1//  Boost rational.hpp header file  ------------------------------------------//
2
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.
7
8//  See http://www.boost.org/libs/rational for documentation.
9
10//  Credits:
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
16//    IntType
17//    Nickolay Mladenov, for the implementation of operator+=
18
19//  Revision History
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)
38
39#ifndef BOOST_RATIONAL_HPP
40#define BOOST_RATIONAL_HPP
41
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
50
51namespace boost {
52
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...
55template <typename IntType>
56IntType gcd(IntType n, IntType m)
57{
58    // Avoid repeated construction
59    IntType zero(0);
60
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).
64    if (n < zero)
65        n = -n;
66    if (m < zero)
67        m = -m;
68
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).
72    for(;;) {
73      if(m == zero)
74        return n;
75      n %= m;
76      if(n == zero)
77        return m;
78      m %= n;
79    }
80}
81
82template <typename IntType>
83IntType lcm(IntType n, IntType m)
84{
85    // Avoid repeated construction
86    IntType zero(0);
87
88    if (n == zero || m == zero)
89        return zero;
90
91    n /= gcd(n, m);
92    n *= m;
93
94    if (n < zero)
95        n = -n;
96    return n;
97}
98
99class bad_rational : public std::domain_error
100{
101public:
102    explicit bad_rational() : std::domain_error("bad rational: zero denominator") {}
103};
104
105template <typename IntType>
106class rational;
107
108template <typename IntType>
109rational<IntType> abs(const rational<IntType>& r);
110
111template <typename IntType>
112class rational :
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    > > > > > > > > > > > > > > > >
130{
131    typedef typename boost::call_traits<IntType>::param_type param_type;
132public:
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(); }
137
138    // Default copy constructor and assignment are fine
139
140    // Add assignment from IntType
141    rational& operator=(param_type n) { return assign(n, 1); }
142
143    // Assign in place
144    rational& assign(param_type n, param_type d);
145
146    // Access to representation
147    IntType numerator() const { return num; }
148    IntType denominator() const { return den; }
149
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);
155
156    rational& operator+= (param_type i);
157    rational& operator-= (param_type i);
158    rational& operator*= (param_type i);
159    rational& operator/= (param_type i);
160
161    // Increment and decrement
162    const rational& operator++();
163    const rational& operator--();
164
165    // Operator not
166    bool operator!() const { return !num; }
167
168    // Comparison operators
169    bool operator< (const rational& r) const;
170    bool operator== (const rational& r) const;
171
172    bool operator< (param_type i) const;
173    bool operator> (param_type i) const;
174    bool operator== (param_type i) const;
175
176private:
177    // Implementation - numerator and denominator (normalized).
178    // Other possibilities - separate whole-part, or sign, fields?
179    IntType num;
180    IntType den;
181
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.
186    void normalize();
187};
188
189// Assign in place
190template <typename IntType>
191inline rational<IntType>& rational<IntType>::assign(param_type n, param_type d)
192{
193    num = n;
194    den = d;
195    normalize();
196    return *this;
197}
198
199// Unary plus and minus
200template <typename IntType>
201inline rational<IntType> operator+ (const rational<IntType>& r)
202{
203    return r;
204}
205
206template <typename IntType>
207inline rational<IntType> operator- (const rational<IntType>& r)
208{
209    return rational<IntType>(-r.numerator(), r.denominator());
210}
211
212// Arithmetic assignment operators
213template <typename IntType>
214rational<IntType>& rational<IntType>::operator+= (const rational<IntType>& r)
215{
216    // This calculation avoids overflow, and minimises the number of expensive
217    // calculations. Thanks to Nickolay Mladenov for this algorithm.
218    //
219    // Proof:
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
222    //
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)
233
234    // Protect against self-modification
235    IntType r_num = r.num;
236    IntType r_den = r.den;
237
238    IntType g = gcd(den, r_den);
239    den /= g;  // = b1 from the calculations above
240    num = num * (r_den / g) + r_num * den;
241    g = gcd(num, g);
242    num /= g;
243    den *= r_den/g;
244
245    return *this;
246}
247
248template <typename IntType>
249rational<IntType>& rational<IntType>::operator-= (const rational<IntType>& r)
250{
251    // Protect against self-modification
252    IntType r_num = r.num;
253    IntType r_den = r.den;
254
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);
258    den /= g;
259    num = num * (r_den / g) - r_num * den;
260    g = gcd(num, g);
261    num /= g;
262    den *= r_den/g;
263
264    return *this;
265}
266
267template <typename IntType>
268rational<IntType>& rational<IntType>::operator*= (const rational<IntType>& r)
269{
270    // Protect against self-modification
271    IntType r_num = r.num;
272    IntType r_den = r.den;
273
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);
279    return *this;
280}
281
282template <typename IntType>
283rational<IntType>& rational<IntType>::operator/= (const rational<IntType>& r)
284{
285    // Protect against self-modification
286    IntType r_num = r.num;
287    IntType r_den = r.den;
288
289    // Avoid repeated construction
290    IntType zero(0);
291
292    // Trap division by zero
293    if (r_num == zero)
294        throw bad_rational();
295    if (num == zero)
296        return *this;
297
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);
303
304    if (den < zero) {
305        num = -num;
306        den = -den;
307    }
308    return *this;
309}
310
311// Mixed-mode operators
312template <typename IntType>
313inline rational<IntType>&
314rational<IntType>::operator+= (param_type i)
315{
316    return operator+= (rational<IntType>(i));
317}
318
319template <typename IntType>
320inline rational<IntType>&
321rational<IntType>::operator-= (param_type i)
322{
323    return operator-= (rational<IntType>(i));
324}
325
326template <typename IntType>
327inline rational<IntType>&
328rational<IntType>::operator*= (param_type i)
329{
330    return operator*= (rational<IntType>(i));
331}
332
333template <typename IntType>
334inline rational<IntType>&
335rational<IntType>::operator/= (param_type i)
336{
337    return operator/= (rational<IntType>(i));
338}
339
340// Increment and decrement
341template <typename IntType>
342inline const rational<IntType>& rational<IntType>::operator++()
343{
344    // This can never denormalise the fraction
345    num += den;
346    return *this;
347}
348
349template <typename IntType>
350inline const rational<IntType>& rational<IntType>::operator--()
351{
352    // This can never denormalise the fraction
353    num -= den;
354    return *this;
355}
356
357// Comparison operators
358template <typename IntType>
359bool rational<IntType>::operator< (const rational<IntType>& r) const
360{
361    // Avoid repeated construction
362    IntType zero(0);
363
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
368        return true;
369    if (num >= zero && r.num <= zero) // +ve or zero is not < -ve or zero
370        return false;
371
372    // Avoid overflow
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);
376}
377
378template <typename IntType>
379bool rational<IntType>::operator< (param_type i) const
380{
381    // Avoid repeated construction
382    IntType zero(0);
383
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
388        return true;
389    if (num >= zero && i <= zero) // +ve or zero is not < -ve or zero
390        return false;
391
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...
396    if (num > zero)
397        return (num/den) < i;
398    else
399        return -i < (-num/den);
400}
401
402template <typename IntType>
403bool rational<IntType>::operator> (param_type i) const
404{
405    // Trap equality first
406    if (num == i && den == IntType(1))
407        return false;
408
409    // Otherwise, we can use operator<
410    return !operator<(i);
411}
412
413template <typename IntType>
414inline bool rational<IntType>::operator== (const rational<IntType>& r) const
415{
416    return ((num == r.num) && (den == r.den));
417}
418
419template <typename IntType>
420inline bool rational<IntType>::operator== (param_type i) const
421{
422    return ((den == IntType(1)) && (num == i));
423}
424
425// Normalisation
426template <typename IntType>
427void rational<IntType>::normalize()
428{
429    // Avoid repeated construction
430    IntType zero(0);
431
432    if (den == zero)
433        throw bad_rational();
434
435    // Handle the case of zero separately, to avoid division by zero
436    if (num == zero) {
437        den = IntType(1);
438        return;
439    }
440
441    IntType g = gcd<IntType>(num, den);
442
443    num /= g;
444    den /= g;
445
446    // Ensure that the denominator is positive
447    if (den < zero) {
448        num = -num;
449        den = -den;
450    }
451}
452
453namespace detail {
454
455    // A utility class to reset the format flags for an istream at end
456    // of scope, even in case of exceptions
457    struct resetter {
458        resetter(std::istream& is) : is_(is), f_(is.flags()) {}
459        ~resetter() { is_.flags(f_); }
460        std::istream& is_;
461        std::istream::fmtflags f_;      // old GNU c++ lib has no ios_base
462    };
463
464}
465
466// Input and output
467template <typename IntType>
468std::istream& operator>> (std::istream& is, rational<IntType>& r)
469{
470    IntType n = IntType(0), d = IntType(1);
471    char c = 0;
472    detail::resetter sentry(is);
473
474    is >> n;
475    c = is.get();
476
477    if (c != '/')
478        is.clear(std::istream::badbit);  // old GNU c++ lib has no ios_base
479
480#if !defined(__GNUC__) || (defined(__GNUC__) && (__GNUC__ >= 3)) || defined __SGI_STL_PORT
481    is >> std::noskipws;
482#else
483    is.unsetf(ios::skipws); // compiles, but seems to have no effect.
484#endif
485    is >> d;
486
487    if (is)
488        r.assign(n, d);
489
490    return is;
491}
492
493// Add manipulators for output format?
494template <typename IntType>
495std::ostream& operator<< (std::ostream& os, const rational<IntType>& r)
496{
497    os << r.numerator() << '/' << r.denominator();
498    return os;
499}
500
501// Type conversion
502template <typename T, typename IntType>
503inline T rational_cast(const rational<IntType>& src)
504{
505    return static_cast<T>(src.numerator())/src.denominator();
506}
507
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).
511template <typename IntType>
512inline rational<IntType> abs(const rational<IntType>& r)
513{
514    if (r.numerator() >= IntType(0))
515        return r;
516
517    return rational<IntType>(-r.numerator(), r.denominator());
518}
519
520} // namespace boost
521
522#endif  // BOOST_RATIONAL_HPP
523
Note: See TracBrowser for help on using the repository browser.