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