]> git.lyx.org Git - lyx.git/blob - boost/boost/rational.hpp
update boost to version 1.36
[lyx.git] / boost / boost / rational.hpp
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 //  05 Nov 06  Change rational_cast to not depend on division between different
21 //             types (Daryle Walker)
22 //  04 Nov 06  Off-load GCD and LCM to Boost.Math; add some invariant checks;
23 //             add std::numeric_limits<> requirement to help GCD (Daryle Walker)
24 //  31 Oct 06  Recoded both operator< to use round-to-negative-infinity
25 //             divisions; the rational-value version now uses continued fraction
26 //             expansion to avoid overflows, for bug #798357 (Daryle Walker)
27 //  20 Oct 06  Fix operator bool_type for CW 8.3 (Joaquín M López Muñoz)
28 //  18 Oct 06  Use EXPLICIT_TEMPLATE_TYPE helper macros from Boost.Config
29 //             (Joaquín M López Muñoz)
30 //  27 Dec 05  Add Boolean conversion operator (Daryle Walker)
31 //  28 Sep 02  Use _left versions of operators from operators.hpp
32 //  05 Jul 01  Recode gcd(), avoiding std::swap (Helmut Zeisel)
33 //  03 Mar 01  Workarounds for Intel C++ 5.0 (David Abrahams)
34 //  05 Feb 01  Update operator>> to tighten up input syntax
35 //  05 Feb 01  Final tidy up of gcd code prior to the new release
36 //  27 Jan 01  Recode abs() without relying on abs(IntType)
37 //  21 Jan 01  Include Nickolay Mladenov's operator+= algorithm,
38 //             tidy up a number of areas, use newer features of operators.hpp
39 //             (reduces space overhead to zero), add operator!,
40 //             introduce explicit mixed-mode arithmetic operations
41 //  12 Jan 01  Include fixes to handle a user-defined IntType better
42 //  19 Nov 00  Throw on divide by zero in operator /= (John (EBo) David)
43 //  23 Jun 00  Incorporate changes from Mark Rodgers for Borland C++
44 //  22 Jun 00  Change _MSC_VER to BOOST_MSVC so other compilers are not
45 //             affected (Beman Dawes)
46 //   6 Mar 00  Fix operator-= normalization, #include <string> (Jens Maurer)
47 //  14 Dec 99  Modifications based on comments from the boost list
48 //  09 Dec 99  Initial Version (Paul Moore)
49
50 #ifndef BOOST_RATIONAL_HPP
51 #define BOOST_RATIONAL_HPP
52
53 #include <iostream>              // for std::istream and std::ostream
54 #include <iomanip>               // for std::noskipws
55 #include <stdexcept>             // for std::domain_error
56 #include <string>                // for std::string implicit constructor
57 #include <boost/operators.hpp>   // for boost::addable etc
58 #include <cstdlib>               // for std::abs
59 #include <boost/call_traits.hpp> // for boost::call_traits
60 #include <boost/config.hpp>      // for BOOST_NO_STDC_NAMESPACE, BOOST_MSVC
61 #include <boost/detail/workaround.hpp> // for BOOST_WORKAROUND
62 #include <boost/assert.hpp>      // for BOOST_ASSERT
63 #include <boost/math/common_factor_rt.hpp>  // for boost::math::gcd, lcm
64 #include <limits>                // for std::numeric_limits
65 #include <boost/static_assert.hpp>  // for BOOST_STATIC_ASSERT
66
67 // Control whether depreciated GCD and LCM functions are included (default: yes)
68 #ifndef BOOST_CONTROL_RATIONAL_HAS_GCD
69 #define BOOST_CONTROL_RATIONAL_HAS_GCD  1
70 #endif
71
72 namespace boost {
73
74 #if BOOST_CONTROL_RATIONAL_HAS_GCD
75 template <typename IntType>
76 IntType gcd(IntType n, IntType m)
77 {
78     // Defer to the version in Boost.Math
79     return math::gcd( n, m );
80 }
81
82 template <typename IntType>
83 IntType lcm(IntType n, IntType m)
84 {
85     // Defer to the version in Boost.Math
86     return math::lcm( n, m );
87 }
88 #endif  // BOOST_CONTROL_RATIONAL_HAS_GCD
89
90 class bad_rational : public std::domain_error
91 {
92 public:
93     explicit bad_rational() : std::domain_error("bad rational: zero denominator") {}
94 };
95
96 template <typename IntType>
97 class rational;
98
99 template <typename IntType>
100 rational<IntType> abs(const rational<IntType>& r);
101
102 template <typename IntType>
103 class rational :
104     less_than_comparable < rational<IntType>,
105     equality_comparable < rational<IntType>,
106     less_than_comparable2 < rational<IntType>, IntType,
107     equality_comparable2 < rational<IntType>, IntType,
108     addable < rational<IntType>,
109     subtractable < rational<IntType>,
110     multipliable < rational<IntType>,
111     dividable < rational<IntType>,
112     addable2 < rational<IntType>, IntType,
113     subtractable2 < rational<IntType>, IntType,
114     subtractable2_left < rational<IntType>, IntType,
115     multipliable2 < rational<IntType>, IntType,
116     dividable2 < rational<IntType>, IntType,
117     dividable2_left < rational<IntType>, IntType,
118     incrementable < rational<IntType>,
119     decrementable < rational<IntType>
120     > > > > > > > > > > > > > > > >
121 {
122     // Class-wide pre-conditions
123     BOOST_STATIC_ASSERT( ::std::numeric_limits<IntType>::is_specialized );
124
125     // Helper types
126     typedef typename boost::call_traits<IntType>::param_type param_type;
127
128     struct helper { IntType parts[2]; };
129     typedef IntType (helper::* bool_type)[2];
130
131 public:
132     typedef IntType int_type;
133     rational() : num(0), den(1) {}
134     rational(param_type n) : num(n), den(1) {}
135     rational(param_type n, param_type d) : num(n), den(d) { normalize(); }
136
137     // Default copy constructor and assignment are fine
138
139     // Add assignment from IntType
140     rational& operator=(param_type n) { return assign(n, 1); }
141
142     // Assign in place
143     rational& assign(param_type n, param_type d);
144
145     // Access to representation
146     IntType numerator() const { return num; }
147     IntType denominator() const { return den; }
148
149     // Arithmetic assignment operators
150     rational& operator+= (const rational& r);
151     rational& operator-= (const rational& r);
152     rational& operator*= (const rational& r);
153     rational& operator/= (const rational& r);
154
155     rational& operator+= (param_type i);
156     rational& operator-= (param_type i);
157     rational& operator*= (param_type i);
158     rational& operator/= (param_type i);
159
160     // Increment and decrement
161     const rational& operator++();
162     const rational& operator--();
163
164     // Operator not
165     bool operator!() const { return !num; }
166
167     // Boolean conversion
168     
169 #if BOOST_WORKAROUND(__MWERKS__,<=0x3003)
170     // The "ISO C++ Template Parser" option in CW 8.3 chokes on the
171     // following, hence we selectively disable that option for the
172     // offending memfun.
173 #pragma parse_mfunc_templ off
174 #endif
175
176     operator bool_type() const { return operator !() ? 0 : &helper::parts; }
177
178 #if BOOST_WORKAROUND(__MWERKS__,<=0x3003)
179 #pragma parse_mfunc_templ reset
180 #endif
181
182     // Comparison operators
183     bool operator< (const rational& r) const;
184     bool operator== (const rational& r) const;
185
186     bool operator< (param_type i) const;
187     bool operator> (param_type i) const;
188     bool operator== (param_type i) const;
189
190 private:
191     // Implementation - numerator and denominator (normalized).
192     // Other possibilities - separate whole-part, or sign, fields?
193     IntType num;
194     IntType den;
195
196     // Representation note: Fractions are kept in normalized form at all
197     // times. normalized form is defined as gcd(num,den) == 1 and den > 0.
198     // In particular, note that the implementation of abs() below relies
199     // on den always being positive.
200     bool test_invariant() const;
201     void normalize();
202 };
203
204 // Assign in place
205 template <typename IntType>
206 inline rational<IntType>& rational<IntType>::assign(param_type n, param_type d)
207 {
208     num = n;
209     den = d;
210     normalize();
211     return *this;
212 }
213
214 // Unary plus and minus
215 template <typename IntType>
216 inline rational<IntType> operator+ (const rational<IntType>& r)
217 {
218     return r;
219 }
220
221 template <typename IntType>
222 inline rational<IntType> operator- (const rational<IntType>& r)
223 {
224     return rational<IntType>(-r.numerator(), r.denominator());
225 }
226
227 // Arithmetic assignment operators
228 template <typename IntType>
229 rational<IntType>& rational<IntType>::operator+= (const rational<IntType>& r)
230 {
231     // This calculation avoids overflow, and minimises the number of expensive
232     // calculations. Thanks to Nickolay Mladenov for this algorithm.
233     //
234     // Proof:
235     // We have to compute a/b + c/d, where gcd(a,b)=1 and gcd(b,c)=1.
236     // Let g = gcd(b,d), and b = b1*g, d=d1*g. Then gcd(b1,d1)=1
237     //
238     // The result is (a*d1 + c*b1) / (b1*d1*g).
239     // Now we have to normalize this ratio.
240     // Let's assume h | gcd((a*d1 + c*b1), (b1*d1*g)), and h > 1
241     // If h | b1 then gcd(h,d1)=1 and hence h|(a*d1+c*b1) => h|a.
242     // But since gcd(a,b1)=1 we have h=1.
243     // Similarly h|d1 leads to h=1.
244     // So we have that h | gcd((a*d1 + c*b1) , (b1*d1*g)) => h|g
245     // Finally we have gcd((a*d1 + c*b1), (b1*d1*g)) = gcd((a*d1 + c*b1), g)
246     // Which proves that instead of normalizing the result, it is better to
247     // divide num and den by gcd((a*d1 + c*b1), g)
248
249     // Protect against self-modification
250     IntType r_num = r.num;
251     IntType r_den = r.den;
252
253     IntType g = math::gcd(den, r_den);
254     den /= g;  // = b1 from the calculations above
255     num = num * (r_den / g) + r_num * den;
256     g = math::gcd(num, g);
257     num /= g;
258     den *= r_den/g;
259
260     return *this;
261 }
262
263 template <typename IntType>
264 rational<IntType>& rational<IntType>::operator-= (const rational<IntType>& r)
265 {
266     // Protect against self-modification
267     IntType r_num = r.num;
268     IntType r_den = r.den;
269
270     // This calculation avoids overflow, and minimises the number of expensive
271     // calculations. It corresponds exactly to the += case above
272     IntType g = math::gcd(den, r_den);
273     den /= g;
274     num = num * (r_den / g) - r_num * den;
275     g = math::gcd(num, g);
276     num /= g;
277     den *= r_den/g;
278
279     return *this;
280 }
281
282 template <typename IntType>
283 rational<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 overflow and preserve normalization
290     IntType gcd1 = math::gcd(num, r_den);
291     IntType gcd2 = math::gcd(r_num, den);
292     num = (num/gcd1) * (r_num/gcd2);
293     den = (den/gcd2) * (r_den/gcd1);
294     return *this;
295 }
296
297 template <typename IntType>
298 rational<IntType>& rational<IntType>::operator/= (const rational<IntType>& r)
299 {
300     // Protect against self-modification
301     IntType r_num = r.num;
302     IntType r_den = r.den;
303
304     // Avoid repeated construction
305     IntType zero(0);
306
307     // Trap division by zero
308     if (r_num == zero)
309         throw bad_rational();
310     if (num == zero)
311         return *this;
312
313     // Avoid overflow and preserve normalization
314     IntType gcd1 = math::gcd(num, r_num);
315     IntType gcd2 = math::gcd(r_den, den);
316     num = (num/gcd1) * (r_den/gcd2);
317     den = (den/gcd2) * (r_num/gcd1);
318
319     if (den < zero) {
320         num = -num;
321         den = -den;
322     }
323     return *this;
324 }
325
326 // Mixed-mode operators
327 template <typename IntType>
328 inline rational<IntType>&
329 rational<IntType>::operator+= (param_type i)
330 {
331     return operator+= (rational<IntType>(i));
332 }
333
334 template <typename IntType>
335 inline rational<IntType>&
336 rational<IntType>::operator-= (param_type i)
337 {
338     return operator-= (rational<IntType>(i));
339 }
340
341 template <typename IntType>
342 inline rational<IntType>&
343 rational<IntType>::operator*= (param_type i)
344 {
345     return operator*= (rational<IntType>(i));
346 }
347
348 template <typename IntType>
349 inline rational<IntType>&
350 rational<IntType>::operator/= (param_type i)
351 {
352     return operator/= (rational<IntType>(i));
353 }
354
355 // Increment and decrement
356 template <typename IntType>
357 inline const rational<IntType>& rational<IntType>::operator++()
358 {
359     // This can never denormalise the fraction
360     num += den;
361     return *this;
362 }
363
364 template <typename IntType>
365 inline const rational<IntType>& rational<IntType>::operator--()
366 {
367     // This can never denormalise the fraction
368     num -= den;
369     return *this;
370 }
371
372 // Comparison operators
373 template <typename IntType>
374 bool rational<IntType>::operator< (const rational<IntType>& r) const
375 {
376     // Avoid repeated construction
377     int_type const  zero( 0 );
378
379     // This should really be a class-wide invariant.  The reason for these
380     // checks is that for 2's complement systems, INT_MIN has no corresponding
381     // positive, so negating it during normalization keeps it INT_MIN, which
382     // is bad for later calculations that assume a positive denominator.
383     BOOST_ASSERT( this->den > zero );
384     BOOST_ASSERT( r.den > zero );
385
386     // Determine relative order by expanding each value to its simple continued
387     // fraction representation using the Euclidian GCD algorithm.
388     struct { int_type  n, d, q, r; }  ts = { this->num, this->den, this->num /
389      this->den, this->num % this->den }, rs = { r.num, r.den, r.num / r.den,
390      r.num % r.den };
391     unsigned  reverse = 0u;
392
393     // Normalize negative moduli by repeatedly adding the (positive) denominator
394     // and decrementing the quotient.  Later cycles should have all positive
395     // values, so this only has to be done for the first cycle.  (The rules of
396     // C++ require a nonnegative quotient & remainder for a nonnegative dividend
397     // & positive divisor.)
398     while ( ts.r < zero )  { ts.r += ts.d; --ts.q; }
399     while ( rs.r < zero )  { rs.r += rs.d; --rs.q; }
400
401     // Loop through and compare each variable's continued-fraction components
402     while ( true )
403     {
404         // The quotients of the current cycle are the continued-fraction
405         // components.  Comparing two c.f. is comparing their sequences,
406         // stopping at the first difference.
407         if ( ts.q != rs.q )
408         {
409             // Since reciprocation changes the relative order of two variables,
410             // and c.f. use reciprocals, the less/greater-than test reverses
411             // after each index.  (Start w/ non-reversed @ whole-number place.)
412             return reverse ? ts.q > rs.q : ts.q < rs.q;
413         }
414
415         // Prepare the next cycle
416         reverse ^= 1u;
417
418         if ( (ts.r == zero) || (rs.r == zero) )
419         {
420             // At least one variable's c.f. expansion has ended
421             break;
422         }
423
424         ts.n = ts.d;         ts.d = ts.r;
425         ts.q = ts.n / ts.d;  ts.r = ts.n % ts.d;
426         rs.n = rs.d;         rs.d = rs.r;
427         rs.q = rs.n / rs.d;  rs.r = rs.n % rs.d;
428     }
429
430     // Compare infinity-valued components for otherwise equal sequences
431     if ( ts.r == rs.r )
432     {
433         // Both remainders are zero, so the next (and subsequent) c.f.
434         // components for both sequences are infinity.  Therefore, the sequences
435         // and their corresponding values are equal.
436         return false;
437     }
438     else
439     {
440         // Exactly one of the remainders is zero, so all following c.f.
441         // components of that variable are infinity, while the other variable
442         // has a finite next c.f. component.  So that other variable has the
443         // lesser value (modulo the reversal flag!).
444         return ( ts.r != zero ) != static_cast<bool>( reverse );
445     }
446 }
447
448 template <typename IntType>
449 bool rational<IntType>::operator< (param_type i) const
450 {
451     // Avoid repeated construction
452     int_type const  zero( 0 );
453
454     // Break value into mixed-fraction form, w/ always-nonnegative remainder
455     BOOST_ASSERT( this->den > zero );
456     int_type  q = this->num / this->den, r = this->num % this->den;
457     while ( r < zero )  { r += this->den; --q; }
458
459     // Compare with just the quotient, since the remainder always bumps the
460     // value up.  [Since q = floor(n/d), and if n/d < i then q < i, if n/d == i
461     // then q == i, if n/d == i + r/d then q == i, and if n/d >= i + 1 then
462     // q >= i + 1 > i; therefore n/d < i iff q < i.]
463     return q < i;
464 }
465
466 template <typename IntType>
467 bool rational<IntType>::operator> (param_type i) const
468 {
469     // Trap equality first
470     if (num == i && den == IntType(1))
471         return false;
472
473     // Otherwise, we can use operator<
474     return !operator<(i);
475 }
476
477 template <typename IntType>
478 inline bool rational<IntType>::operator== (const rational<IntType>& r) const
479 {
480     return ((num == r.num) && (den == r.den));
481 }
482
483 template <typename IntType>
484 inline bool rational<IntType>::operator== (param_type i) const
485 {
486     return ((den == IntType(1)) && (num == i));
487 }
488
489 // Invariant check
490 template <typename IntType>
491 inline bool rational<IntType>::test_invariant() const
492 {
493     return ( this->den > int_type(0) ) && ( math::gcd(this->num, this->den) ==
494      int_type(1) );
495 }
496
497 // Normalisation
498 template <typename IntType>
499 void rational<IntType>::normalize()
500 {
501     // Avoid repeated construction
502     IntType zero(0);
503
504     if (den == zero)
505         throw bad_rational();
506
507     // Handle the case of zero separately, to avoid division by zero
508     if (num == zero) {
509         den = IntType(1);
510         return;
511     }
512
513     IntType g = math::gcd(num, den);
514
515     num /= g;
516     den /= g;
517
518     // Ensure that the denominator is positive
519     if (den < zero) {
520         num = -num;
521         den = -den;
522     }
523
524     BOOST_ASSERT( this->test_invariant() );
525 }
526
527 namespace detail {
528
529     // A utility class to reset the format flags for an istream at end
530     // of scope, even in case of exceptions
531     struct resetter {
532         resetter(std::istream& is) : is_(is), f_(is.flags()) {}
533         ~resetter() { is_.flags(f_); }
534         std::istream& is_;
535         std::istream::fmtflags f_;      // old GNU c++ lib has no ios_base
536     };
537
538 }
539
540 // Input and output
541 template <typename IntType>
542 std::istream& operator>> (std::istream& is, rational<IntType>& r)
543 {
544     IntType n = IntType(0), d = IntType(1);
545     char c = 0;
546     detail::resetter sentry(is);
547
548     is >> n;
549     c = is.get();
550
551     if (c != '/')
552         is.clear(std::istream::badbit);  // old GNU c++ lib has no ios_base
553
554 #if !defined(__GNUC__) || (defined(__GNUC__) && (__GNUC__ >= 3)) || defined __SGI_STL_PORT
555     is >> std::noskipws;
556 #else
557     is.unsetf(ios::skipws); // compiles, but seems to have no effect.
558 #endif
559     is >> d;
560
561     if (is)
562         r.assign(n, d);
563
564     return is;
565 }
566
567 // Add manipulators for output format?
568 template <typename IntType>
569 std::ostream& operator<< (std::ostream& os, const rational<IntType>& r)
570 {
571     os << r.numerator() << '/' << r.denominator();
572     return os;
573 }
574
575 // Type conversion
576 template <typename T, typename IntType>
577 inline T rational_cast(
578     const rational<IntType>& src BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE(T))
579 {
580     return static_cast<T>(src.numerator())/static_cast<T>(src.denominator());
581 }
582
583 // Do not use any abs() defined on IntType - it isn't worth it, given the
584 // difficulties involved (Koenig lookup required, there may not *be* an abs()
585 // defined, etc etc).
586 template <typename IntType>
587 inline rational<IntType> abs(const rational<IntType>& r)
588 {
589     if (r.numerator() >= IntType(0))
590         return r;
591
592     return rational<IntType>(-r.numerator(), r.denominator());
593 }
594
595 } // namespace boost
596
597 #endif  // BOOST_RATIONAL_HPP
598