]>
Commit | Line | Data |
---|---|---|
7c673cae FG |
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 | // 02 Sep 13 Remove unneeded forward declarations; tweak private helper | |
25 | // function (Daryle Walker) | |
26 | // 30 Aug 13 Improve exception safety of "assign"; start modernizing I/O code | |
27 | // (Daryle Walker) | |
28 | // 27 Aug 13 Add cross-version constructor template, plus some private helper | |
29 | // functions; add constructor to exception class to take custom | |
30 | // messages (Daryle Walker) | |
31 | // 25 Aug 13 Add constexpr qualification wherever possible (Daryle Walker) | |
32 | // 05 May 12 Reduced use of implicit gcd (Mario Lang) | |
33 | // 05 Nov 06 Change rational_cast to not depend on division between different | |
34 | // types (Daryle Walker) | |
b32b8144 | 35 | // 04 Nov 06 Off-load GCD and LCM to Boost.Integer; add some invariant checks; |
7c673cae FG |
36 | // add std::numeric_limits<> requirement to help GCD (Daryle Walker) |
37 | // 31 Oct 06 Recoded both operator< to use round-to-negative-infinity | |
38 | // divisions; the rational-value version now uses continued fraction | |
39 | // expansion to avoid overflows, for bug #798357 (Daryle Walker) | |
40 | // 20 Oct 06 Fix operator bool_type for CW 8.3 (Joaquín M López Muñoz) | |
41 | // 18 Oct 06 Use EXPLICIT_TEMPLATE_TYPE helper macros from Boost.Config | |
42 | // (Joaquín M López Muñoz) | |
43 | // 27 Dec 05 Add Boolean conversion operator (Daryle Walker) | |
44 | // 28 Sep 02 Use _left versions of operators from operators.hpp | |
45 | // 05 Jul 01 Recode gcd(), avoiding std::swap (Helmut Zeisel) | |
46 | // 03 Mar 01 Workarounds for Intel C++ 5.0 (David Abrahams) | |
47 | // 05 Feb 01 Update operator>> to tighten up input syntax | |
48 | // 05 Feb 01 Final tidy up of gcd code prior to the new release | |
49 | // 27 Jan 01 Recode abs() without relying on abs(IntType) | |
50 | // 21 Jan 01 Include Nickolay Mladenov's operator+= algorithm, | |
51 | // tidy up a number of areas, use newer features of operators.hpp | |
52 | // (reduces space overhead to zero), add operator!, | |
53 | // introduce explicit mixed-mode arithmetic operations | |
54 | // 12 Jan 01 Include fixes to handle a user-defined IntType better | |
55 | // 19 Nov 00 Throw on divide by zero in operator /= (John (EBo) David) | |
56 | // 23 Jun 00 Incorporate changes from Mark Rodgers for Borland C++ | |
57 | // 22 Jun 00 Change _MSC_VER to BOOST_MSVC so other compilers are not | |
58 | // affected (Beman Dawes) | |
59 | // 6 Mar 00 Fix operator-= normalization, #include <string> (Jens Maurer) | |
60 | // 14 Dec 99 Modifications based on comments from the boost list | |
61 | // 09 Dec 99 Initial Version (Paul Moore) | |
62 | ||
63 | #ifndef BOOST_RATIONAL_HPP | |
64 | #define BOOST_RATIONAL_HPP | |
65 | ||
66 | #include <boost/config.hpp> // for BOOST_NO_STDC_NAMESPACE, BOOST_MSVC, etc | |
67 | #ifndef BOOST_NO_IOSTREAM | |
68 | #include <iomanip> // for std::setw | |
69 | #include <ios> // for std::noskipws, streamsize | |
70 | #include <istream> // for std::istream | |
71 | #include <ostream> // for std::ostream | |
72 | #include <sstream> // for std::ostringstream | |
73 | #endif | |
74 | #include <cstddef> // for NULL | |
75 | #include <stdexcept> // for std::domain_error | |
76 | #include <string> // for std::string implicit constructor | |
77 | #include <boost/operators.hpp> // for boost::addable etc | |
78 | #include <cstdlib> // for std::abs | |
79 | #include <boost/call_traits.hpp> // for boost::call_traits | |
80 | #include <boost/detail/workaround.hpp> // for BOOST_WORKAROUND | |
81 | #include <boost/assert.hpp> // for BOOST_ASSERT | |
82 | #include <boost/integer/common_factor_rt.hpp> // for boost::integer::gcd, lcm | |
83 | #include <limits> // for std::numeric_limits | |
84 | #include <boost/static_assert.hpp> // for BOOST_STATIC_ASSERT | |
85 | #include <boost/throw_exception.hpp> | |
b32b8144 FG |
86 | #include <boost/utility/enable_if.hpp> |
87 | #include <boost/type_traits/is_convertible.hpp> | |
88 | #include <boost/type_traits/is_class.hpp> | |
89 | #include <boost/type_traits/is_same.hpp> | |
7c673cae FG |
90 | |
91 | // Control whether depreciated GCD and LCM functions are included (default: yes) | |
92 | #ifndef BOOST_CONTROL_RATIONAL_HAS_GCD | |
93 | #define BOOST_CONTROL_RATIONAL_HAS_GCD 1 | |
94 | #endif | |
95 | ||
96 | namespace boost { | |
97 | ||
98 | #if BOOST_CONTROL_RATIONAL_HAS_GCD | |
99 | template <typename IntType> | |
100 | IntType gcd(IntType n, IntType m) | |
101 | { | |
b32b8144 | 102 | // Defer to the version in Boost.Integer |
7c673cae FG |
103 | return integer::gcd( n, m ); |
104 | } | |
105 | ||
106 | template <typename IntType> | |
107 | IntType lcm(IntType n, IntType m) | |
108 | { | |
b32b8144 | 109 | // Defer to the version in Boost.Integer |
7c673cae FG |
110 | return integer::lcm( n, m ); |
111 | } | |
112 | #endif // BOOST_CONTROL_RATIONAL_HAS_GCD | |
113 | ||
b32b8144 FG |
114 | namespace rational_detail{ |
115 | ||
116 | template <class FromInt, class ToInt> | |
117 | struct is_compatible_integer | |
118 | { | |
119 | BOOST_STATIC_CONSTANT(bool, value = ((std::numeric_limits<FromInt>::is_specialized && std::numeric_limits<FromInt>::is_integer | |
120 | && (std::numeric_limits<FromInt>::digits <= std::numeric_limits<ToInt>::digits) | |
121 | && (std::numeric_limits<FromInt>::radix == std::numeric_limits<ToInt>::radix) | |
122 | && ((std::numeric_limits<FromInt>::is_signed == false) || (std::numeric_limits<ToInt>::is_signed == true)) | |
123 | && is_convertible<FromInt, ToInt>::value) | |
124 | || is_same<FromInt, ToInt>::value) | |
125 | || (is_class<ToInt>::value && is_class<FromInt>::value && is_convertible<FromInt, ToInt>::value)); | |
126 | }; | |
127 | ||
128 | } | |
129 | ||
7c673cae FG |
130 | class bad_rational : public std::domain_error |
131 | { | |
132 | public: | |
133 | explicit bad_rational() : std::domain_error("bad rational: zero denominator") {} | |
134 | explicit bad_rational( char const *what ) : std::domain_error( what ) {} | |
135 | }; | |
136 | ||
137 | template <typename IntType> | |
b32b8144 | 138 | class rational |
7c673cae FG |
139 | { |
140 | // Class-wide pre-conditions | |
141 | BOOST_STATIC_ASSERT( ::std::numeric_limits<IntType>::is_specialized ); | |
142 | ||
143 | // Helper types | |
144 | typedef typename boost::call_traits<IntType>::param_type param_type; | |
145 | ||
146 | struct helper { IntType parts[2]; }; | |
147 | typedef IntType (helper::* bool_type)[2]; | |
148 | ||
149 | public: | |
150 | // Component type | |
151 | typedef IntType int_type; | |
152 | ||
153 | BOOST_CONSTEXPR | |
154 | rational() : num(0), den(1) {} | |
b32b8144 FG |
155 | template <class T> |
156 | BOOST_CONSTEXPR rational(const T& n, typename enable_if_c< | |
157 | rational_detail::is_compatible_integer<T, IntType>::value | |
158 | >::type const* = 0) : num(n), den(1) {} | |
159 | template <class T, class U> | |
160 | rational(const T& n, const U& d, typename enable_if_c< | |
161 | rational_detail::is_compatible_integer<T, IntType>::value && rational_detail::is_compatible_integer<U, IntType>::value | |
162 | >::type const* = 0) : num(n), den(d) { | |
163 | normalize(); | |
164 | } | |
7c673cae | 165 | |
7c673cae FG |
166 | template < typename NewType > |
167 | BOOST_CONSTEXPR explicit | |
b32b8144 | 168 | rational(rational<NewType> const &r, typename enable_if_c<rational_detail::is_compatible_integer<NewType, IntType>::value>::type const* = 0) |
7c673cae FG |
169 | : num(r.numerator()), den(is_normalized(int_type(r.numerator()), |
170 | int_type(r.denominator())) ? r.denominator() : | |
171 | (BOOST_THROW_EXCEPTION(bad_rational("bad rational: denormalized conversion")), 0)){} | |
7c673cae | 172 | |
b32b8144 FG |
173 | template < typename NewType > |
174 | BOOST_CONSTEXPR explicit | |
175 | rational(rational<NewType> const &r, typename disable_if_c<rational_detail::is_compatible_integer<NewType, IntType>::value>::type const* = 0) | |
176 | : num(r.numerator()), den(is_normalized(int_type(r.numerator()), | |
177 | int_type(r.denominator())) && is_safe_narrowing_conversion(r.denominator()) && is_safe_narrowing_conversion(r.numerator()) ? r.denominator() : | |
178 | (BOOST_THROW_EXCEPTION(bad_rational("bad rational: denormalized conversion")), 0)){} | |
7c673cae FG |
179 | // Default copy constructor and assignment are fine |
180 | ||
181 | // Add assignment from IntType | |
b32b8144 FG |
182 | template <class T> |
183 | typename enable_if_c< | |
184 | rational_detail::is_compatible_integer<T, IntType>::value, rational & | |
185 | >::type operator=(const T& n) { return assign(static_cast<IntType>(n), static_cast<IntType>(1)); } | |
7c673cae FG |
186 | |
187 | // Assign in place | |
b32b8144 FG |
188 | template <class T, class U> |
189 | typename enable_if_c< | |
190 | rational_detail::is_compatible_integer<T, IntType>::value && rational_detail::is_compatible_integer<U, IntType>::value, rational & | |
191 | >::type assign(const T& n, const U& d) | |
192 | { | |
193 | return *this = rational<IntType>(static_cast<IntType>(n), static_cast<IntType>(d)); | |
194 | } | |
195 | // | |
196 | // The following overloads should probably *not* be provided - | |
197 | // but are provided for backwards compatibity reasons only. | |
198 | // These allow for construction/assignment from types that | |
199 | // are wider than IntType only if there is an implicit | |
200 | // conversion from T to IntType, they will throw a bad_rational | |
201 | // if the conversion results in loss of precision or undefined behaviour. | |
202 | // | |
203 | template <class T> | |
204 | rational(const T& n, typename enable_if_c< | |
205 | std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer | |
206 | && !rational_detail::is_compatible_integer<T, IntType>::value | |
207 | && (std::numeric_limits<T>::radix == std::numeric_limits<IntType>::radix) | |
208 | && is_convertible<T, IntType>::value | |
209 | >::type const* = 0) | |
210 | { | |
211 | assign(n, static_cast<T>(1)); | |
212 | } | |
213 | template <class T, class U> | |
214 | rational(const T& n, const U& d, typename enable_if_c< | |
215 | (!rational_detail::is_compatible_integer<T, IntType>::value | |
216 | || !rational_detail::is_compatible_integer<U, IntType>::value) | |
217 | && std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer | |
218 | && (std::numeric_limits<T>::radix == std::numeric_limits<IntType>::radix) | |
219 | && is_convertible<T, IntType>::value && | |
220 | std::numeric_limits<U>::is_specialized && std::numeric_limits<U>::is_integer | |
221 | && (std::numeric_limits<U>::radix == std::numeric_limits<IntType>::radix) | |
222 | && is_convertible<U, IntType>::value | |
223 | >::type const* = 0) | |
224 | { | |
225 | assign(n, d); | |
226 | } | |
227 | template <class T> | |
228 | typename enable_if_c< | |
229 | std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer | |
230 | && !rational_detail::is_compatible_integer<T, IntType>::value | |
231 | && (std::numeric_limits<T>::radix == std::numeric_limits<IntType>::radix) | |
232 | && is_convertible<T, IntType>::value, | |
233 | rational & | |
234 | >::type operator=(const T& n) { return assign(n, static_cast<T>(1)); } | |
235 | ||
236 | template <class T, class U> | |
237 | typename enable_if_c< | |
238 | (!rational_detail::is_compatible_integer<T, IntType>::value | |
239 | || !rational_detail::is_compatible_integer<U, IntType>::value) | |
240 | && std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer | |
241 | && (std::numeric_limits<T>::radix == std::numeric_limits<IntType>::radix) | |
242 | && is_convertible<T, IntType>::value && | |
243 | std::numeric_limits<U>::is_specialized && std::numeric_limits<U>::is_integer | |
244 | && (std::numeric_limits<U>::radix == std::numeric_limits<IntType>::radix) | |
245 | && is_convertible<U, IntType>::value, | |
246 | rational & | |
247 | >::type assign(const T& n, const U& d) | |
248 | { | |
249 | if(!is_safe_narrowing_conversion(n) || !is_safe_narrowing_conversion(d)) | |
250 | BOOST_THROW_EXCEPTION(bad_rational()); | |
251 | return *this = rational<IntType>(static_cast<IntType>(n), static_cast<IntType>(d)); | |
252 | } | |
7c673cae FG |
253 | |
254 | // Access to representation | |
255 | BOOST_CONSTEXPR | |
256 | const IntType& numerator() const { return num; } | |
257 | BOOST_CONSTEXPR | |
258 | const IntType& denominator() const { return den; } | |
259 | ||
260 | // Arithmetic assignment operators | |
261 | rational& operator+= (const rational& r); | |
262 | rational& operator-= (const rational& r); | |
263 | rational& operator*= (const rational& r); | |
264 | rational& operator/= (const rational& r); | |
265 | ||
b32b8144 FG |
266 | template <class T> |
267 | typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, rational&>::type operator+= (const T& i) | |
268 | { | |
269 | num += i * den; | |
270 | return *this; | |
271 | } | |
272 | template <class T> | |
273 | typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, rational&>::type operator-= (const T& i) | |
274 | { | |
275 | num -= i * den; | |
276 | return *this; | |
277 | } | |
278 | template <class T> | |
279 | typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, rational&>::type operator*= (const T& i) | |
280 | { | |
281 | // Avoid overflow and preserve normalization | |
282 | IntType gcd = integer::gcd(static_cast<IntType>(i), den); | |
283 | num *= i / gcd; | |
284 | den /= gcd; | |
285 | return *this; | |
286 | } | |
287 | template <class T> | |
288 | typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, rational&>::type operator/= (const T& i) | |
289 | { | |
290 | // Avoid repeated construction | |
291 | IntType const zero(0); | |
292 | ||
293 | if(i == zero) BOOST_THROW_EXCEPTION(bad_rational()); | |
294 | if(num == zero) return *this; | |
295 | ||
296 | // Avoid overflow and preserve normalization | |
297 | IntType const gcd = integer::gcd(num, static_cast<IntType>(i)); | |
298 | num /= gcd; | |
299 | den *= i / gcd; | |
300 | ||
301 | if(den < zero) { | |
302 | num = -num; | |
303 | den = -den; | |
304 | } | |
305 | ||
306 | return *this; | |
307 | } | |
7c673cae FG |
308 | |
309 | // Increment and decrement | |
310 | const rational& operator++() { num += den; return *this; } | |
311 | const rational& operator--() { num -= den; return *this; } | |
312 | ||
b32b8144 FG |
313 | rational operator++(int) |
314 | { | |
315 | rational t(*this); | |
316 | ++(*this); | |
317 | return t; | |
318 | } | |
319 | rational operator--(int) | |
320 | { | |
321 | rational t(*this); | |
322 | --(*this); | |
323 | return t; | |
324 | } | |
325 | ||
7c673cae FG |
326 | // Operator not |
327 | BOOST_CONSTEXPR | |
328 | bool operator!() const { return !num; } | |
329 | ||
330 | // Boolean conversion | |
331 | ||
332 | #if BOOST_WORKAROUND(__MWERKS__,<=0x3003) | |
333 | // The "ISO C++ Template Parser" option in CW 8.3 chokes on the | |
334 | // following, hence we selectively disable that option for the | |
335 | // offending memfun. | |
336 | #pragma parse_mfunc_templ off | |
337 | #endif | |
338 | ||
339 | BOOST_CONSTEXPR | |
340 | operator bool_type() const { return operator !() ? 0 : &helper::parts; } | |
341 | ||
342 | #if BOOST_WORKAROUND(__MWERKS__,<=0x3003) | |
343 | #pragma parse_mfunc_templ reset | |
344 | #endif | |
345 | ||
346 | // Comparison operators | |
347 | bool operator< (const rational& r) const; | |
b32b8144 | 348 | bool operator> (const rational& r) const { return r < *this; } |
7c673cae FG |
349 | BOOST_CONSTEXPR |
350 | bool operator== (const rational& r) const; | |
351 | ||
b32b8144 FG |
352 | template <class T> |
353 | typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, bool>::type operator< (const T& i) const | |
354 | { | |
355 | // Avoid repeated construction | |
356 | int_type const zero(0); | |
357 | ||
358 | // Break value into mixed-fraction form, w/ always-nonnegative remainder | |
359 | BOOST_ASSERT(this->den > zero); | |
360 | int_type q = this->num / this->den, r = this->num % this->den; | |
361 | while(r < zero) { r += this->den; --q; } | |
362 | ||
363 | // Compare with just the quotient, since the remainder always bumps the | |
364 | // value up. [Since q = floor(n/d), and if n/d < i then q < i, if n/d == i | |
365 | // then q == i, if n/d == i + r/d then q == i, and if n/d >= i + 1 then | |
366 | // q >= i + 1 > i; therefore n/d < i iff q < i.] | |
367 | return q < i; | |
368 | } | |
369 | template <class T> | |
370 | typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, bool>::type operator>(const T& i) const | |
371 | { | |
372 | return operator==(i) ? false : !operator<(i); | |
373 | } | |
374 | template <class T> | |
375 | BOOST_CONSTEXPR typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, bool>::type operator== (const T& i) const | |
376 | { | |
377 | return ((den == IntType(1)) && (num == i)); | |
378 | } | |
7c673cae FG |
379 | |
380 | private: | |
381 | // Implementation - numerator and denominator (normalized). | |
382 | // Other possibilities - separate whole-part, or sign, fields? | |
383 | IntType num; | |
384 | IntType den; | |
385 | ||
386 | // Helper functions | |
387 | static BOOST_CONSTEXPR | |
388 | int_type inner_gcd( param_type a, param_type b, int_type const &zero = | |
389 | int_type(0) ) | |
390 | { return b == zero ? a : inner_gcd(b, a % b, zero); } | |
391 | ||
392 | static BOOST_CONSTEXPR | |
393 | int_type inner_abs( param_type x, int_type const &zero = int_type(0) ) | |
394 | { return x < zero ? -x : +x; } | |
395 | ||
396 | // Representation note: Fractions are kept in normalized form at all | |
397 | // times. normalized form is defined as gcd(num,den) == 1 and den > 0. | |
398 | // In particular, note that the implementation of abs() below relies | |
399 | // on den always being positive. | |
400 | bool test_invariant() const; | |
401 | void normalize(); | |
402 | ||
403 | static BOOST_CONSTEXPR | |
404 | bool is_normalized( param_type n, param_type d, int_type const &zero = | |
405 | int_type(0), int_type const &one = int_type(1) ) | |
406 | { | |
407 | return d > zero && ( n != zero || d == one ) && inner_abs( inner_gcd(n, | |
408 | d, zero), zero ) == one; | |
409 | } | |
b32b8144 FG |
410 | // |
411 | // Conversion checks: | |
412 | // | |
413 | // (1) From an unsigned type with more digits than IntType: | |
414 | // | |
415 | template <class T> | |
416 | BOOST_CONSTEXPR static typename boost::enable_if_c<(std::numeric_limits<T>::digits > std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == false), bool>::type is_safe_narrowing_conversion(const T& val) | |
417 | { | |
418 | return val < (T(1) << std::numeric_limits<IntType>::digits); | |
419 | } | |
420 | // | |
421 | // (2) From a signed type with more digits than IntType, and IntType also signed: | |
422 | // | |
423 | template <class T> | |
424 | BOOST_CONSTEXPR static typename boost::enable_if_c<(std::numeric_limits<T>::digits > std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == true) && (std::numeric_limits<IntType>::is_signed == true), bool>::type is_safe_narrowing_conversion(const T& val) | |
425 | { | |
426 | // Note that this check assumes IntType has a 2's complement representation, | |
427 | // we don't want to try to convert a std::numeric_limits<IntType>::min() to | |
428 | // a T because that conversion may not be allowed (this happens when IntType | |
429 | // is from Boost.Multiprecision). | |
430 | return (val < (T(1) << std::numeric_limits<IntType>::digits)) && (val >= -(T(1) << std::numeric_limits<IntType>::digits)); | |
431 | } | |
432 | // | |
433 | // (3) From a signed type with more digits than IntType, and IntType unsigned: | |
434 | // | |
435 | template <class T> | |
436 | BOOST_CONSTEXPR static typename boost::enable_if_c<(std::numeric_limits<T>::digits > std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == true) && (std::numeric_limits<IntType>::is_signed == false), bool>::type is_safe_narrowing_conversion(const T& val) | |
437 | { | |
438 | return (val < (T(1) << std::numeric_limits<IntType>::digits)) && (val >= 0); | |
439 | } | |
440 | // | |
441 | // (4) From a signed type with fewer digits than IntType, and IntType unsigned: | |
442 | // | |
443 | template <class T> | |
444 | BOOST_CONSTEXPR static typename boost::enable_if_c<(std::numeric_limits<T>::digits <= std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == true) && (std::numeric_limits<IntType>::is_signed == false), bool>::type is_safe_narrowing_conversion(const T& val) | |
445 | { | |
446 | return val >= 0; | |
447 | } | |
448 | // | |
449 | // (5) From an unsigned type with fewer digits than IntType, and IntType signed: | |
450 | // | |
451 | template <class T> | |
452 | BOOST_CONSTEXPR static typename boost::enable_if_c<(std::numeric_limits<T>::digits <= std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == false) && (std::numeric_limits<IntType>::is_signed == true), bool>::type is_safe_narrowing_conversion(const T&) | |
453 | { | |
454 | return true; | |
455 | } | |
456 | // | |
457 | // (6) From an unsigned type with fewer digits than IntType, and IntType unsigned: | |
458 | // | |
459 | template <class T> | |
460 | BOOST_CONSTEXPR static typename boost::enable_if_c<(std::numeric_limits<T>::digits <= std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == false) && (std::numeric_limits<IntType>::is_signed == false), bool>::type is_safe_narrowing_conversion(const T&) | |
461 | { | |
462 | return true; | |
463 | } | |
464 | // | |
465 | // (7) From an signed type with fewer digits than IntType, and IntType signed: | |
466 | // | |
467 | template <class T> | |
468 | BOOST_CONSTEXPR static typename boost::enable_if_c<(std::numeric_limits<T>::digits <= std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == true) && (std::numeric_limits<IntType>::is_signed == true), bool>::type is_safe_narrowing_conversion(const T&) | |
469 | { | |
470 | return true; | |
471 | } | |
7c673cae FG |
472 | }; |
473 | ||
7c673cae FG |
474 | // Unary plus and minus |
475 | template <typename IntType> | |
476 | BOOST_CONSTEXPR | |
477 | inline rational<IntType> operator+ (const rational<IntType>& r) | |
478 | { | |
479 | return r; | |
480 | } | |
481 | ||
482 | template <typename IntType> | |
483 | inline rational<IntType> operator- (const rational<IntType>& r) | |
484 | { | |
b32b8144 | 485 | return rational<IntType>(static_cast<IntType>(-r.numerator()), r.denominator()); |
7c673cae FG |
486 | } |
487 | ||
488 | // Arithmetic assignment operators | |
489 | template <typename IntType> | |
490 | rational<IntType>& rational<IntType>::operator+= (const rational<IntType>& r) | |
491 | { | |
492 | // This calculation avoids overflow, and minimises the number of expensive | |
493 | // calculations. Thanks to Nickolay Mladenov for this algorithm. | |
494 | // | |
495 | // Proof: | |
496 | // We have to compute a/b + c/d, where gcd(a,b)=1 and gcd(b,c)=1. | |
497 | // Let g = gcd(b,d), and b = b1*g, d=d1*g. Then gcd(b1,d1)=1 | |
498 | // | |
499 | // The result is (a*d1 + c*b1) / (b1*d1*g). | |
500 | // Now we have to normalize this ratio. | |
501 | // Let's assume h | gcd((a*d1 + c*b1), (b1*d1*g)), and h > 1 | |
502 | // If h | b1 then gcd(h,d1)=1 and hence h|(a*d1+c*b1) => h|a. | |
503 | // But since gcd(a,b1)=1 we have h=1. | |
504 | // Similarly h|d1 leads to h=1. | |
505 | // So we have that h | gcd((a*d1 + c*b1) , (b1*d1*g)) => h|g | |
506 | // Finally we have gcd((a*d1 + c*b1), (b1*d1*g)) = gcd((a*d1 + c*b1), g) | |
507 | // Which proves that instead of normalizing the result, it is better to | |
508 | // divide num and den by gcd((a*d1 + c*b1), g) | |
509 | ||
510 | // Protect against self-modification | |
511 | IntType r_num = r.num; | |
512 | IntType r_den = r.den; | |
513 | ||
514 | IntType g = integer::gcd(den, r_den); | |
515 | den /= g; // = b1 from the calculations above | |
516 | num = num * (r_den / g) + r_num * den; | |
517 | g = integer::gcd(num, g); | |
518 | num /= g; | |
519 | den *= r_den/g; | |
520 | ||
521 | return *this; | |
522 | } | |
523 | ||
524 | template <typename IntType> | |
525 | rational<IntType>& rational<IntType>::operator-= (const rational<IntType>& r) | |
526 | { | |
527 | // Protect against self-modification | |
528 | IntType r_num = r.num; | |
529 | IntType r_den = r.den; | |
530 | ||
531 | // This calculation avoids overflow, and minimises the number of expensive | |
532 | // calculations. It corresponds exactly to the += case above | |
533 | IntType g = integer::gcd(den, r_den); | |
534 | den /= g; | |
535 | num = num * (r_den / g) - r_num * den; | |
536 | g = integer::gcd(num, g); | |
537 | num /= g; | |
538 | den *= r_den/g; | |
539 | ||
540 | return *this; | |
541 | } | |
542 | ||
543 | template <typename IntType> | |
544 | rational<IntType>& rational<IntType>::operator*= (const rational<IntType>& r) | |
545 | { | |
546 | // Protect against self-modification | |
547 | IntType r_num = r.num; | |
548 | IntType r_den = r.den; | |
549 | ||
550 | // Avoid overflow and preserve normalization | |
551 | IntType gcd1 = integer::gcd(num, r_den); | |
552 | IntType gcd2 = integer::gcd(r_num, den); | |
553 | num = (num/gcd1) * (r_num/gcd2); | |
554 | den = (den/gcd2) * (r_den/gcd1); | |
555 | return *this; | |
556 | } | |
557 | ||
558 | template <typename IntType> | |
559 | rational<IntType>& rational<IntType>::operator/= (const rational<IntType>& r) | |
560 | { | |
561 | // Protect against self-modification | |
562 | IntType r_num = r.num; | |
563 | IntType r_den = r.den; | |
564 | ||
565 | // Avoid repeated construction | |
566 | IntType zero(0); | |
567 | ||
568 | // Trap division by zero | |
569 | if (r_num == zero) | |
570 | BOOST_THROW_EXCEPTION(bad_rational()); | |
571 | if (num == zero) | |
572 | return *this; | |
573 | ||
574 | // Avoid overflow and preserve normalization | |
575 | IntType gcd1 = integer::gcd(num, r_num); | |
576 | IntType gcd2 = integer::gcd(r_den, den); | |
577 | num = (num/gcd1) * (r_den/gcd2); | |
578 | den = (den/gcd2) * (r_num/gcd1); | |
579 | ||
580 | if (den < zero) { | |
581 | num = -num; | |
582 | den = -den; | |
583 | } | |
584 | return *this; | |
585 | } | |
586 | ||
b32b8144 FG |
587 | |
588 | // | |
589 | // Non-member operators: previously these were provided by Boost.Operator, but these had a number of | |
590 | // drawbacks, most notably, that in order to allow inter-operability with IntType code such as this: | |
591 | // | |
592 | // rational<int> r(3); | |
593 | // assert(r == 3.5); // compiles and passes!! | |
594 | // | |
595 | // Happens to be allowed as well :-( | |
596 | // | |
597 | // There are three possible cases for each operator: | |
598 | // 1) rational op rational. | |
599 | // 2) rational op integer | |
600 | // 3) integer op rational | |
601 | // Cases (1) and (2) are folded into the one function. | |
602 | // | |
603 | template <class IntType, class Arg> | |
604 | inline typename boost::enable_if_c < | |
605 | rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type | |
606 | operator + (const rational<IntType>& a, const Arg& b) | |
7c673cae | 607 | { |
b32b8144 FG |
608 | rational<IntType> t(a); |
609 | return t += b; | |
610 | } | |
611 | template <class Arg, class IntType> | |
612 | inline typename boost::enable_if_c < | |
613 | rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type | |
614 | operator + (const Arg& b, const rational<IntType>& a) | |
615 | { | |
616 | rational<IntType> t(a); | |
617 | return t += b; | |
618 | } | |
7c673cae | 619 | |
b32b8144 FG |
620 | template <class IntType, class Arg> |
621 | inline typename boost::enable_if_c < | |
622 | rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type | |
623 | operator - (const rational<IntType>& a, const Arg& b) | |
624 | { | |
625 | rational<IntType> t(a); | |
626 | return t -= b; | |
627 | } | |
628 | template <class Arg, class IntType> | |
629 | inline typename boost::enable_if_c < | |
630 | rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type | |
631 | operator - (const Arg& b, const rational<IntType>& a) | |
632 | { | |
633 | rational<IntType> t(a); | |
634 | return -(t -= b); | |
7c673cae FG |
635 | } |
636 | ||
b32b8144 FG |
637 | template <class IntType, class Arg> |
638 | inline typename boost::enable_if_c < | |
639 | rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type | |
640 | operator * (const rational<IntType>& a, const Arg& b) | |
7c673cae | 641 | { |
b32b8144 FG |
642 | rational<IntType> t(a); |
643 | return t *= b; | |
644 | } | |
645 | template <class Arg, class IntType> | |
646 | inline typename boost::enable_if_c < | |
647 | rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type | |
648 | operator * (const Arg& b, const rational<IntType>& a) | |
649 | { | |
650 | rational<IntType> t(a); | |
651 | return t *= b; | |
652 | } | |
7c673cae | 653 | |
b32b8144 FG |
654 | template <class IntType, class Arg> |
655 | inline typename boost::enable_if_c < | |
656 | rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type | |
657 | operator / (const rational<IntType>& a, const Arg& b) | |
658 | { | |
659 | rational<IntType> t(a); | |
660 | return t /= b; | |
661 | } | |
662 | template <class Arg, class IntType> | |
663 | inline typename boost::enable_if_c < | |
664 | rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type | |
665 | operator / (const Arg& b, const rational<IntType>& a) | |
666 | { | |
667 | rational<IntType> t(b); | |
668 | return t /= a; | |
669 | } | |
7c673cae | 670 | |
b32b8144 FG |
671 | template <class IntType, class Arg> |
672 | inline typename boost::enable_if_c < | |
673 | rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, bool>::type | |
674 | operator <= (const rational<IntType>& a, const Arg& b) | |
675 | { | |
676 | return !(a > b); | |
677 | } | |
678 | template <class Arg, class IntType> | |
679 | inline typename boost::enable_if_c < | |
680 | rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type | |
681 | operator <= (const Arg& b, const rational<IntType>& a) | |
682 | { | |
683 | return a >= b; | |
684 | } | |
7c673cae | 685 | |
b32b8144 FG |
686 | template <class IntType, class Arg> |
687 | inline typename boost::enable_if_c < | |
688 | rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, bool>::type | |
689 | operator >= (const rational<IntType>& a, const Arg& b) | |
690 | { | |
691 | return !(a < b); | |
692 | } | |
693 | template <class Arg, class IntType> | |
694 | inline typename boost::enable_if_c < | |
695 | rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type | |
696 | operator >= (const Arg& b, const rational<IntType>& a) | |
697 | { | |
698 | return a <= b; | |
699 | } | |
7c673cae | 700 | |
b32b8144 FG |
701 | template <class IntType, class Arg> |
702 | inline typename boost::enable_if_c < | |
703 | rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, bool>::type | |
704 | operator != (const rational<IntType>& a, const Arg& b) | |
705 | { | |
706 | return !(a == b); | |
707 | } | |
708 | template <class Arg, class IntType> | |
709 | inline typename boost::enable_if_c < | |
710 | rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type | |
711 | operator != (const Arg& b, const rational<IntType>& a) | |
712 | { | |
713 | return !(b == a); | |
714 | } | |
715 | ||
716 | template <class Arg, class IntType> | |
717 | inline typename boost::enable_if_c < | |
718 | rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type | |
719 | operator < (const Arg& b, const rational<IntType>& a) | |
720 | { | |
721 | return a > b; | |
722 | } | |
723 | template <class Arg, class IntType> | |
724 | inline typename boost::enable_if_c < | |
725 | rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type | |
726 | operator > (const Arg& b, const rational<IntType>& a) | |
727 | { | |
728 | return a < b; | |
729 | } | |
730 | template <class Arg, class IntType> | |
731 | inline typename boost::enable_if_c < | |
732 | rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type | |
733 | operator == (const Arg& b, const rational<IntType>& a) | |
734 | { | |
735 | return a == b; | |
7c673cae FG |
736 | } |
737 | ||
738 | // Comparison operators | |
739 | template <typename IntType> | |
740 | bool rational<IntType>::operator< (const rational<IntType>& r) const | |
741 | { | |
742 | // Avoid repeated construction | |
743 | int_type const zero( 0 ); | |
744 | ||
745 | // This should really be a class-wide invariant. The reason for these | |
746 | // checks is that for 2's complement systems, INT_MIN has no corresponding | |
747 | // positive, so negating it during normalization keeps it INT_MIN, which | |
748 | // is bad for later calculations that assume a positive denominator. | |
749 | BOOST_ASSERT( this->den > zero ); | |
750 | BOOST_ASSERT( r.den > zero ); | |
751 | ||
752 | // Determine relative order by expanding each value to its simple continued | |
753 | // fraction representation using the Euclidian GCD algorithm. | |
754 | struct { int_type n, d, q, r; } | |
755 | ts = { this->num, this->den, static_cast<int_type>(this->num / this->den), | |
756 | static_cast<int_type>(this->num % this->den) }, | |
757 | rs = { r.num, r.den, static_cast<int_type>(r.num / r.den), | |
758 | static_cast<int_type>(r.num % r.den) }; | |
759 | unsigned reverse = 0u; | |
760 | ||
761 | // Normalize negative moduli by repeatedly adding the (positive) denominator | |
762 | // and decrementing the quotient. Later cycles should have all positive | |
763 | // values, so this only has to be done for the first cycle. (The rules of | |
764 | // C++ require a nonnegative quotient & remainder for a nonnegative dividend | |
765 | // & positive divisor.) | |
766 | while ( ts.r < zero ) { ts.r += ts.d; --ts.q; } | |
767 | while ( rs.r < zero ) { rs.r += rs.d; --rs.q; } | |
768 | ||
769 | // Loop through and compare each variable's continued-fraction components | |
770 | for ( ;; ) | |
771 | { | |
772 | // The quotients of the current cycle are the continued-fraction | |
773 | // components. Comparing two c.f. is comparing their sequences, | |
774 | // stopping at the first difference. | |
775 | if ( ts.q != rs.q ) | |
776 | { | |
777 | // Since reciprocation changes the relative order of two variables, | |
778 | // and c.f. use reciprocals, the less/greater-than test reverses | |
779 | // after each index. (Start w/ non-reversed @ whole-number place.) | |
780 | return reverse ? ts.q > rs.q : ts.q < rs.q; | |
781 | } | |
782 | ||
783 | // Prepare the next cycle | |
784 | reverse ^= 1u; | |
785 | ||
786 | if ( (ts.r == zero) || (rs.r == zero) ) | |
787 | { | |
788 | // At least one variable's c.f. expansion has ended | |
789 | break; | |
790 | } | |
791 | ||
792 | ts.n = ts.d; ts.d = ts.r; | |
793 | ts.q = ts.n / ts.d; ts.r = ts.n % ts.d; | |
794 | rs.n = rs.d; rs.d = rs.r; | |
795 | rs.q = rs.n / rs.d; rs.r = rs.n % rs.d; | |
796 | } | |
797 | ||
798 | // Compare infinity-valued components for otherwise equal sequences | |
799 | if ( ts.r == rs.r ) | |
800 | { | |
801 | // Both remainders are zero, so the next (and subsequent) c.f. | |
802 | // components for both sequences are infinity. Therefore, the sequences | |
803 | // and their corresponding values are equal. | |
804 | return false; | |
805 | } | |
806 | else | |
807 | { | |
808 | #ifdef BOOST_MSVC | |
809 | #pragma warning(push) | |
810 | #pragma warning(disable:4800) | |
811 | #endif | |
812 | // Exactly one of the remainders is zero, so all following c.f. | |
813 | // components of that variable are infinity, while the other variable | |
814 | // has a finite next c.f. component. So that other variable has the | |
815 | // lesser value (modulo the reversal flag!). | |
816 | return ( ts.r != zero ) != static_cast<bool>( reverse ); | |
817 | #ifdef BOOST_MSVC | |
818 | #pragma warning(pop) | |
819 | #endif | |
820 | } | |
821 | } | |
822 | ||
7c673cae FG |
823 | template <typename IntType> |
824 | BOOST_CONSTEXPR | |
825 | inline bool rational<IntType>::operator== (const rational<IntType>& r) const | |
826 | { | |
827 | return ((num == r.num) && (den == r.den)); | |
828 | } | |
829 | ||
7c673cae FG |
830 | // Invariant check |
831 | template <typename IntType> | |
832 | inline bool rational<IntType>::test_invariant() const | |
833 | { | |
834 | return ( this->den > int_type(0) ) && ( integer::gcd(this->num, this->den) == | |
835 | int_type(1) ); | |
836 | } | |
837 | ||
838 | // Normalisation | |
839 | template <typename IntType> | |
840 | void rational<IntType>::normalize() | |
841 | { | |
842 | // Avoid repeated construction | |
843 | IntType zero(0); | |
844 | ||
845 | if (den == zero) | |
846 | BOOST_THROW_EXCEPTION(bad_rational()); | |
847 | ||
848 | // Handle the case of zero separately, to avoid division by zero | |
849 | if (num == zero) { | |
850 | den = IntType(1); | |
851 | return; | |
852 | } | |
853 | ||
854 | IntType g = integer::gcd(num, den); | |
855 | ||
856 | num /= g; | |
857 | den /= g; | |
858 | ||
859 | // Ensure that the denominator is positive | |
860 | if (den < zero) { | |
861 | num = -num; | |
862 | den = -den; | |
863 | } | |
864 | ||
865 | // ...But acknowledge that the previous step doesn't always work. | |
866 | // (Nominally, this should be done before the mutating steps, but this | |
867 | // member function is only called during the constructor, so we never have | |
868 | // to worry about zombie objects.) | |
869 | if (den < zero) | |
870 | BOOST_THROW_EXCEPTION(bad_rational("bad rational: non-zero singular denominator")); | |
871 | ||
872 | BOOST_ASSERT( this->test_invariant() ); | |
873 | } | |
874 | ||
875 | #ifndef BOOST_NO_IOSTREAM | |
876 | namespace detail { | |
877 | ||
878 | // A utility class to reset the format flags for an istream at end | |
879 | // of scope, even in case of exceptions | |
880 | struct resetter { | |
881 | resetter(std::istream& is) : is_(is), f_(is.flags()) {} | |
882 | ~resetter() { is_.flags(f_); } | |
883 | std::istream& is_; | |
884 | std::istream::fmtflags f_; // old GNU c++ lib has no ios_base | |
885 | }; | |
886 | ||
887 | } | |
888 | ||
889 | // Input and output | |
890 | template <typename IntType> | |
891 | std::istream& operator>> (std::istream& is, rational<IntType>& r) | |
892 | { | |
893 | using std::ios; | |
894 | ||
895 | IntType n = IntType(0), d = IntType(1); | |
896 | char c = 0; | |
897 | detail::resetter sentry(is); | |
898 | ||
899 | if ( is >> n ) | |
900 | { | |
901 | if ( is.get(c) ) | |
902 | { | |
903 | if ( c == '/' ) | |
904 | { | |
905 | if ( is >> std::noskipws >> d ) | |
906 | try { | |
907 | r.assign( n, d ); | |
908 | } catch ( bad_rational & ) { // normalization fail | |
909 | try { is.setstate(ios::failbit); } | |
910 | catch ( ... ) {} // don't throw ios_base::failure... | |
911 | if ( is.exceptions() & ios::failbit ) | |
912 | throw; // ...but the original exception instead | |
913 | // ELSE: suppress the exception, use just error flags | |
914 | } | |
915 | } | |
916 | else | |
917 | is.setstate( ios::failbit ); | |
918 | } | |
919 | } | |
920 | ||
921 | return is; | |
922 | } | |
923 | ||
924 | // Add manipulators for output format? | |
925 | template <typename IntType> | |
926 | std::ostream& operator<< (std::ostream& os, const rational<IntType>& r) | |
927 | { | |
928 | // The slash directly precedes the denominator, which has no prefixes. | |
929 | std::ostringstream ss; | |
930 | ||
931 | ss.copyfmt( os ); | |
932 | ss.tie( NULL ); | |
933 | ss.exceptions( std::ios::goodbit ); | |
934 | ss.width( 0 ); | |
935 | ss << std::noshowpos << std::noshowbase << '/' << r.denominator(); | |
936 | ||
937 | // The numerator holds the showpos, internal, and showbase flags. | |
938 | std::string const tail = ss.str(); | |
939 | std::streamsize const w = | |
940 | os.width() - static_cast<std::streamsize>( tail.size() ); | |
941 | ||
942 | ss.clear(); | |
943 | ss.str( "" ); | |
944 | ss.flags( os.flags() ); | |
945 | ss << std::setw( w < 0 || (os.flags() & std::ios::adjustfield) != | |
946 | std::ios::internal ? 0 : w ) << r.numerator(); | |
947 | return os << ss.str() + tail; | |
948 | } | |
949 | #endif // BOOST_NO_IOSTREAM | |
950 | ||
951 | // Type conversion | |
952 | template <typename T, typename IntType> | |
953 | BOOST_CONSTEXPR | |
954 | inline T rational_cast(const rational<IntType>& src) | |
955 | { | |
956 | return static_cast<T>(src.numerator())/static_cast<T>(src.denominator()); | |
957 | } | |
958 | ||
959 | // Do not use any abs() defined on IntType - it isn't worth it, given the | |
960 | // difficulties involved (Koenig lookup required, there may not *be* an abs() | |
961 | // defined, etc etc). | |
962 | template <typename IntType> | |
963 | inline rational<IntType> abs(const rational<IntType>& r) | |
964 | { | |
965 | return r.numerator() >= IntType(0)? r: -r; | |
966 | } | |
967 | ||
968 | namespace integer { | |
969 | ||
970 | template <typename IntType> | |
971 | struct gcd_evaluator< rational<IntType> > | |
972 | { | |
973 | typedef rational<IntType> result_type, | |
974 | first_argument_type, second_argument_type; | |
975 | result_type operator() ( first_argument_type const &a | |
976 | , second_argument_type const &b | |
977 | ) const | |
978 | { | |
979 | return result_type(integer::gcd(a.numerator(), b.numerator()), | |
980 | integer::lcm(a.denominator(), b.denominator())); | |
981 | } | |
982 | }; | |
983 | ||
984 | template <typename IntType> | |
985 | struct lcm_evaluator< rational<IntType> > | |
986 | { | |
987 | typedef rational<IntType> result_type, | |
988 | first_argument_type, second_argument_type; | |
989 | result_type operator() ( first_argument_type const &a | |
990 | , second_argument_type const &b | |
991 | ) const | |
992 | { | |
993 | return result_type(integer::lcm(a.numerator(), b.numerator()), | |
994 | integer::gcd(a.denominator(), b.denominator())); | |
995 | } | |
996 | }; | |
997 | ||
998 | } // namespace integer | |
999 | ||
1000 | } // namespace boost | |
1001 | ||
1002 | #endif // BOOST_RATIONAL_HPP |