Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/boost_1_34_1/boost/rational.hpp @ 66

Last change on this file since 66 was 29, checked in by landauf, 16 years ago

updated boost from 1_33_1 to 1_34_1

File size: 16.1 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//  20 Oct 06  Fix operator bool_type for CW 8.3 (Joaquín M López Muñoz)
21//  18 Oct 06  Use EXPLICIT_TEMPLATE_TYPE helper macros from Boost.Config
22//             (Joaquín M López Muñoz)
23//  27 Dec 05  Add Boolean conversion operator (Daryle Walker)
24//  28 Sep 02  Use _left versions of operators from operators.hpp
25//  05 Jul 01  Recode gcd(), avoiding std::swap (Helmut Zeisel)
26//  03 Mar 01  Workarounds for Intel C++ 5.0 (David Abrahams)
27//  05 Feb 01  Update operator>> to tighten up input syntax
28//  05 Feb 01  Final tidy up of gcd code prior to the new release
29//  27 Jan 01  Recode abs() without relying on abs(IntType)
30//  21 Jan 01  Include Nickolay Mladenov's operator+= algorithm,
31//             tidy up a number of areas, use newer features of operators.hpp
32//             (reduces space overhead to zero), add operator!,
33//             introduce explicit mixed-mode arithmetic operations
34//  12 Jan 01  Include fixes to handle a user-defined IntType better
35//  19 Nov 00  Throw on divide by zero in operator /= (John (EBo) David)
36//  23 Jun 00  Incorporate changes from Mark Rodgers for Borland C++
37//  22 Jun 00  Change _MSC_VER to BOOST_MSVC so other compilers are not
38//             affected (Beman Dawes)
39//   6 Mar 00  Fix operator-= normalization, #include <string> (Jens Maurer)
40//  14 Dec 99  Modifications based on comments from the boost list
41//  09 Dec 99  Initial Version (Paul Moore)
42
43#ifndef BOOST_RATIONAL_HPP
44#define BOOST_RATIONAL_HPP
45
46#include <iostream>              // for std::istream and std::ostream
47#include <iomanip>               // for std::noskipws
48#include <stdexcept>             // for std::domain_error
49#include <string>                // for std::string implicit constructor
50#include <boost/operators.hpp>   // for boost::addable etc
51#include <cstdlib>               // for std::abs
52#include <boost/call_traits.hpp> // for boost::call_traits
53#include <boost/config.hpp>      // for BOOST_NO_STDC_NAMESPACE, BOOST_MSVC
54#include <boost/detail/workaround.hpp> // for BOOST_WORKAROUND
55
56namespace boost {
57
58// Note: We use n and m as temporaries in this function, so there is no value
59// in using const IntType& as we would only need to make a copy anyway...
60template <typename IntType>
61IntType gcd(IntType n, IntType m)
62{
63    // Avoid repeated construction
64    IntType zero(0);
65
66    // This is abs() - given the existence of broken compilers with Koenig
67    // lookup issues and other problems, I code this explicitly. (Remember,
68    // IntType may be a user-defined type).
69    if (n < zero)
70        n = -n;
71    if (m < zero)
72        m = -m;
73
74    // As n and m are now positive, we can be sure that %= returns a
75    // positive value (the standard guarantees this for built-in types,
76    // and we require it of user-defined types).
77    for(;;) {
78      if(m == zero)
79        return n;
80      n %= m;
81      if(n == zero)
82        return m;
83      m %= n;
84    }
85}
86
87template <typename IntType>
88IntType lcm(IntType n, IntType m)
89{
90    // Avoid repeated construction
91    IntType zero(0);
92
93    if (n == zero || m == zero)
94        return zero;
95
96    n /= gcd(n, m);
97    n *= m;
98
99    if (n < zero)
100        n = -n;
101    return n;
102}
103
104class bad_rational : public std::domain_error
105{
106public:
107    explicit bad_rational() : std::domain_error("bad rational: zero denominator") {}
108};
109
110template <typename IntType>
111class rational;
112
113template <typename IntType>
114rational<IntType> abs(const rational<IntType>& r);
115
116template <typename IntType>
117class rational :
118    less_than_comparable < rational<IntType>,
119    equality_comparable < rational<IntType>,
120    less_than_comparable2 < rational<IntType>, IntType,
121    equality_comparable2 < rational<IntType>, IntType,
122    addable < rational<IntType>,
123    subtractable < rational<IntType>,
124    multipliable < rational<IntType>,
125    dividable < rational<IntType>,
126    addable2 < rational<IntType>, IntType,
127    subtractable2 < rational<IntType>, IntType,
128    subtractable2_left < rational<IntType>, IntType,
129    multipliable2 < rational<IntType>, IntType,
130    dividable2 < rational<IntType>, IntType,
131    dividable2_left < rational<IntType>, IntType,
132    incrementable < rational<IntType>,
133    decrementable < rational<IntType>
134    > > > > > > > > > > > > > > > >
135{
136    typedef typename boost::call_traits<IntType>::param_type param_type;
137
138    struct helper { IntType parts[2]; };
139    typedef IntType (helper::* bool_type)[2];
140
141public:
142    typedef IntType int_type;
143    rational() : num(0), den(1) {}
144    rational(param_type n) : num(n), den(1) {}
145    rational(param_type n, param_type d) : num(n), den(d) { normalize(); }
146
147    // Default copy constructor and assignment are fine
148
149    // Add assignment from IntType
150    rational& operator=(param_type n) { return assign(n, 1); }
151
152    // Assign in place
153    rational& assign(param_type n, param_type d);
154
155    // Access to representation
156    IntType numerator() const { return num; }
157    IntType denominator() const { return den; }
158
159    // Arithmetic assignment operators
160    rational& operator+= (const rational& r);
161    rational& operator-= (const rational& r);
162    rational& operator*= (const rational& r);
163    rational& operator/= (const rational& r);
164
165    rational& operator+= (param_type i);
166    rational& operator-= (param_type i);
167    rational& operator*= (param_type i);
168    rational& operator/= (param_type i);
169
170    // Increment and decrement
171    const rational& operator++();
172    const rational& operator--();
173
174    // Operator not
175    bool operator!() const { return !num; }
176
177    // Boolean conversion
178   
179#if BOOST_WORKAROUND(__MWERKS__,<=0x3003)
180    // The "ISO C++ Template Parser" option in CW 8.3 chokes on the
181    // following, hence we selectively disable that option for the
182    // offending memfun.
183#pragma parse_mfunc_templ off
184#endif
185
186    operator bool_type() const { return operator !() ? 0 : &helper::parts; }
187
188#if BOOST_WORKAROUND(__MWERKS__,<=0x3003)
189#pragma parse_mfunc_templ reset
190#endif
191
192    // Comparison operators
193    bool operator< (const rational& r) const;
194    bool operator== (const rational& r) const;
195
196    bool operator< (param_type i) const;
197    bool operator> (param_type i) const;
198    bool operator== (param_type i) const;
199
200private:
201    // Implementation - numerator and denominator (normalized).
202    // Other possibilities - separate whole-part, or sign, fields?
203    IntType num;
204    IntType den;
205
206    // Representation note: Fractions are kept in normalized form at all
207    // times. normalized form is defined as gcd(num,den) == 1 and den > 0.
208    // In particular, note that the implementation of abs() below relies
209    // on den always being positive.
210    void normalize();
211};
212
213// Assign in place
214template <typename IntType>
215inline rational<IntType>& rational<IntType>::assign(param_type n, param_type d)
216{
217    num = n;
218    den = d;
219    normalize();
220    return *this;
221}
222
223// Unary plus and minus
224template <typename IntType>
225inline rational<IntType> operator+ (const rational<IntType>& r)
226{
227    return r;
228}
229
230template <typename IntType>
231inline rational<IntType> operator- (const rational<IntType>& r)
232{
233    return rational<IntType>(-r.numerator(), r.denominator());
234}
235
236// Arithmetic assignment operators
237template <typename IntType>
238rational<IntType>& rational<IntType>::operator+= (const rational<IntType>& r)
239{
240    // This calculation avoids overflow, and minimises the number of expensive
241    // calculations. Thanks to Nickolay Mladenov for this algorithm.
242    //
243    // Proof:
244    // We have to compute a/b + c/d, where gcd(a,b)=1 and gcd(b,c)=1.
245    // Let g = gcd(b,d), and b = b1*g, d=d1*g. Then gcd(b1,d1)=1
246    //
247    // The result is (a*d1 + c*b1) / (b1*d1*g).
248    // Now we have to normalize this ratio.
249    // Let's assume h | gcd((a*d1 + c*b1), (b1*d1*g)), and h > 1
250    // If h | b1 then gcd(h,d1)=1 and hence h|(a*d1+c*b1) => h|a.
251    // But since gcd(a,b1)=1 we have h=1.
252    // Similarly h|d1 leads to h=1.
253    // So we have that h | gcd((a*d1 + c*b1) , (b1*d1*g)) => h|g
254    // Finally we have gcd((a*d1 + c*b1), (b1*d1*g)) = gcd((a*d1 + c*b1), g)
255    // Which proves that instead of normalizing the result, it is better to
256    // divide num and den by gcd((a*d1 + c*b1), g)
257
258    // Protect against self-modification
259    IntType r_num = r.num;
260    IntType r_den = r.den;
261
262    IntType g = gcd(den, r_den);
263    den /= g;  // = b1 from the calculations above
264    num = num * (r_den / g) + r_num * den;
265    g = gcd(num, g);
266    num /= g;
267    den *= r_den/g;
268
269    return *this;
270}
271
272template <typename IntType>
273rational<IntType>& rational<IntType>::operator-= (const rational<IntType>& r)
274{
275    // Protect against self-modification
276    IntType r_num = r.num;
277    IntType r_den = r.den;
278
279    // This calculation avoids overflow, and minimises the number of expensive
280    // calculations. It corresponds exactly to the += case above
281    IntType g = gcd(den, r_den);
282    den /= g;
283    num = num * (r_den / g) - r_num * den;
284    g = gcd(num, g);
285    num /= g;
286    den *= r_den/g;
287
288    return *this;
289}
290
291template <typename IntType>
292rational<IntType>& rational<IntType>::operator*= (const rational<IntType>& r)
293{
294    // Protect against self-modification
295    IntType r_num = r.num;
296    IntType r_den = r.den;
297
298    // Avoid overflow and preserve normalization
299    IntType gcd1 = gcd<IntType>(num, r_den);
300    IntType gcd2 = gcd<IntType>(r_num, den);
301    num = (num/gcd1) * (r_num/gcd2);
302    den = (den/gcd2) * (r_den/gcd1);
303    return *this;
304}
305
306template <typename IntType>
307rational<IntType>& rational<IntType>::operator/= (const rational<IntType>& r)
308{
309    // Protect against self-modification
310    IntType r_num = r.num;
311    IntType r_den = r.den;
312
313    // Avoid repeated construction
314    IntType zero(0);
315
316    // Trap division by zero
317    if (r_num == zero)
318        throw bad_rational();
319    if (num == zero)
320        return *this;
321
322    // Avoid overflow and preserve normalization
323    IntType gcd1 = gcd<IntType>(num, r_num);
324    IntType gcd2 = gcd<IntType>(r_den, den);
325    num = (num/gcd1) * (r_den/gcd2);
326    den = (den/gcd2) * (r_num/gcd1);
327
328    if (den < zero) {
329        num = -num;
330        den = -den;
331    }
332    return *this;
333}
334
335// Mixed-mode operators
336template <typename IntType>
337inline rational<IntType>&
338rational<IntType>::operator+= (param_type i)
339{
340    return operator+= (rational<IntType>(i));
341}
342
343template <typename IntType>
344inline rational<IntType>&
345rational<IntType>::operator-= (param_type i)
346{
347    return operator-= (rational<IntType>(i));
348}
349
350template <typename IntType>
351inline rational<IntType>&
352rational<IntType>::operator*= (param_type i)
353{
354    return operator*= (rational<IntType>(i));
355}
356
357template <typename IntType>
358inline rational<IntType>&
359rational<IntType>::operator/= (param_type i)
360{
361    return operator/= (rational<IntType>(i));
362}
363
364// Increment and decrement
365template <typename IntType>
366inline const rational<IntType>& rational<IntType>::operator++()
367{
368    // This can never denormalise the fraction
369    num += den;
370    return *this;
371}
372
373template <typename IntType>
374inline const rational<IntType>& rational<IntType>::operator--()
375{
376    // This can never denormalise the fraction
377    num -= den;
378    return *this;
379}
380
381// Comparison operators
382template <typename IntType>
383bool rational<IntType>::operator< (const rational<IntType>& r) const
384{
385    // Avoid repeated construction
386    IntType zero(0);
387
388    // If the two values have different signs, we don't need to do the
389    // expensive calculations below. We take advantage here of the fact
390    // that the denominator is always positive.
391    if (num < zero && r.num >= zero) // -ve < +ve
392        return true;
393    if (num >= zero && r.num <= zero) // +ve or zero is not < -ve or zero
394        return false;
395
396    // Avoid overflow
397    IntType gcd1 = gcd<IntType>(num, r.num);
398    IntType gcd2 = gcd<IntType>(r.den, den);
399    return (num/gcd1) * (r.den/gcd2) < (den/gcd2) * (r.num/gcd1);
400}
401
402template <typename IntType>
403bool rational<IntType>::operator< (param_type i) const
404{
405    // Avoid repeated construction
406    IntType zero(0);
407
408    // If the two values have different signs, we don't need to do the
409    // expensive calculations below. We take advantage here of the fact
410    // that the denominator is always positive.
411    if (num < zero && i >= zero) // -ve < +ve
412        return true;
413    if (num >= zero && i <= zero) // +ve or zero is not < -ve or zero
414        return false;
415
416    // Now, use the fact that n/d truncates towards zero as long as n and d
417    // are both positive.
418    // Divide instead of multiplying to avoid overflow issues. Of course,
419    // division may be slower, but accuracy is more important than speed...
420    if (num > zero)
421        return (num/den) < i;
422    else
423        return -i < (-num/den);
424}
425
426template <typename IntType>
427bool rational<IntType>::operator> (param_type i) const
428{
429    // Trap equality first
430    if (num == i && den == IntType(1))
431        return false;
432
433    // Otherwise, we can use operator<
434    return !operator<(i);
435}
436
437template <typename IntType>
438inline bool rational<IntType>::operator== (const rational<IntType>& r) const
439{
440    return ((num == r.num) && (den == r.den));
441}
442
443template <typename IntType>
444inline bool rational<IntType>::operator== (param_type i) const
445{
446    return ((den == IntType(1)) && (num == i));
447}
448
449// Normalisation
450template <typename IntType>
451void rational<IntType>::normalize()
452{
453    // Avoid repeated construction
454    IntType zero(0);
455
456    if (den == zero)
457        throw bad_rational();
458
459    // Handle the case of zero separately, to avoid division by zero
460    if (num == zero) {
461        den = IntType(1);
462        return;
463    }
464
465    IntType g = gcd<IntType>(num, den);
466
467    num /= g;
468    den /= g;
469
470    // Ensure that the denominator is positive
471    if (den < zero) {
472        num = -num;
473        den = -den;
474    }
475}
476
477namespace detail {
478
479    // A utility class to reset the format flags for an istream at end
480    // of scope, even in case of exceptions
481    struct resetter {
482        resetter(std::istream& is) : is_(is), f_(is.flags()) {}
483        ~resetter() { is_.flags(f_); }
484        std::istream& is_;
485        std::istream::fmtflags f_;      // old GNU c++ lib has no ios_base
486    };
487
488}
489
490// Input and output
491template <typename IntType>
492std::istream& operator>> (std::istream& is, rational<IntType>& r)
493{
494    IntType n = IntType(0), d = IntType(1);
495    char c = 0;
496    detail::resetter sentry(is);
497
498    is >> n;
499    c = is.get();
500
501    if (c != '/')
502        is.clear(std::istream::badbit);  // old GNU c++ lib has no ios_base
503
504#if !defined(__GNUC__) || (defined(__GNUC__) && (__GNUC__ >= 3)) || defined __SGI_STL_PORT
505    is >> std::noskipws;
506#else
507    is.unsetf(ios::skipws); // compiles, but seems to have no effect.
508#endif
509    is >> d;
510
511    if (is)
512        r.assign(n, d);
513
514    return is;
515}
516
517// Add manipulators for output format?
518template <typename IntType>
519std::ostream& operator<< (std::ostream& os, const rational<IntType>& r)
520{
521    os << r.numerator() << '/' << r.denominator();
522    return os;
523}
524
525// Type conversion
526template <typename T, typename IntType>
527inline T rational_cast(
528    const rational<IntType>& src BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE(T))
529{
530    return static_cast<T>(src.numerator())/src.denominator();
531}
532
533// Do not use any abs() defined on IntType - it isn't worth it, given the
534// difficulties involved (Koenig lookup required, there may not *be* an abs()
535// defined, etc etc).
536template <typename IntType>
537inline rational<IntType> abs(const rational<IntType>& r)
538{
539    if (r.numerator() >= IntType(0))
540        return r;
541
542    return rational<IntType>(-r.numerator(), r.denominator());
543}
544
545} // namespace boost
546
547#endif  // BOOST_RATIONAL_HPP
548
Note: See TracBrowser for help on using the repository browser.