OLD | NEW |
1 """Implementation of rational arithmetic.""" | 1 """Implementation of rational arithmetic.""" |
2 | 2 |
3 | 3 |
4 | 4 |
5 import math as _math | 5 import math as _math |
6 | 6 |
7 def _gcf(a, b): | 7 def _gcf(a, b): |
8 """Returns the greatest common factor of a and b.""" | 8 """Returns the greatest common factor of a and b.""" |
9 a = abs(a) | 9 a = abs(a) |
10 b = abs(b) | 10 b = abs(b) |
11 while b: | 11 while b: |
12 a, b = b, a % b | 12 a, b = b, a % b |
13 return a | 13 return a |
14 | 14 |
15 class Rational(object): | 15 class Rational(object): |
16 """ | 16 """ |
17 This class provides an exact representation of rational numbers. | 17 This class provides an exact representation of rational numbers. |
18 | 18 |
19 All of the standard arithmetic operators are provided. In mixed-type | 19 All of the standard arithmetic operators are provided. In mixed-type |
20 expressions, an int or a long can be converted to a Rational without | 20 expressions, an int or a long can be converted to a Rational without |
21 loss of precision, and will be done as such. | 21 loss of precision, and will be done as such. |
22 | 22 |
23 Rationals can be implicity (using binary operators) or explicity | 23 Rationals can be implicity (using binary operators) or explicity |
24 (using float(x) or x.decimal()) converted to floats or Decimals; | 24 (using float(x) or x.decimal()) converted to floats or Decimals; |
25 this may cause a loss of precision. The reverse conversions can be | 25 this may cause a loss of precision. The reverse conversions can be |
26 done without loss of precision, and are performed with the | 26 done without loss of precision, and are performed with the |
27 from_exact_float and from_exact_decimal static methods. However, | 27 from_exact_float and from_exact_decimal static methods. However, |
28 because of rounding error in the original values, this tends to | 28 because of rounding error in the original values, this tends to |
(...skipping 227 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
256 minError = error | 256 minError = error |
257 return result | 257 return result |
258 | 258 |
259 def divide(x, y): | 259 def divide(x, y): |
260 """Same as x/y, but returns a Rational if both are ints.""" | 260 """Same as x/y, but returns a Rational if both are ints.""" |
261 if isinstance(x, int) and isinstance(y, int): | 261 if isinstance(x, int) and isinstance(y, int): |
262 return Rational(x, y) | 262 return Rational(x, y) |
263 else: | 263 else: |
264 return x / y | 264 return x / y |
265 | 265 |
OLD | NEW |