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