]> git.lyx.org Git - lyx.git/blob - boost/boost/rational.hpp
Update in-tree boost to latest from boost 1.34 cvs.
[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 //  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)
39
40 #ifndef BOOST_RATIONAL_HPP
41 #define BOOST_RATIONAL_HPP
42
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
51
52 namespace boost {
53
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)
58 {
59     // Avoid repeated construction
60     IntType zero(0);
61
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).
65     if (n < zero)
66         n = -n;
67     if (m < zero)
68         m = -m;
69
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).
73     for(;;) {
74       if(m == zero)
75         return n;
76       n %= m;
77       if(n == zero)
78         return m;
79       m %= n;
80     }
81 }
82
83 template <typename IntType>
84 IntType lcm(IntType n, IntType m)
85 {
86     // Avoid repeated construction
87     IntType zero(0);
88
89     if (n == zero || m == zero)
90         return zero;
91
92     n /= gcd(n, m);
93     n *= m;
94
95     if (n < zero)
96         n = -n;
97     return n;
98 }
99
100 class bad_rational : public std::domain_error
101 {
102 public:
103     explicit bad_rational() : std::domain_error("bad rational: zero denominator") {}
104 };
105
106 template <typename IntType>
107 class rational;
108
109 template <typename IntType>
110 rational<IntType> abs(const rational<IntType>& r);
111
112 template <typename IntType>
113 class rational :
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     > > > > > > > > > > > > > > > >
131 {
132     typedef typename boost::call_traits<IntType>::param_type param_type;
133
134     struct helper { IntType parts[2]; };
135     typedef IntType (helper::* bool_type)[2];
136
137 public:
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(); }
142
143     // Default copy constructor and assignment are fine
144
145     // Add assignment from IntType
146     rational& operator=(param_type n) { return assign(n, 1); }
147
148     // Assign in place
149     rational& assign(param_type n, param_type d);
150
151     // Access to representation
152     IntType numerator() const { return num; }
153     IntType denominator() const { return den; }
154
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);
160
161     rational& operator+= (param_type i);
162     rational& operator-= (param_type i);
163     rational& operator*= (param_type i);
164     rational& operator/= (param_type i);
165
166     // Increment and decrement
167     const rational& operator++();
168     const rational& operator--();
169
170     // Operator not
171     bool operator!() const { return !num; }
172
173     // Boolean conversion
174     operator bool_type() const { return operator !() ? 0 : &helper::parts; }
175
176     // Comparison operators
177     bool operator< (const rational& r) const;
178     bool operator== (const rational& r) const;
179
180     bool operator< (param_type i) const;
181     bool operator> (param_type i) const;
182     bool operator== (param_type i) const;
183
184 private:
185     // Implementation - numerator and denominator (normalized).
186     // Other possibilities - separate whole-part, or sign, fields?
187     IntType num;
188     IntType den;
189
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.
194     void normalize();
195 };
196
197 // Assign in place
198 template <typename IntType>
199 inline rational<IntType>& rational<IntType>::assign(param_type n, param_type d)
200 {
201     num = n;
202     den = d;
203     normalize();
204     return *this;
205 }
206
207 // Unary plus and minus
208 template <typename IntType>
209 inline rational<IntType> operator+ (const rational<IntType>& r)
210 {
211     return r;
212 }
213
214 template <typename IntType>
215 inline rational<IntType> operator- (const rational<IntType>& r)
216 {
217     return rational<IntType>(-r.numerator(), r.denominator());
218 }
219
220 // Arithmetic assignment operators
221 template <typename IntType>
222 rational<IntType>& rational<IntType>::operator+= (const rational<IntType>& r)
223 {
224     // This calculation avoids overflow, and minimises the number of expensive
225     // calculations. Thanks to Nickolay Mladenov for this algorithm.
226     //
227     // Proof:
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
230     //
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)
241
242     // Protect against self-modification
243     IntType r_num = r.num;
244     IntType r_den = r.den;
245
246     IntType g = gcd(den, r_den);
247     den /= g;  // = b1 from the calculations above
248     num = num * (r_den / g) + r_num * den;
249     g = gcd(num, g);
250     num /= g;
251     den *= r_den/g;
252
253     return *this;
254 }
255
256 template <typename IntType>
257 rational<IntType>& rational<IntType>::operator-= (const rational<IntType>& r)
258 {
259     // Protect against self-modification
260     IntType r_num = r.num;
261     IntType r_den = r.den;
262
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);
266     den /= g;
267     num = num * (r_den / g) - r_num * den;
268     g = gcd(num, g);
269     num /= g;
270     den *= r_den/g;
271
272     return *this;
273 }
274
275 template <typename IntType>
276 rational<IntType>& rational<IntType>::operator*= (const rational<IntType>& r)
277 {
278     // Protect against self-modification
279     IntType r_num = r.num;
280     IntType r_den = r.den;
281
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);
287     return *this;
288 }
289
290 template <typename IntType>
291 rational<IntType>& rational<IntType>::operator/= (const rational<IntType>& r)
292 {
293     // Protect against self-modification
294     IntType r_num = r.num;
295     IntType r_den = r.den;
296
297     // Avoid repeated construction
298     IntType zero(0);
299
300     // Trap division by zero
301     if (r_num == zero)
302         throw bad_rational();
303     if (num == zero)
304         return *this;
305
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);
311
312     if (den < zero) {
313         num = -num;
314         den = -den;
315     }
316     return *this;
317 }
318
319 // Mixed-mode operators
320 template <typename IntType>
321 inline rational<IntType>&
322 rational<IntType>::operator+= (param_type i)
323 {
324     return operator+= (rational<IntType>(i));
325 }
326
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 // Increment and decrement
349 template <typename IntType>
350 inline const rational<IntType>& rational<IntType>::operator++()
351 {
352     // This can never denormalise the fraction
353     num += den;
354     return *this;
355 }
356
357 template <typename IntType>
358 inline const rational<IntType>& rational<IntType>::operator--()
359 {
360     // This can never denormalise the fraction
361     num -= den;
362     return *this;
363 }
364
365 // Comparison operators
366 template <typename IntType>
367 bool rational<IntType>::operator< (const rational<IntType>& r) const
368 {
369     // Avoid repeated construction
370     IntType zero(0);
371
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
376         return true;
377     if (num >= zero && r.num <= zero) // +ve or zero is not < -ve or zero
378         return false;
379
380     // Avoid overflow
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);
384 }
385
386 template <typename IntType>
387 bool rational<IntType>::operator< (param_type i) const
388 {
389     // Avoid repeated construction
390     IntType zero(0);
391
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
396         return true;
397     if (num >= zero && i <= zero) // +ve or zero is not < -ve or zero
398         return false;
399
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...
404     if (num > zero)
405         return (num/den) < i;
406     else
407         return -i < (-num/den);
408 }
409
410 template <typename IntType>
411 bool rational<IntType>::operator> (param_type i) const
412 {
413     // Trap equality first
414     if (num == i && den == IntType(1))
415         return false;
416
417     // Otherwise, we can use operator<
418     return !operator<(i);
419 }
420
421 template <typename IntType>
422 inline bool rational<IntType>::operator== (const rational<IntType>& r) const
423 {
424     return ((num == r.num) && (den == r.den));
425 }
426
427 template <typename IntType>
428 inline bool rational<IntType>::operator== (param_type i) const
429 {
430     return ((den == IntType(1)) && (num == i));
431 }
432
433 // Normalisation
434 template <typename IntType>
435 void rational<IntType>::normalize()
436 {
437     // Avoid repeated construction
438     IntType zero(0);
439
440     if (den == zero)
441         throw bad_rational();
442
443     // Handle the case of zero separately, to avoid division by zero
444     if (num == zero) {
445         den = IntType(1);
446         return;
447     }
448
449     IntType g = gcd<IntType>(num, den);
450
451     num /= g;
452     den /= g;
453
454     // Ensure that the denominator is positive
455     if (den < zero) {
456         num = -num;
457         den = -den;
458     }
459 }
460
461 namespace detail {
462
463     // A utility class to reset the format flags for an istream at end
464     // of scope, even in case of exceptions
465     struct resetter {
466         resetter(std::istream& is) : is_(is), f_(is.flags()) {}
467         ~resetter() { is_.flags(f_); }
468         std::istream& is_;
469         std::istream::fmtflags f_;      // old GNU c++ lib has no ios_base
470     };
471
472 }
473
474 // Input and output
475 template <typename IntType>
476 std::istream& operator>> (std::istream& is, rational<IntType>& r)
477 {
478     IntType n = IntType(0), d = IntType(1);
479     char c = 0;
480     detail::resetter sentry(is);
481
482     is >> n;
483     c = is.get();
484
485     if (c != '/')
486         is.clear(std::istream::badbit);  // old GNU c++ lib has no ios_base
487
488 #if !defined(__GNUC__) || (defined(__GNUC__) && (__GNUC__ >= 3)) || defined __SGI_STL_PORT
489     is >> std::noskipws;
490 #else
491     is.unsetf(ios::skipws); // compiles, but seems to have no effect.
492 #endif
493     is >> d;
494
495     if (is)
496         r.assign(n, d);
497
498     return is;
499 }
500
501 // Add manipulators for output format?
502 template <typename IntType>
503 std::ostream& operator<< (std::ostream& os, const rational<IntType>& r)
504 {
505     os << r.numerator() << '/' << r.denominator();
506     return os;
507 }
508
509 // Type conversion
510 template <typename T, typename IntType>
511 inline T rational_cast(const rational<IntType>& src)
512 {
513     return static_cast<T>(src.numerator())/src.denominator();
514 }
515
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)
521 {
522     if (r.numerator() >= IntType(0))
523         return r;
524
525     return rational<IntType>(-r.numerator(), r.denominator());
526 }
527
528 } // namespace boost
529
530 #endif  // BOOST_RATIONAL_HPP
531