Lines Matching refs:self

202                trap_enabler is not set.  First argument is self, second is the
205 context._raise_error(NewError, '(-x)!', self._sign) would
206 call NewError().handle(context, self._sign).)
211 def handle(self, context, *args):
250 def handle(self, context, *args):
263 def handle(self, context, *args):
279 def handle(self, context, sign, *args):
290 def handle(self, context, *args):
301 def handle(self, context, *args):
327 def handle(self, context, *args):
375 def handle(self, context, sign, *args):
547 # Note that the coefficient, self._int, is actually stored as
555 self = object.__new__(cls)
568 self._sign = 1
570 self._sign = 0
576 self._int = str(int(intpart+fracpart))
577 self._exp = exp - len(fracpart)
578 self._is_special = False
583 self._int = str(int(diag or '0')).lstrip('0')
585 self._exp = 'N'
587 self._exp = 'n'
590 self._int = '0'
591 self._exp = 'F'
592 self._is_special = True
593 return self
598 self._sign = 0
600 self._sign = 1
601 self._exp = 0
602 self._int = str(abs(value))
603 self._is_special = False
604 return self
608 self._exp = value._exp
609 self._sign = value._sign
610 self._int = value._int
611 self._is_special = value._is_special
612 return self
616 self._sign = value.sign
617 self._int = str(value.int)
618 self._exp = int(value.exp)
619 self._is_special = False
620 return self
633 self._sign = value[0]
636 self._int = '0'
637 self._exp = value[2]
638 self._is_special = True
653 self._int = ''.join(map(str, digits))
654 self._exp = value[2]
655 self._is_special = True
658 self._int = ''.join(map(str, digits or [0]))
659 self._exp = value[2]
660 self._is_special = False
665 return self
674 self._exp = value._exp
675 self._sign = value._sign
676 self._int = value._int
677 self._is_special = value._is_special
678 return self
727 def _isnan(self):
734 if self._is_special:
735 exp = self._exp
742 def _isinfinity(self):
749 if self._exp == 'F':
750 if self._sign:
755 def _check_nans(self, other=None, context=None):
758 if self, other are sNaN, signal
759 if self, other are NaN return nan
765 self_is_nan = self._isnan()
777 self)
782 return self._fix_nan(context)
787 def _compare_check_nans(self, other, context):
791 Signal InvalidOperation if either self or other is a (quiet
801 if self._is_special or other._is_special:
802 if self.is_snan():
805 self)
810 elif self.is_qnan():
813 self)
820 def __bool__(self):
821 """Return True if self is nonzero; otherwise return False.
825 return self._is_special or self._int != '0'
827 def _cmp(self, other):
828 """Compare the two non-NaN decimal instances self and other.
830 Returns -1 if self < other, 0 if self == other and 1
831 if self > other. This routine is for internal use only."""
833 if self._is_special or other._is_special:
834 self_inf = self._isinfinity()
844 if not self:
850 return (-1)**self._sign
853 if other._sign < self._sign:
855 if self._sign < other._sign:
858 self_adjusted = self.adjusted()
861 self_padded = self._int + '0'*(self._exp - other._exp)
862 other_padded = other._int + '0'*(other._exp - self._exp)
866 return -(-1)**self._sign
868 return (-1)**self._sign
870 return (-1)**self._sign
872 return -((-1)**self._sign)
891 def __eq__(self, other, context=None):
892 self, other = _convert_for_comparison(self, other, equality_op=True)
895 if self._check_nans(other, context):
897 return self._cmp(other) == 0
899 def __lt__(self, other, context=None):
900 self, other = _convert_for_comparison(self, other)
903 ans = self._compare_check_nans(other, context)
906 return self._cmp(other) < 0
908 def __le__(self, other, context=None):
909 self, other = _convert_for_comparison(self, other)
912 ans = self._compare_check_nans(other, context)
915 return self._cmp(other) <= 0
917 def __gt__(self, other, context=None):
918 self, other = _convert_for_comparison(self, other)
921 ans = self._compare_check_nans(other, context)
924 return self._cmp(other) > 0
926 def __ge__(self, other, context=None):
927 self, other = _convert_for_comparison(self, other)
930 ans = self._compare_check_nans(other, context)
933 return self._cmp(other) >= 0
935 def compare(self, other, context=None):
936 """Compare self to other. Return a decimal value:
946 if (self._is_special or other and other._is_special):
947 ans = self._check_nans(other, context)
951 return Decimal(self._cmp(other))
953 def __hash__(self):
960 if self._is_special:
961 if self.is_snan():
963 elif self.is_nan():
964 return object.__hash__(self)
966 if self._sign:
971 if self._exp >= 0:
972 exp_hash = pow(10, self._exp, _PyHASH_MODULUS)
974 exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS)
975 hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS
976 ans = hash_ if self >= 0 else -hash_
979 def as_tuple(self):
984 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
986 def as_integer_ratio(self):
1000 if self._is_special:
1001 if self.is_nan():
1006 if not self:
1009 # Find n, d in lowest terms such that abs(self) == n / d;
1011 n = int(self._int)
1012 if self._exp >= 0:
1013 # self is an integer.
1014 n, d = n * 10**self._exp, 1
1016 # Find d2, d5 such that abs(self) = n / (2**d2 * 5**d5).
1017 d5 = -self._exp
1024 d2 = -self._exp
1032 if self._sign:
1036 def __repr__(self):
1039 return "Decimal('%s')" % str(self)
1041 def __str__(self, eng=False, context=None):
1047 sign = ['', '-'][self._sign]
1048 if self._is_special:
1049 if self._exp == 'F':
1051 elif self._exp == 'n':
1052 return sign + 'NaN' + self._int
1053 else: # self._exp == 'N'
1054 return sign + 'sNaN' + self._int
1056 # number of digits of self._int to left of decimal point
1057 leftdigits = self._exp + len(self._int)
1059 # dotplace is number of digits of self._int to the left of the
1062 if self._exp <= 0 and leftdigits > -6:
1068 elif self._int == '0':
1077 fracpart = '.' + '0'*(-dotplace) + self._int
1078 elif dotplace >= len(self._int):
1079 intpart = self._int+'0'*(dotplace-len(self._int))
1082 intpart = self._int[:dotplace]
1083 fracpart = '.' + self._int[dotplace:]
1093 def to_eng_string(self, context=None):
1100 return self.__str__(eng=True, context=context)
1102 def __neg__(self, context=None):
1107 if self._is_special:
1108 ans = self._check_nans(context=context)
1115 if not self and context.rounding != ROUND_FLOOR:
1118 ans = self.copy_abs()
1120 ans = self.copy_negate()
1124 def __pos__(self, context=None):
1129 if self._is_special:
1130 ans = self._check_nans(context=context)
1137 if not self and context.rounding != ROUND_FLOOR:
1139 ans = self.copy_abs()
1141 ans = Decimal(self)
1145 def __abs__(self, round=True, context=None):
1146 """Returns the absolute value of self.
1149 expression self.__abs__(round=False) is equivalent to
1150 self.copy_abs().
1153 return self.copy_abs()
1155 if self._is_special:
1156 ans = self._check_nans(context=context)
1160 if self._sign:
1161 ans = self.__neg__(context=context)
1163 ans = self.__pos__(context=context)
1167 def __add__(self, other, context=None):
1168 """Returns self + other.
1179 if self._is_special or other._is_special:
1180 ans = self._check_nans(other, context)
1184 if self._isinfinity():
1186 if self._sign != other._sign and other._isinfinity():
1188 return Decimal(self)
1192 exp = min(self._exp, other._exp)
1194 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
1198 if not self and not other:
1199 sign = min(self._sign, other._sign)
1205 if not self:
1211 exp = max(exp, self._exp - context.prec-1)
1212 ans = self._rescale(exp, context.rounding)
1216 op1 = _WorkRep(self)
1255 def __sub__(self, other, context=None):
1256 """Return self - other"""
1261 if self._is_special or other._is_special:
1262 ans = self._check_nans(other, context=context)
1266 # self - other is computed as self + other.copy_negate()
1267 return self.__add__(other.copy_negate(), context=context)
1269 def __rsub__(self, other, context=None):
1270 """Return other - self"""
1275 return other.__sub__(self, context=context)
1277 def __mul__(self, other, context=None):
1278 """Return self * other.
1289 resultsign = self._sign ^ other._sign
1291 if self._is_special or other._is_special:
1292 ans = self._check_nans(other, context)
1296 if self._isinfinity():
1302 if not self:
1306 resultexp = self._exp + other._exp
1309 if not self or not other:
1316 if self._int == '1':
1321 ans = _dec_from_triple(resultsign, self._int, resultexp)
1325 op1 = _WorkRep(self)
1334 def __truediv__(self, other, context=None):
1335 """Return self / other."""
1343 sign = self._sign ^ other._sign
1345 if self._is_special or other._is_special:
1346 ans = self._check_nans(other, context)
1350 if self._isinfinity() and other._isinfinity():
1353 if self._isinfinity():
1362 if not self:
1366 if not self:
1367 exp = self._exp - other._exp
1371 shift = len(other._int) - len(self._int) + context.prec + 1
1372 exp = self._exp - other._exp - shift
1373 op1 = _WorkRep(self)
1385 ideal_exp = self._exp - other._exp
1393 def _divide(self, other, context):
1394 """Return (self // other, self % other), to context.prec precision.
1396 Assumes that neither self nor other is a NaN, that self is not
1399 sign = self._sign ^ other._sign
1401 ideal_exp = self._exp
1403 ideal_exp = min(self._exp, other._exp)
1405 expdiff = self.adjusted() - other.adjusted()
1406 if not self or other._isinfinity() or expdiff <= -2:
1408 self._rescale(ideal_exp, context.rounding))
1410 op1 = _WorkRep(self)
1419 _dec_from_triple(self._sign, str(r), ideal_exp))
1426 def __rtruediv__(self, other, context=None):
1427 """Swaps self/other and returns __truediv__."""
1431 return other.__truediv__(self, context=context)
1433 def __divmod__(self, other, context=None):
1435 Return (self // other, self % other)
1444 ans = self._check_nans(other, context)
1448 sign = self._sign ^ other._sign
1449 if self._isinfinity():
1458 if not self:
1465 quotient, remainder = self._divide(other, context)
1469 def __rdivmod__(self, other, context=None):
1470 """Swaps self/other and returns __divmod__."""
1474 return other.__divmod__(self, context=context)
1476 def __mod__(self, other, context=None):
1478 self % other
1487 ans = self._check_nans(other, context)
1491 if self._isinfinity():
1494 if self:
1499 remainder = self._divide(other, context)[1]
1503 def __rmod__(self, other, context=None):
1504 """Swaps self/other and returns __mod__."""
1508 return other.__mod__(self, context=context)
1510 def remainder_near(self, other, context=None):
1519 ans = self._check_nans(other, context)
1523 # self == +/-infinity -> InvalidOperation
1524 if self._isinfinity():
1530 if self:
1537 # other = +/-infinity -> remainder = self
1539 ans = Decimal(self)
1542 # self = 0 -> remainder = self, with ideal exponent
1543 ideal_exponent = min(self._exp, other._exp)
1544 if not self:
1545 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
1549 expdiff = self.adjusted() - other.adjusted()
1551 # expdiff >= prec+1 => abs(self/other) > 10**prec
1554 # expdiff <= -2 => abs(self/other) < 0.1
1555 ans = self._rescale(ideal_exponent, context.rounding)
1559 op1 = _WorkRep(self)
1576 # result has same sign as self unless r is negative
1577 sign = self._sign
1585 def __floordiv__(self, other, context=None):
1586 """self // other"""
1594 ans = self._check_nans(other, context)
1598 if self._isinfinity():
1602 return _SignedInfinity[self._sign ^ other._sign]
1605 if self:
1607 self._sign ^ other._sign)
1611 return self._divide(other, context)[0]
1613 def __rfloordiv__(self, other, context=None):
1614 """Swaps self/other and returns __floordiv__."""
1618 return other.__floordiv__(self, context=context)
1620 def __float__(self):
1622 if self._isnan():
1623 if self.is_snan():
1625 s = "-nan" if self._sign else "nan"
1627 s = str(self)
1630 def __int__(self):
1631 """Converts self to an int, truncating if necessary."""
1632 if self._is_special:
1633 if self._isnan():
1635 elif self._isinfinity():
1637 s = (-1)**self._sign
1638 if self._exp >= 0:
1639 return s*int(self._int)*10**self._exp
1641 return s*int(self._int[:self._exp] or '0')
1646 def real(self):
1647 return self
1650 def imag(self):
1653 def conjugate(self):
1654 return self
1656 def __complex__(self):
1657 return complex(float(self))
1659 def _fix_nan(self, context):
1661 payload = self._int
1668 return _dec_from_triple(self._sign, payload, self._exp, True)
1669 return Decimal(self)
1671 def _fix(self, context):
1672 """Round if it is necessary to keep self within prec precision.
1677 self - Decimal instance
1681 if self._is_special:
1682 if self._isnan():
1684 return self._fix_nan(context)
1686 # self is +/-Infinity; return unaltered
1687 return Decimal(self)
1689 # if self is zero then exponent should be between Etiny and
1693 if not self:
1695 new_exp = min(max(self._exp, Etiny), exp_max)
1696 if new_exp != self._exp:
1698 return _dec_from_triple(self._sign, '0', new_exp)
1700 return Decimal(self)
1703 # equal to max(self.adjusted()-context.prec+1, Etiny)
1704 exp_min = len(self._int) + self._exp - context.prec
1706 # overflow: exp_min > Etop iff self.adjusted() > Emax
1707 ans = context._raise_error(Overflow, 'above Emax', self._sign)
1716 # round if self has too many digits
1717 if self._exp < exp_min:
1718 digits = len(self._int) + self._exp - exp_min
1720 self = _dec_from_triple(self._sign, '1', exp_min-1)
1722 rounding_method = self._pick_rounding_function[context.rounding]
1723 changed = rounding_method(self, digits)
1724 coeff = self._int[:digits] or '0'
1733 ans = context._raise_error(Overflow, 'above Emax', self._sign)
1735 ans = _dec_from_triple(self._sign, coeff, exp_min)
1754 # fold down if clamp == 1 and self has too few digits
1755 if context.clamp == 1 and self._exp > Etop:
1757 self_padded = self._int + '0'*(self._exp - Etop)
1758 return _dec_from_triple(self._sign, self_padded, Etop)
1760 # here self was representable to begin with; return unchanged
1761 return Decimal(self)
1764 # self is a finite, nonzero Decimal
1765 # prec is an integer satisfying 0 <= prec < len(self._int)
1768 # 1 indicates that self should be rounded up (away from zero)
1769 # 0 indicates that self should be truncated, and that all the
1773 def _round_down(self, prec):
1775 if _all_zeros(self._int, prec):
1780 def _round_up(self, prec):
1782 return -self._round_down(prec)
1784 def _round_half_up(self, prec):
1786 if self._int[prec] in '56789':
1788 elif _all_zeros(self._int, prec):
1793 def _round_half_down(self, prec):
1795 if _exact_half(self._int, prec):
1798 return self._round_half_up(prec)
1800 def _round_half_even(self, prec):
1802 if _exact_half(self._int, prec) and \
1803 (prec == 0 or self._int[prec-1] in '02468'):
1806 return self._round_half_up(prec)
1808 def _round_ceiling(self, prec):
1810 if self._sign:
1811 return self._round_down(prec)
1813 return -self._round_down(prec)
1815 def _round_floor(self, prec):
1817 if not self._sign:
1818 return self._round_down(prec)
1820 return -self._round_down(prec)
1822 def _round_05up(self, prec):
1824 if prec and self._int[prec-1] not in '05':
1825 return self._round_down(prec)
1827 return -self._round_down(prec)
1840 def __round__(self, n=None):
1841 """Round self to the nearest integer, or to a given precision.
1844 instance self to the nearest integer. If self is infinite or
1845 a NaN then a Python exception is raised. If self is finite
1868 If a second argument n is supplied, self is rounded to n
1872 For an integer n, round(self, -n) is exactly equivalent to
1873 self.quantize(Decimal('1En')).
1892 return self.quantize(exp)
1895 if self._is_special:
1896 if self.is_nan():
1900 return int(self._rescale(0, ROUND_HALF_EVEN))
1902 def __floor__(self):
1903 """Return the floor of self, as an integer.
1905 For a finite Decimal instance self, return the greatest
1906 integer n such that n <= self. If self is infinite or a NaN
1910 if self._is_special:
1911 if self.is_nan():
1915 return int(self._rescale(0, ROUND_FLOOR))
1917 def __ceil__(self):
1918 """Return the ceiling of self, as an integer.
1920 For a finite Decimal instance self, return the least integer n
1921 such that n >= self. If self is infinite or a NaN then a
1925 if self._is_special:
1926 if self.is_nan():
1930 return int(self._rescale(0, ROUND_CEILING))
1932 def fma(self, other, third, context=None):
1935 Returns self*other+third with no rounding of the intermediate
1936 product self*other.
1938 self and other are multiplied together, with no rounding of
1948 if self._is_special or other._is_special:
1951 if self._exp == 'N':
1952 return context._raise_error(InvalidOperation, 'sNaN', self)
1955 if self._exp == 'n':
1956 product = self
1959 elif self._exp == 'F':
1963 product = _SignedInfinity[self._sign ^ other._sign]
1965 if not self:
1968 product = _SignedInfinity[self._sign ^ other._sign]
1970 product = _dec_from_triple(self._sign ^ other._sign,
1971 str(int(self._int) * int(other._int)),
1972 self._exp + other._exp)
1976 def _power_modulo(self, other, modulo, context=None):
1991 self_is_nan = self._isnan()
1997 self)
2005 return self._fix_nan(context)
2011 if not (self._isinteger() and
2035 if not other and not self:
2045 sign = self._sign
2047 # convert modulo to a Python integer, and self and other to
2050 base = _WorkRep(self.to_integral_value())
2061 def _power_exact(self, other, p):
2062 """Attempt to compute self**other exactly.
2064 Given Decimals self and other and an integer p, attempt to
2065 compute an exact result for the power self**other, with p
2066 digits of precision. Return None if self**other is not
2070 performed: self and other must both be nonspecial; self must
2075 # In the comments below, we write x for the value of self and y for the
2119 x = _WorkRep(self)
2146 ideal_exponent = self._exp*int(other)
2292 ideal_exponent = self._exp*int(other)
2298 def __pow__(self, other, modulo=None, context=None):
2299 """Return self ** other [ % modulo].
2301 With two arguments, compute self**other.
2303 With three arguments, compute (self**other) % modulo. For the
2309 - either self or other (or both) must be nonzero
2316 The result of pow(self, other, modulo) is identical to the
2317 result that would be obtained by computing (self**other) %
2323 return self._power_modulo(other, modulo, context)
2333 ans = self._check_nans(other, context)
2339 if not self:
2344 # result has sign 1 iff self._sign is 1 and other is an odd integer
2346 if self._sign == 1:
2353 if self:
2356 # negate self, without doing any unwanted rounding
2357 self = self.copy_negate()
2360 if not self:
2367 if self._isinfinity():
2374 # depend on the exponent of self, and on whether other is a
2376 if self == _One:
2378 # exp = max(self._exp*max(int(other), 0),
2389 exp = self._exp * multiplier
2400 # compute adjusted exponent of self
2401 self_adj = self.adjusted()
2403 # self ** infinity is infinity if self > 1, 0 if self < 1
2404 # self ** -infinity is infinity if self < 1, 0 if self > 1
2417 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2419 # self**other >= 10**(Emax+1), so overflow occurs. The test
2421 bound = self._log10_exp_bound() + other.adjusted()
2423 # self > 1 and other +ve, or self < 1 and other -ve
2428 # self > 1 and other -ve, or self < 1 and other +ve
2436 ans = self._power_exact(other, context.prec + 1)
2445 x = _WorkRep(self)
2514 def __rpow__(self, other, context=None):
2515 """Swaps self/other and returns __pow__."""
2519 return other.__pow__(self, context=context)
2521 def normalize(self, context=None):
2527 if self._is_special:
2528 ans = self._check_nans(context=context)
2532 dup = self._fix(context)
2546 def quantize(self, exp, rounding=None, context=None):
2547 """Quantize self so its exponent is the same as that of exp.
2549 Similar to self._rescale(exp._exp) but with error checking.
2558 if self._is_special or exp._is_special:
2559 ans = self._check_nans(exp, context)
2563 if exp._isinfinity() or self._isinfinity():
2564 if exp._isinfinity() and self._isinfinity():
2565 return Decimal(self) # if both are inf, it is OK
2574 if not self:
2575 ans = _dec_from_triple(self._sign, '0', exp._exp)
2578 self_adjusted = self.adjusted()
2586 ans = self._rescale(exp._exp, rounding)
2597 if ans._exp > self._exp:
2598 if ans != self:
2607 def same_quantum(self, other, context=None):
2608 """Return True if self and other have the same exponent; otherwise
2617 if self._is_special or other._is_special:
2618 return (self.is_nan() and other.is_nan() or
2619 self.is_infinite() and other.is_infinite())
2620 return self._exp == other._exp
2622 def _rescale(self, exp, rounding):
2623 """Rescale self so that the exponent is exp, either by padding with zeros
2633 if self._is_special:
2634 return Decimal(self)
2635 if not self:
2636 return _dec_from_triple(self._sign, '0', exp)
2638 if self._exp >= exp:
2640 return _dec_from_triple(self._sign,
2641 self._int + '0'*(self._exp - exp), exp)
2643 # too many digits; round and lose data. If self.adjusted() <
2644 # exp-1, replace self by 10**(exp-1) before rounding
2645 digits = len(self._int) + self._exp - exp
2647 self = _dec_from_triple(self._sign, '1', exp-1)
2649 this_function = self._pick_rounding_function[rounding]
2650 changed = this_function(self, digits)
2651 coeff = self._int[:digits] or '0'
2654 return _dec_from_triple(self._sign, coeff, exp)
2656 def _round(self, places, rounding):
2668 if self._is_special or not self:
2669 return Decimal(self)
2670 ans = self._rescale(self.adjusted()+1-places, rounding)
2675 if ans.adjusted() != self.adjusted():
2679 def to_integral_exact(self, rounding=None, context=None):
2689 if self._is_special:
2690 ans = self._check_nans(context=context)
2693 return Decimal(self)
2694 if self._exp >= 0:
2695 return Decimal(self)
2696 if not self:
2697 return _dec_from_triple(self._sign, '0', 0)
2702 ans = self._rescale(0, rounding)
2703 if ans != self:
2708 def to_integral_value(self, rounding=None, context=None):
2714 if self._is_special:
2715 ans = self._check_nans(context=context)
2718 return Decimal(self)
2719 if self._exp >= 0:
2720 return Decimal(self)
2722 return self._rescale(0, rounding)
2727 def sqrt(self, context=None):
2728 """Return the square root of self."""
2732 if self._is_special:
2733 ans = self._check_nans(context=context)
2737 if self._isinfinity() and self._sign == 0:
2738 return Decimal(self)
2740 if not self:
2741 # exponent = self._exp // 2. sqrt(-0) = -0
2742 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
2745 if self._sign == 1:
2748 # At this point self represents a positive number. Let p be
2749 # the desired precision and express self in the form c*100**e
2752 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2770 # write argument in the form c*100**e where e = self._exp//2
2774 op = _WorkRep(self)
2778 l = (len(self._int) >> 1) + 1
2781 l = len(self._int)+1 >> 1
2826 def max(self, other, context=None):
2829 Like max(self, other) except if one is not a number, returns
2837 if self._is_special or other._is_special:
2840 sn = self._isnan()
2844 return self._fix(context)
2847 return self._check_nans(other, context)
2849 c = self._cmp(other)
2859 c = self.compare_total(other)
2864 ans = self
2868 def min(self, other, context=None):
2871 Like min(self, other) except if one is not a number, returns
2879 if self._is_special or other._is_special:
2882 sn = self._isnan()
2886 return self._fix(context)
2889 return self._check_nans(other, context)
2891 c = self._cmp(other)
2893 c = self.compare_total(other)
2896 ans = self
2902 def _isinteger(self):
2903 """Returns whether self is an integer"""
2904 if self._is_special:
2906 if self._exp >= 0:
2908 rest = self._int[self._exp:]
2911 def _iseven(self):
2912 """Returns True if self is even. Assumes self is an integer."""
2913 if not self or self._exp > 0:
2915 return self._int[-1+self._exp] in '02468'
2917 def adjusted(self):
2918 """Return the adjusted exponent of self"""
2920 return self._exp + len(self._int) - 1
2921 # If NaN or Infinity, self._exp is string
2925 def canonical(self):
2931 return self
2933 def compare_signal(self, other, context=None):
2934 """Compares self to the other operand numerically.
2940 ans = self._compare_check_nans(other, context)
2943 return self.compare(other, context=context)
2945 def compare_total(self, other, context=None):
2946 """Compares self to other using the abstract representations.
2955 if self._sign and not other._sign:
2957 if not self._sign and other._sign:
2959 sign = self._sign
2962 self_nan = self._isnan()
2967 self_key = len(self._int), self._int
3000 if self < other:
3002 if self > other:
3005 if self._exp < other._exp:
3010 if self._exp > other._exp:
3018 def compare_total_mag(self, other, context=None):
3019 """Compares self to other using abstract repr., ignoring sign.
3025 s = self.copy_abs()
3029 def copy_abs(self):
3031 return _dec_from_triple(0, self._int, self._exp, self._is_special)
3033 def copy_negate(self):
3035 if self._sign:
3036 return _dec_from_triple(0, self._int, self._exp, self._is_special)
3038 return _dec_from_triple(1, self._int, self._exp, self._is_special)
3040 def copy_sign(self, other, context=None):
3041 """Returns self with the sign of other."""
3043 return _dec_from_triple(other._sign, self._int,
3044 self._exp, self._is_special)
3046 def exp(self, context=None):
3047 """Returns e ** self."""
3053 ans = self._check_nans(context=context)
3058 if self._isinfinity() == -1:
3062 if not self:
3066 if self._isinfinity() == 1:
3067 return Decimal(self)
3074 adj = self.adjusted()
3081 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
3084 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
3087 elif self._sign == 0 and adj < -p:
3090 elif self._sign == 1 and adj < -p-1:
3095 op = _WorkRep(self)
3121 def is_canonical(self):
3122 """Return True if self is canonical; otherwise return False.
3129 def is_finite(self):
3130 """Return True if self is finite; otherwise return False.
3135 return not self._is_special
3137 def is_infinite(self):
3138 """Return True if self is infinite; otherwise return False."""
3139 return self._exp == 'F'
3141 def is_nan(self):
3142 """Return True if self is a qNaN or sNaN; otherwise return False."""
3143 return self._exp in ('n', 'N')
3145 def is_normal(self, context=None):
3146 """Return True if self is a normal number; otherwise return False."""
3147 if self._is_special or not self:
3151 return context.Emin <= self.adjusted()
3153 def is_qnan(self):
3154 """Return True if self is a quiet NaN; otherwise return False."""
3155 return self._exp == 'n'
3157 def is_signed(self):
3158 """Return True if self is negative; otherwise return False."""
3159 return self._sign == 1
3161 def is_snan(self):
3162 """Return True if self is a signaling NaN; otherwise return False."""
3163 return self._exp == 'N'
3165 def is_subnormal(self, context=None):
3166 """Return True if self is subnormal; otherwise return False."""
3167 if self._is_special or not self:
3171 return self.adjusted() < context.Emin
3173 def is_zero(self):
3174 """Return True if self is a zero; otherwise return False."""
3175 return not self._is_special and self._int == '0'
3177 def _ln_exp_bound(self):
3178 """Compute a lower bound for the adjusted exponent of self.ln().
3179 In other words, compute r such that self.ln() >= 10**r. Assumes
3180 that self is finite and positive and that self != 1.
3184 adj = self._exp + len(self._int) - 1
3191 op = _WorkRep(self)
3194 # 1 < self < 10
3198 # adj == -1, 0.1 <= self < 1
3202 def ln(self, context=None):
3203 """Returns the natural (base e) logarithm of self."""
3209 ans = self._check_nans(context=context)
3214 if not self:
3218 if self._isinfinity() == 1:
3222 if self == _One:
3226 if self._sign == 1:
3231 op = _WorkRep(self)
3237 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3252 def _log10_exp_bound(self):
3253 """Compute a lower bound for the adjusted exponent of self.log10().
3254 In other words, find r such that self.log10() >= 10**r.
3255 Assumes that self is finite and positive and that self != 1.
3259 # part of log10(self), and this comes directly from the
3264 adj = self._exp + len(self._int) - 1
3266 # self >= 10
3269 # self < 0.1
3271 op = _WorkRep(self)
3274 # 1 < self < 10
3278 # adj == -1, 0.1 <= self < 1
3282 def log10(self, context=None):
3283 """Returns the base 10 logarithm of self."""
3289 ans = self._check_nans(context=context)
3294 if not self:
3298 if self._isinfinity() == 1:
3302 if self._sign == 1:
3307 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
3309 ans = Decimal(self._exp + len(self._int) - 1)
3312 op = _WorkRep(self)
3318 places = p-self._log10_exp_bound()+2
3333 def logb(self, context=None):
3334 """ Returns the exponent of the magnitude of self's MSD.
3337 of the most significant digit of self (as though it were truncated
3342 ans = self._check_nans(context=context)
3350 if self._isinfinity():
3354 if not self:
3357 # otherwise, simply return the adjusted exponent of self, as a
3360 ans = Decimal(self.adjusted())
3363 def _islogical(self):
3364 """Return True if self is a logical operand.
3370 if self._sign != 0 or self._exp != 0:
3372 for dig in self._int:
3377 def _fill_logical(self, context, opa, opb):
3390 def logical_and(self, other, context=None):
3391 """Applies an 'and' operation between self and other's digits."""
3397 if not self._islogical() or not other._islogical():
3401 (opa, opb) = self._fill_logical(context, self._int, other._int)
3407 def logical_invert(self, context=None):
3411 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3414 def logical_or(self, other, context=None):
3415 """Applies an 'or' operation between self and other's digits."""
3421 if not self._islogical() or not other._islogical():
3425 (opa, opb) = self._fill_logical(context, self._int, other._int)
3431 def logical_xor(self, other, context=None):
3432 """Applies an 'xor' operation between self and other's digits."""
3438 if not self._islogical() or not other._islogical():
3442 (opa, opb) = self._fill_logical(context, self._int, other._int)
3448 def max_mag(self, other, context=None):
3455 if self._is_special or other._is_special:
3458 sn = self._isnan()
3462 return self._fix(context)
3465 return self._check_nans(other, context)
3467 c = self.copy_abs()._cmp(other.copy_abs())
3469 c = self.compare_total(other)
3474 ans = self
3478 def min_mag(self, other, context=None):
3485 if self._is_special or other._is_special:
3488 sn = self._isnan()
3492 return self._fix(context)
3495 return self._check_nans(other, context)
3497 c = self.copy_abs()._cmp(other.copy_abs())
3499 c = self.compare_total(other)
3502 ans = self
3508 def next_minus(self, context=None):
3513 ans = self._check_nans(context=context)
3517 if self._isinfinity() == -1:
3519 if self._isinfinity() == 1:
3525 new_self = self._fix(context)
3526 if new_self != self:
3528 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3531 def next_plus(self, context=None):
3536 ans = self._check_nans(context=context)
3540 if self._isinfinity() == 1:
3542 if self._isinfinity() == -1:
3548 new_self = self._fix(context)
3549 if new_self != self:
3551 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3554 def next_toward(self, other, context=None):
3555 """Returns the number closest to self, in the direction towards other.
3557 The result is the closest representable number to self
3558 (excluding self) that is in the direction towards other,
3560 numerically equal, then the result is a copy of self with the
3568 ans = self._check_nans(other, context)
3572 comparison = self._cmp(other)
3574 return self.copy_sign(other)
3577 ans = self.next_plus(context)
3579 ans = self.next_minus(context)
3600 def number_class(self, context=None):
3601 """Returns an indication of the class of self.
3615 if self.is_snan():
3617 if self.is_qnan():
3619 inf = self._isinfinity()
3624 if self.is_zero():
3625 if self._sign:
3631 if self.is_subnormal(context=context):
3632 if self._sign:
3637 if self._sign:
3642 def radix(self):
3646 def rotate(self, other, context=None):
3647 """Returns a rotated copy of self, value-of-other times."""
3653 ans = self._check_nans(other, context)
3662 if self._isinfinity():
3663 return Decimal(self)
3667 rotdig = self._int
3676 return _dec_from_triple(self._sign,
3677 rotated.lstrip('0') or '0', self._exp)
3679 def scaleb(self, other, context=None):
3680 """Returns self operand after adding the second value to its exp."""
3686 ans = self._check_nans(other, context)
3697 if self._isinfinity():
3698 return Decimal(self)
3700 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
3704 def shift(self, other, context=None):
3705 """Returns a shifted copy of self, value-of-other times."""
3711 ans = self._check_nans(other, context)
3720 if self._isinfinity():
3721 return Decimal(self)
3725 rotdig = self._int
3739 return _dec_from_triple(self._sign,
3740 shifted.lstrip('0') or '0', self._exp)
3743 def __reduce__(self):
3744 return (self.__class__, (str(self),))
3746 def __copy__(self):
3747 if type(self) is Decimal:
3748 return self # I'm immutable; therefore I am my own clone
3749 return self.__class__(str(self))
3751 def __deepcopy__(self, memo):
3752 if type(self) is Decimal:
3753 return self # My components are also immutable
3754 return self.__class__(str(self))
3758 def __format__(self, specifier, context=None, _localeconv=None):
3779 if self._is_special:
3780 sign = _format_sign(self._sign, spec)
3781 body = str(self.copy_abs())
3790 # if type is '%', adjust exponent of self accordingly
3792 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3799 self = self._round(precision+1, rounding)
3801 self = self._rescale(-precision, rounding)
3802 elif spec['type'] in 'gG' and len(self._int) > precision:
3803 self = self._round(precision, rounding)
3806 if not self and self._exp > 0 and spec['type'] in 'fF%':
3807 self = self._rescale(0, rounding)
3808 if not self and spec['no_neg_0'] and self._sign:
3811 adjusted_sign = self._sign
3814 leftdigits = self._exp + len(self._int)
3816 if not self and precision is not None:
3823 if self._exp <= 0 and leftdigits > -6:
3831 fracpart = '0'*(-dotplace) + self._int
3832 elif dotplace > len(self._int):
3833 intpart = self._int + '0'*(dotplace-len(self._int))
3836 intpart = self._int[:dotplace] or '0'
3837 fracpart = self._int[dotplace:]
3852 self = object.__new__(Decimal)
3853 self._sign = sign
3854 self._int = coefficient
3855 self._exp = exponent
3856 self._is_special = special
3858 return self
3874 def __init__(self, new_context):
3875 self.new_context = new_context.copy()
3876 def __enter__(self):
3877 self.saved_context = getcontext()
3878 setcontext(self.new_context)
3879 return self.new_context
3880 def __exit__(self, t, v, tb):
3881 setcontext(self.saved_context)
3902 def __init__(self, prec=None, rounding=None, Emin=None, Emax=None,
3912 self.prec = prec if prec is not None else dc.prec
3913 self.rounding = rounding if rounding is not None else dc.rounding
3914 self.Emin = Emin if Emin is not None else dc.Emin
3915 self.Emax = Emax if Emax is not None else dc.Emax
3916 self.capitals = capitals if capitals is not None else dc.capitals
3917 self.clamp = clamp if clamp is not None else dc.clamp
3920 self._ignored_flags = []
3922 self._ignored_flags = _ignored_flags
3925 self.traps = dc.traps.copy()
3927 self.traps = dict((s, int(s in traps)) for s in _signals + traps)
3929 self.traps = traps
3932 self.flags = dict.fromkeys(_signals, 0)
3934 self.flags = dict((s, int(s in flags)) for s in _signals + flags)
3936 self.flags = flags
3938 def _set_integer_check(self, name, value, vmin, vmax):
3950 return object.__setattr__(self, name, value)
3952 def _set_signal_dict(self, name, d):
3961 return object.__setattr__(self, name, d)
3963 def __setattr__(self, name, value):
3965 return self._set_integer_check(name, value, 1, 'inf')
3967 return self._set_integer_check(name, value, '-inf', 0)
3969 return self._set_integer_check(name, value, 0, 'inf')
3971 return self._set_integer_check(name, value, 0, 1)
3973 return self._set_integer_check(name, value, 0, 1)
3979 return object.__setattr__(self, name, value)
3981 return self._set_signal_dict(name, value)
3983 return object.__setattr__(self, name, value)
3988 def __delattr__(self, name):
3992 def __reduce__(self):
3993 flags = [sig for sig, v in self.flags.items() if v]
3994 traps = [sig for sig, v in self.traps.items() if v]
3995 return (self.__class__,
3996 (self.prec, self.rounding, self.Emin, self.Emax,
3997 self.capitals, self.clamp, flags, traps))
3999 def __repr__(self):
4005 % vars(self))
4006 names = [f.__name__ for f, v in self.flags.items() if v]
4008 names = [t.__name__ for t, v in self.traps.items() if v]
4012 def clear_flags(self):
4014 for flag in self.flags:
4015 self.flags[flag] = 0
4017 def clear_traps(self):
4019 for flag in self.traps:
4020 self.traps[flag] = 0
4022 def _shallow_copy(self):
4023 """Returns a shallow copy from self."""
4024 nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
4025 self.capitals, self.clamp, self.flags, self.traps,
4026 self._ignored_flags)
4029 def copy(self):
4030 """Returns a deep copy from self."""
4031 nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
4032 self.capitals, self.clamp,
4033 self.flags.copy(), self.traps.copy(),
4034 self._ignored_flags)
4038 def _raise_error(self, condition, explanation = None, *args):
4047 if error in self._ignored_flags:
4049 return error().handle(self, *args)
4051 self.flags[error] = 1
4052 if not self.traps[error]:
4054 return condition().handle(self, *args)
4057 # self._ignored_flags = []
4060 def _ignore_all_flags(self):
4062 return self._ignore_flags(*_signals)
4064 def _ignore_flags(self, *flags):
4068 self._ignored_flags = (self._ignored_flags + list(flags))
4071 def _regard_flags(self, *flags):
4076 self._ignored_flags.remove(flag)
4081 def Etiny(self):
4083 return int(self.Emin - self.prec + 1)
4085 def Etop(self):
4087 return int(self.Emax - self.prec + 1)
4089 def _set_rounding(self, type):
4099 val = self.__sub__(other, context=context)
4104 rounding = self.rounding
4105 self.rounding = type
4108 def create_decimal(self, num='0'):
4109 """Creates a new Decimal instance but using self as context.
4115 return self._raise_error(ConversionSyntax,
4119 d = Decimal(num, context=self)
4120 if d._isnan() and len(d._int) > self.prec - self.clamp:
4121 return self._raise_error(ConversionSyntax,
4123 return d._fix(self)
4125 def create_decimal_from_float(self, f):
4126 """Creates a new Decimal instance from a float but rounding using self
4140 return d._fix(self) # Apply the context rounding
4143 def abs(self, a):
4162 return a.__abs__(context=self)
4164 def add(self, a, b):
4179 r = a.__add__(b, context=self)
4185 def _apply(self, a):
4186 return str(a._fix(self))
4188 def canonical(self, a):
4201 def compare(self, a, b):
4235 return a.compare(b, context=self)
4237 def compare_signal(self, a, b):
4270 return a.compare_signal(b, context=self)
4272 def compare_total(self, a, b):
4301 def compare_total_mag(self, a, b):
4309 def copy_abs(self, a):
4322 def copy_decimal(self, a):
4335 def copy_negate(self, a):
4348 def copy_sign(self, a, b):
4372 def divide(self, a, b):
4403 r = a.__truediv__(b, context=self)
4409 def divide_int(self, a, b):
4426 r = a.__floordiv__(b, context=self)
4432 def divmod(self, a, b):
4447 r = a.__divmod__(b, context=self)
4453 def exp(self, a):
4475 return a.exp(context=self)
4477 def fma(self, a, b, c):
4498 return a.fma(b, c, context=self)
4500 def is_canonical(self, a):
4513 def is_finite(self, a):
4535 def is_infinite(self, a):
4550 def is_nan(self, a):
4566 def is_normal(self, a):
4587 return a.is_normal(context=self)
4589 def is_qnan(self, a):
4604 def is_signed(self, a):
4621 def is_snan(self, a):
4637 def is_subnormal(self, a):
4657 return a.is_subnormal(context=self)
4659 def is_zero(self, a):
4676 def ln(self, a):
4696 return a.ln(context=self)
4698 def log10(self, a):
4724 return a.log10(context=self)
4726 def logb(self, a):
4750 return a.logb(context=self)
4752 def logical_and(self, a, b):
4777 return a.logical_and(b, context=self)
4779 def logical_invert(self, a):
4796 return a.logical_invert(context=self)
4798 def logical_or(self, a, b):
4823 return a.logical_or(b, context=self)
4825 def logical_xor(self, a, b):
4850 return a.logical_xor(b, context=self)
4852 def max(self, a, b):
4877 return a.max(b, context=self)
4879 def max_mag(self, a, b):
4894 return a.max_mag(b, context=self)
4896 def min(self, a, b):
4921 return a.min(b, context=self)
4923 def min_mag(self, a, b):
4938 return a.min_mag(b, context=self)
4940 def minus(self, a):
4955 return a.__neg__(context=self)
4957 def multiply(self, a, b):
4983 r = a.__mul__(b, context=self)
4989 def next_minus(self, a):
5007 return a.next_minus(context=self)
5009 def next_plus(self, a):
5027 return a.next_plus(context=self)
5029 def next_toward(self, a, b):
5062 return a.next_toward(b, context=self)
5064 def normalize(self, a):
5086 return a.normalize(context=self)
5088 def number_class(self, a):
5136 return a.number_class(context=self)
5138 def plus(self, a):
5153 return a.__pos__(context=self)
5155 def power(self, a, b, modulo=None):
5229 r = a.__pow__(b, modulo, context=self)
5235 def quantize(self, a, b):
5291 return a.quantize(b, context=self)
5293 def radix(self):
5301 def remainder(self, a, b):
5333 r = a.__mod__(b, context=self)
5339 def remainder_near(self, a, b):
5371 return a.remainder_near(b, context=self)
5373 def rotate(self, a, b):
5400 return a.rotate(b, context=self)
5402 def same_quantum(self, a, b):
5426 def scaleb (self, a, b):
5443 return a.scaleb(b, context=self)
5445 def shift(self, a, b):
5473 return a.shift(b, context=self)
5475 def sqrt(self, a):
5505 return a.sqrt(context=self)
5507 def subtract(self, a, b):
5524 r = a.__sub__(b, context=self)
5530 def to_eng_string(self, a):
5556 return a.to_eng_string(context=self)
5558 def to_sci_string(self, a):
5564 return a.__str__(context=self)
5566 def to_integral_exact(self, a):
5594 return a.to_integral_exact(context=self)
5596 def to_integral_value(self, a):
5623 return a.to_integral_value(context=self)
5634 def __init__(self, value=None):
5636 self.sign = None
5637 self.int = 0
5638 self.exp = None
5640 self.sign = value._sign
5641 self.int = int(value._int)
5642 self.exp = value._exp
5645 self.sign = value[0]
5646 self.int = value[1]
5647 self.exp = value[2]
5649 def __repr__(self):
5650 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5868 def __init__(self):
5869 self.digits = "23025850929940456840179914546843642076011014886"
5871 def getdigits(self, p):
5874 For example, self.getdigits(3) returns 2302.
5883 if p >= len(self.digits):
5896 self.digits = digits.rstrip('0')[:-1]
5897 return int(self.digits[:p+1])
6046 def _convert_for_comparison(self, other, equality_op=False):
6047 """Given a Decimal instance self and a Python object other, return
6049 equivalent to "self op other" for any of the 6 comparison
6054 return self, other
6057 # self op n/d <=> self*d op n (for n and d integers, d positive).
6061 if not self._is_special:
6062 self = _dec_from_triple(self._sign,
6063 str(int(self._int) * other.denominator),
6064 self._exp)
6065 return self, Decimal(other.numerator)
6079 return self, Decimal.from_float(other)