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