Express a finite Decimal instance in the form n / d. Returns a pair (n, d) of integers. When called on an infinity or NaN, raises OverflowError or ValueError respectively. >>> Decimal('3.14').as_integer_ratio() (157, 50) >>> Decimal('-123e5').as_inte
(self)
| 984 | return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp) |
| 985 | |
| 986 | def as_integer_ratio(self): |
| 987 | """Express a finite Decimal instance in the form n / d. |
| 988 | |
| 989 | Returns a pair (n, d) of integers. When called on an infinity |
| 990 | or NaN, raises OverflowError or ValueError respectively. |
| 991 | |
| 992 | >>> Decimal('3.14').as_integer_ratio() |
| 993 | (157, 50) |
| 994 | >>> Decimal('-123e5').as_integer_ratio() |
| 995 | (-12300000, 1) |
| 996 | >>> Decimal('0.00').as_integer_ratio() |
| 997 | (0, 1) |
| 998 | |
| 999 | """ |
| 1000 | if self._is_special: |
| 1001 | if self.is_nan(): |
| 1002 | raise ValueError("cannot convert NaN to integer ratio") |
| 1003 | else: |
| 1004 | raise OverflowError("cannot convert Infinity to integer ratio") |
| 1005 | |
| 1006 | if not self: |
| 1007 | return 0, 1 |
| 1008 | |
| 1009 | # Find n, d in lowest terms such that abs(self) == n / d; |
| 1010 | # we'll deal with the sign later. |
| 1011 | n = int(self._int) |
| 1012 | if self._exp >= 0: |
| 1013 | # self is an integer. |
| 1014 | n, d = n * 10**self._exp, 1 |
| 1015 | else: |
| 1016 | # Find d2, d5 such that abs(self) = n / (2**d2 * 5**d5). |
| 1017 | d5 = -self._exp |
| 1018 | while d5 > 0 and n % 5 == 0: |
| 1019 | n //= 5 |
| 1020 | d5 -= 1 |
| 1021 | |
| 1022 | # (n & -n).bit_length() - 1 counts trailing zeros in binary |
| 1023 | # representation of n (provided n is nonzero). |
| 1024 | d2 = -self._exp |
| 1025 | shift2 = min((n & -n).bit_length() - 1, d2) |
| 1026 | if shift2: |
| 1027 | n >>= shift2 |
| 1028 | d2 -= shift2 |
| 1029 | |
| 1030 | d = 5**d5 << d2 |
| 1031 | |
| 1032 | if self._sign: |
| 1033 | n = -n |
| 1034 | return n, d |
| 1035 | |
| 1036 | def __repr__(self): |
| 1037 | """Represents the number as an instance of Decimal.""" |
no test coverage detected