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_integer_rat
(self)
| 928 | return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp) |
| 929 | |
| 930 | def as_integer_ratio(self): |
| 931 | """Express a finite Decimal instance in the form n / d. |
| 932 | |
| 933 | Returns a pair (n, d) of integers. When called on an infinity |
| 934 | or NaN, raises OverflowError or ValueError respectively. |
| 935 | |
| 936 | >>> Decimal('3.14').as_integer_ratio() |
| 937 | (157, 50) |
| 938 | >>> Decimal('-123e5').as_integer_ratio() |
| 939 | (-12300000, 1) |
| 940 | >>> Decimal('0.00').as_integer_ratio() |
| 941 | (0, 1) |
| 942 | |
| 943 | """ |
| 944 | if self._is_special: |
| 945 | if self.is_nan(): |
| 946 | raise ValueError("cannot convert NaN to integer ratio") |
| 947 | else: |
| 948 | raise OverflowError("cannot convert Infinity to integer ratio") |
| 949 | |
| 950 | if not self: |
| 951 | return 0, 1 |
| 952 | |
| 953 | # Find n, d in lowest terms such that abs(self) == n / d; |
| 954 | # we'll deal with the sign later. |
| 955 | n = int(self._int) |
| 956 | if self._exp >= 0: |
| 957 | # self is an integer. |
| 958 | n, d = n * 10**self._exp, 1 |
| 959 | else: |
| 960 | # Find d2, d5 such that abs(self) = n / (2**d2 * 5**d5). |
| 961 | d5 = -self._exp |
| 962 | while d5 > 0 and n % 5 == 0: |
| 963 | n //= 5 |
| 964 | d5 -= 1 |
| 965 | |
| 966 | # (n & -n).bit_length() - 1 counts trailing zeros in binary |
| 967 | # representation of n (provided n is nonzero). |
| 968 | d2 = -self._exp |
| 969 | shift2 = min((n & -n).bit_length() - 1, d2) |
| 970 | if shift2: |
| 971 | n >>= shift2 |
| 972 | d2 -= shift2 |
| 973 | |
| 974 | d = 5**d5 << d2 |
| 975 | |
| 976 | if self._sign: |
| 977 | n = -n |
| 978 | return n, d |
| 979 | |
| 980 | def __repr__(self): |
| 981 | """Represents the number as an instance of Decimal.""" |