NovaBryan/EVE_Dump
Log | Files | 📦 下载最新源码 (.zip) | Refs | README

decimal.py (102228B)


      1 #Embedded file name: C:\BuildAgent\work\20d73f1b24eed06e\eve\release\V24.01\carbon\common\stdlib\decimal.py
      2 __all__ = ['Decimal',
      3  'Context',
      4  'DefaultContext',
      5  'BasicContext',
      6  'ExtendedContext',
      7  'DecimalException',
      8  'Clamped',
      9  'InvalidOperation',
     10  'DivisionByZero',
     11  'Inexact',
     12  'Rounded',
     13  'Subnormal',
     14  'Overflow',
     15  'Underflow',
     16  'ROUND_DOWN',
     17  'ROUND_HALF_UP',
     18  'ROUND_HALF_EVEN',
     19  'ROUND_CEILING',
     20  'ROUND_FLOOR',
     21  'ROUND_UP',
     22  'ROUND_HALF_DOWN',
     23  'ROUND_05UP',
     24  'setcontext',
     25  'getcontext',
     26  'localcontext']
     27 __version__ = '1.70'
     28 import copy as _copy
     29 import math as _math
     30 import numbers as _numbers
     31 try:
     32     from collections import namedtuple as _namedtuple
     33     DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
     34 except ImportError:
     35     DecimalTuple = lambda *args: args
     36 
     37 ROUND_DOWN = 'ROUND_DOWN'
     38 ROUND_HALF_UP = 'ROUND_HALF_UP'
     39 ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
     40 ROUND_CEILING = 'ROUND_CEILING'
     41 ROUND_FLOOR = 'ROUND_FLOOR'
     42 ROUND_UP = 'ROUND_UP'
     43 ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
     44 ROUND_05UP = 'ROUND_05UP'
     45 
     46 class DecimalException(ArithmeticError):
     47 
     48     def handle(self, context, *args):
     49         pass
     50 
     51 
     52 class Clamped(DecimalException):
     53     pass
     54 
     55 
     56 class InvalidOperation(DecimalException):
     57 
     58     def handle(self, context, *args):
     59         if args:
     60             ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
     61             return ans._fix_nan(context)
     62         return _NaN
     63 
     64 
     65 class ConversionSyntax(InvalidOperation):
     66 
     67     def handle(self, context, *args):
     68         return _NaN
     69 
     70 
     71 class DivisionByZero(DecimalException, ZeroDivisionError):
     72 
     73     def handle(self, context, sign, *args):
     74         return _SignedInfinity[sign]
     75 
     76 
     77 class DivisionImpossible(InvalidOperation):
     78 
     79     def handle(self, context, *args):
     80         return _NaN
     81 
     82 
     83 class DivisionUndefined(InvalidOperation, ZeroDivisionError):
     84 
     85     def handle(self, context, *args):
     86         return _NaN
     87 
     88 
     89 class Inexact(DecimalException):
     90     pass
     91 
     92 
     93 class InvalidContext(InvalidOperation):
     94 
     95     def handle(self, context, *args):
     96         return _NaN
     97 
     98 
     99 class Rounded(DecimalException):
    100     pass
    101 
    102 
    103 class Subnormal(DecimalException):
    104     pass
    105 
    106 
    107 class Overflow(Inexact, Rounded):
    108 
    109     def handle(self, context, sign, *args):
    110         if context.rounding in (ROUND_HALF_UP,
    111          ROUND_HALF_EVEN,
    112          ROUND_HALF_DOWN,
    113          ROUND_UP):
    114             return _SignedInfinity[sign]
    115         if sign == 0:
    116             if context.rounding == ROUND_CEILING:
    117                 return _SignedInfinity[sign]
    118             return _dec_from_triple(sign, '9' * context.prec, context.Emax - context.prec + 1)
    119         if sign == 1:
    120             if context.rounding == ROUND_FLOOR:
    121                 return _SignedInfinity[sign]
    122             return _dec_from_triple(sign, '9' * context.prec, context.Emax - context.prec + 1)
    123 
    124 
    125 class Underflow(Inexact, Rounded, Subnormal):
    126     pass
    127 
    128 
    129 _signals = [Clamped,
    130  DivisionByZero,
    131  Inexact,
    132  Overflow,
    133  Rounded,
    134  Underflow,
    135  InvalidOperation,
    136  Subnormal]
    137 _condition_map = {ConversionSyntax: InvalidOperation,
    138  DivisionImpossible: InvalidOperation,
    139  DivisionUndefined: InvalidOperation,
    140  InvalidContext: InvalidOperation}
    141 try:
    142     import threading
    143 except ImportError:
    144     import sys
    145 
    146     class MockThreading(object):
    147 
    148         def local(self, sys = sys):
    149             return sys.modules[__name__]
    150 
    151 
    152     threading = MockThreading()
    153     del sys
    154     del MockThreading
    155 
    156 try:
    157     threading.local
    158 except AttributeError:
    159     if hasattr(threading.currentThread(), '__decimal_context__'):
    160         del threading.currentThread().__decimal_context__
    161 
    162     def setcontext(context):
    163         if context in (DefaultContext, BasicContext, ExtendedContext):
    164             context = context.copy()
    165             context.clear_flags()
    166         threading.currentThread().__decimal_context__ = context
    167 
    168 
    169     def getcontext():
    170         try:
    171             return threading.currentThread().__decimal_context__
    172         except AttributeError:
    173             context = Context()
    174             threading.currentThread().__decimal_context__ = context
    175             return context
    176 
    177 
    178 else:
    179     local = threading.local()
    180     if hasattr(local, '__decimal_context__'):
    181         del local.__decimal_context__
    182 
    183     def getcontext(_local = local):
    184         try:
    185             return _local.__decimal_context__
    186         except AttributeError:
    187             context = Context()
    188             _local.__decimal_context__ = context
    189             return context
    190 
    191 
    192     def setcontext(context, _local = local):
    193         if context in (DefaultContext, BasicContext, ExtendedContext):
    194             context = context.copy()
    195             context.clear_flags()
    196         _local.__decimal_context__ = context
    197 
    198 
    199     del threading
    200     del local
    201 
    202 def localcontext(ctx = None):
    203     if ctx is None:
    204         ctx = getcontext()
    205     return _ContextManager(ctx)
    206 
    207 
    208 class Decimal(object):
    209     __slots__ = ('_exp', '_int', '_sign', '_is_special')
    210 
    211     def __new__(cls, value = '0', context = None):
    212         self = object.__new__(cls)
    213         if isinstance(value, basestring):
    214             m = _parser(value.strip())
    215             if m is None:
    216                 if context is None:
    217                     context = getcontext()
    218                 return context._raise_error(ConversionSyntax, 'Invalid literal for Decimal: %r' % value)
    219             if m.group('sign') == '-':
    220                 self._sign = 1
    221             else:
    222                 self._sign = 0
    223             intpart = m.group('int')
    224             if intpart is not None:
    225                 fracpart = m.group('frac') or ''
    226                 exp = int(m.group('exp') or '0')
    227                 self._int = str(int(intpart + fracpart))
    228                 self._exp = exp - len(fracpart)
    229                 self._is_special = False
    230             else:
    231                 diag = m.group('diag')
    232                 if diag is not None:
    233                     self._int = str(int(diag or '0')).lstrip('0')
    234                     if m.group('signal'):
    235                         self._exp = 'N'
    236                     else:
    237                         self._exp = 'n'
    238                 else:
    239                     self._int = '0'
    240                     self._exp = 'F'
    241                 self._is_special = True
    242             return self
    243         if isinstance(value, (int, long)):
    244             if value >= 0:
    245                 self._sign = 0
    246             else:
    247                 self._sign = 1
    248             self._exp = 0
    249             self._int = str(abs(value))
    250             self._is_special = False
    251             return self
    252         if isinstance(value, Decimal):
    253             self._exp = value._exp
    254             self._sign = value._sign
    255             self._int = value._int
    256             self._is_special = value._is_special
    257             return self
    258         if isinstance(value, _WorkRep):
    259             self._sign = value.sign
    260             self._int = str(value.int)
    261             self._exp = int(value.exp)
    262             self._is_special = False
    263             return self
    264         if isinstance(value, (list, tuple)):
    265             if len(value) != 3:
    266                 raise ValueError('Invalid tuple size in creation of Decimal from list or tuple.  The list or tuple should have exactly three elements.')
    267             if not (isinstance(value[0], (int, long)) and value[0] in (0, 1)):
    268                 raise ValueError('Invalid sign.  The first value in the tuple should be an integer; either 0 for a positive number or 1 for a negative number.')
    269             self._sign = value[0]
    270             if value[2] == 'F':
    271                 self._int = '0'
    272                 self._exp = value[2]
    273                 self._is_special = True
    274             else:
    275                 digits = []
    276                 for digit in value[1]:
    277                     if isinstance(digit, (int, long)) and 0 <= digit <= 9:
    278                         if digits or digit != 0:
    279                             digits.append(digit)
    280                     else:
    281                         raise ValueError('The second value in the tuple must be composed of integers in the range 0 through 9.')
    282 
    283                 if value[2] in ('n', 'N'):
    284                     self._int = ''.join(map(str, digits))
    285                     self._exp = value[2]
    286                     self._is_special = True
    287                 elif isinstance(value[2], (int, long)):
    288                     self._int = ''.join(map(str, digits or [0]))
    289                     self._exp = value[2]
    290                     self._is_special = False
    291                 else:
    292                     raise ValueError("The third value in the tuple must be an integer, or one of the strings 'F', 'n', 'N'.")
    293             return self
    294         if isinstance(value, float):
    295             value = Decimal.from_float(value)
    296             self._exp = value._exp
    297             self._sign = value._sign
    298             self._int = value._int
    299             self._is_special = value._is_special
    300             return self
    301         raise TypeError('Cannot convert %r to Decimal' % value)
    302 
    303     def from_float(cls, f):
    304         if isinstance(f, (int, long)):
    305             return cls(f)
    306         elif _math.isinf(f) or _math.isnan(f):
    307             return cls(repr(f))
    308         if _math.copysign(1.0, f) == 1.0:
    309             sign = 0
    310         else:
    311             sign = 1
    312         n, d = abs(f).as_integer_ratio()
    313         k = d.bit_length() - 1
    314         result = _dec_from_triple(sign, str(n * 5 ** k), -k)
    315         if cls is Decimal:
    316             return result
    317         else:
    318             return cls(result)
    319 
    320     from_float = classmethod(from_float)
    321 
    322     def _isnan(self):
    323         if self._is_special:
    324             exp = self._exp
    325             if exp == 'n':
    326                 return 1
    327             if exp == 'N':
    328                 return 2
    329         return 0
    330 
    331     def _isinfinity(self):
    332         if self._exp == 'F':
    333             if self._sign:
    334                 return -1
    335             return 1
    336         return 0
    337 
    338     def _check_nans(self, other = None, context = None):
    339         self_is_nan = self._isnan()
    340         if other is None:
    341             other_is_nan = False
    342         else:
    343             other_is_nan = other._isnan()
    344         if self_is_nan or other_is_nan:
    345             if context is None:
    346                 context = getcontext()
    347             if self_is_nan == 2:
    348                 return context._raise_error(InvalidOperation, 'sNaN', self)
    349             if other_is_nan == 2:
    350                 return context._raise_error(InvalidOperation, 'sNaN', other)
    351             if self_is_nan:
    352                 return self._fix_nan(context)
    353             return other._fix_nan(context)
    354         return 0
    355 
    356     def _compare_check_nans(self, other, context):
    357         if context is None:
    358             context = getcontext()
    359         if self._is_special or other._is_special:
    360             if self.is_snan():
    361                 return context._raise_error(InvalidOperation, 'comparison involving sNaN', self)
    362             if other.is_snan():
    363                 return context._raise_error(InvalidOperation, 'comparison involving sNaN', other)
    364             if self.is_qnan():
    365                 return context._raise_error(InvalidOperation, 'comparison involving NaN', self)
    366             if other.is_qnan():
    367                 return context._raise_error(InvalidOperation, 'comparison involving NaN', other)
    368         return 0
    369 
    370     def __nonzero__(self):
    371         return self._is_special or self._int != '0'
    372 
    373     def _cmp(self, other):
    374         if self._is_special or other._is_special:
    375             self_inf = self._isinfinity()
    376             other_inf = other._isinfinity()
    377             if self_inf == other_inf:
    378                 return 0
    379             elif self_inf < other_inf:
    380                 return -1
    381             else:
    382                 return 1
    383         if not self:
    384             if not other:
    385                 return 0
    386             else:
    387                 return -(-1) ** other._sign
    388         if not other:
    389             return (-1) ** self._sign
    390         if other._sign < self._sign:
    391             return -1
    392         if self._sign < other._sign:
    393             return 1
    394         self_adjusted = self.adjusted()
    395         other_adjusted = other.adjusted()
    396         if self_adjusted == other_adjusted:
    397             self_padded = self._int + '0' * (self._exp - other._exp)
    398             other_padded = other._int + '0' * (other._exp - self._exp)
    399             if self_padded == other_padded:
    400                 return 0
    401             elif self_padded < other_padded:
    402                 return -(-1) ** self._sign
    403             else:
    404                 return (-1) ** self._sign
    405         else:
    406             if self_adjusted > other_adjusted:
    407                 return (-1) ** self._sign
    408             return -(-1) ** self._sign
    409 
    410     def __eq__(self, other, context = None):
    411         other = _convert_other(other, allow_float=True)
    412         if other is NotImplemented:
    413             return other
    414         if self._check_nans(other, context):
    415             return False
    416         return self._cmp(other) == 0
    417 
    418     def __ne__(self, other, context = None):
    419         other = _convert_other(other, allow_float=True)
    420         if other is NotImplemented:
    421             return other
    422         if self._check_nans(other, context):
    423             return True
    424         return self._cmp(other) != 0
    425 
    426     def __lt__(self, other, context = None):
    427         other = _convert_other(other, allow_float=True)
    428         if other is NotImplemented:
    429             return other
    430         ans = self._compare_check_nans(other, context)
    431         if ans:
    432             return False
    433         return self._cmp(other) < 0
    434 
    435     def __le__(self, other, context = None):
    436         other = _convert_other(other, allow_float=True)
    437         if other is NotImplemented:
    438             return other
    439         ans = self._compare_check_nans(other, context)
    440         if ans:
    441             return False
    442         return self._cmp(other) <= 0
    443 
    444     def __gt__(self, other, context = None):
    445         other = _convert_other(other, allow_float=True)
    446         if other is NotImplemented:
    447             return other
    448         ans = self._compare_check_nans(other, context)
    449         if ans:
    450             return False
    451         return self._cmp(other) > 0
    452 
    453     def __ge__(self, other, context = None):
    454         other = _convert_other(other, allow_float=True)
    455         if other is NotImplemented:
    456             return other
    457         ans = self._compare_check_nans(other, context)
    458         if ans:
    459             return False
    460         return self._cmp(other) >= 0
    461 
    462     def compare(self, other, context = None):
    463         other = _convert_other(other, raiseit=True)
    464         if self._is_special or other and other._is_special:
    465             ans = self._check_nans(other, context)
    466             if ans:
    467                 return ans
    468         return Decimal(self._cmp(other))
    469 
    470     def __hash__(self):
    471         if self._is_special:
    472             if self.is_snan():
    473                 raise TypeError('Cannot hash a signaling NaN value.')
    474             elif self.is_nan():
    475                 return 0
    476             elif self._sign:
    477                 return -271828
    478             else:
    479                 return 314159
    480         self_as_float = float(self)
    481         if Decimal.from_float(self_as_float) == self:
    482             return hash(self_as_float)
    483         if self._isinteger():
    484             op = _WorkRep(self.to_integral_value())
    485             return hash((-1) ** op.sign * op.int * pow(10, op.exp, 18446744073709551615L))
    486         return hash((self._sign, self._exp + len(self._int), self._int.rstrip('0')))
    487 
    488     def as_tuple(self):
    489         return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
    490 
    491     def __repr__(self):
    492         return "Decimal('%s')" % str(self)
    493 
    494     def __str__(self, eng = False, context = None):
    495         sign = ['', '-'][self._sign]
    496         if self._is_special:
    497             if self._exp == 'F':
    498                 return sign + 'Infinity'
    499             elif self._exp == 'n':
    500                 return sign + 'NaN' + self._int
    501             else:
    502                 return sign + 'sNaN' + self._int
    503         leftdigits = self._exp + len(self._int)
    504         if self._exp <= 0 and leftdigits > -6:
    505             dotplace = leftdigits
    506         elif not eng:
    507             dotplace = 1
    508         elif self._int == '0':
    509             dotplace = (leftdigits + 1) % 3 - 1
    510         else:
    511             dotplace = (leftdigits - 1) % 3 + 1
    512         if dotplace <= 0:
    513             intpart = '0'
    514             fracpart = '.' + '0' * -dotplace + self._int
    515         elif dotplace >= len(self._int):
    516             intpart = self._int + '0' * (dotplace - len(self._int))
    517             fracpart = ''
    518         else:
    519             intpart = self._int[:dotplace]
    520             fracpart = '.' + self._int[dotplace:]
    521         if leftdigits == dotplace:
    522             exp = ''
    523         else:
    524             if context is None:
    525                 context = getcontext()
    526             exp = ['e', 'E'][context.capitals] + '%+d' % (leftdigits - dotplace)
    527         return sign + intpart + fracpart + exp
    528 
    529     def to_eng_string(self, context = None):
    530         return self.__str__(eng=True, context=context)
    531 
    532     def __neg__(self, context = None):
    533         if self._is_special:
    534             ans = self._check_nans(context=context)
    535             if ans:
    536                 return ans
    537         if not self:
    538             ans = self.copy_abs()
    539         else:
    540             ans = self.copy_negate()
    541         if context is None:
    542             context = getcontext()
    543         return ans._fix(context)
    544 
    545     def __pos__(self, context = None):
    546         if self._is_special:
    547             ans = self._check_nans(context=context)
    548             if ans:
    549                 return ans
    550         if not self:
    551             ans = self.copy_abs()
    552         else:
    553             ans = Decimal(self)
    554         if context is None:
    555             context = getcontext()
    556         return ans._fix(context)
    557 
    558     def __abs__(self, round = True, context = None):
    559         if not round:
    560             return self.copy_abs()
    561         if self._is_special:
    562             ans = self._check_nans(context=context)
    563             if ans:
    564                 return ans
    565         if self._sign:
    566             ans = self.__neg__(context=context)
    567         else:
    568             ans = self.__pos__(context=context)
    569         return ans
    570 
    571     def __add__(self, other, context = None):
    572         other = _convert_other(other)
    573         if other is NotImplemented:
    574             return other
    575         if context is None:
    576             context = getcontext()
    577         if self._is_special or other._is_special:
    578             ans = self._check_nans(other, context)
    579             if ans:
    580                 return ans
    581             if self._isinfinity():
    582                 if self._sign != other._sign and other._isinfinity():
    583                     return context._raise_error(InvalidOperation, '-INF + INF')
    584                 return Decimal(self)
    585             if other._isinfinity():
    586                 return Decimal(other)
    587         exp = min(self._exp, other._exp)
    588         negativezero = 0
    589         if context.rounding == ROUND_FLOOR and self._sign != other._sign:
    590             negativezero = 1
    591         if not self and not other:
    592             sign = min(self._sign, other._sign)
    593             if negativezero:
    594                 sign = 1
    595             ans = _dec_from_triple(sign, '0', exp)
    596             ans = ans._fix(context)
    597             return ans
    598         if not self:
    599             exp = max(exp, other._exp - context.prec - 1)
    600             ans = other._rescale(exp, context.rounding)
    601             ans = ans._fix(context)
    602             return ans
    603         if not other:
    604             exp = max(exp, self._exp - context.prec - 1)
    605             ans = self._rescale(exp, context.rounding)
    606             ans = ans._fix(context)
    607             return ans
    608         op1 = _WorkRep(self)
    609         op2 = _WorkRep(other)
    610         op1, op2 = _normalize(op1, op2, context.prec)
    611         result = _WorkRep()
    612         if op1.sign != op2.sign:
    613             if op1.int == op2.int:
    614                 ans = _dec_from_triple(negativezero, '0', exp)
    615                 ans = ans._fix(context)
    616                 return ans
    617             if op1.int < op2.int:
    618                 op1, op2 = op2, op1
    619             if op1.sign == 1:
    620                 result.sign = 1
    621                 op1.sign, op2.sign = op2.sign, op1.sign
    622             else:
    623                 result.sign = 0
    624         elif op1.sign == 1:
    625             result.sign = 1
    626             op1.sign, op2.sign = (0, 0)
    627         else:
    628             result.sign = 0
    629         if op2.sign == 0:
    630             result.int = op1.int + op2.int
    631         else:
    632             result.int = op1.int - op2.int
    633         result.exp = op1.exp
    634         ans = Decimal(result)
    635         ans = ans._fix(context)
    636         return ans
    637 
    638     __radd__ = __add__
    639 
    640     def __sub__(self, other, context = None):
    641         other = _convert_other(other)
    642         if other is NotImplemented:
    643             return other
    644         if self._is_special or other._is_special:
    645             ans = self._check_nans(other, context=context)
    646             if ans:
    647                 return ans
    648         return self.__add__(other.copy_negate(), context=context)
    649 
    650     def __rsub__(self, other, context = None):
    651         other = _convert_other(other)
    652         if other is NotImplemented:
    653             return other
    654         return other.__sub__(self, context=context)
    655 
    656     def __mul__(self, other, context = None):
    657         other = _convert_other(other)
    658         if other is NotImplemented:
    659             return other
    660         if context is None:
    661             context = getcontext()
    662         resultsign = self._sign ^ other._sign
    663         if self._is_special or other._is_special:
    664             ans = self._check_nans(other, context)
    665             if ans:
    666                 return ans
    667             if self._isinfinity():
    668                 if not other:
    669                     return context._raise_error(InvalidOperation, '(+-)INF * 0')
    670                 return _SignedInfinity[resultsign]
    671             if other._isinfinity():
    672                 if not self:
    673                     return context._raise_error(InvalidOperation, '0 * (+-)INF')
    674                 return _SignedInfinity[resultsign]
    675         resultexp = self._exp + other._exp
    676         if not self or not other:
    677             ans = _dec_from_triple(resultsign, '0', resultexp)
    678             ans = ans._fix(context)
    679             return ans
    680         if self._int == '1':
    681             ans = _dec_from_triple(resultsign, other._int, resultexp)
    682             ans = ans._fix(context)
    683             return ans
    684         if other._int == '1':
    685             ans = _dec_from_triple(resultsign, self._int, resultexp)
    686             ans = ans._fix(context)
    687             return ans
    688         op1 = _WorkRep(self)
    689         op2 = _WorkRep(other)
    690         ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
    691         ans = ans._fix(context)
    692         return ans
    693 
    694     __rmul__ = __mul__
    695 
    696     def __truediv__(self, other, context = None):
    697         other = _convert_other(other)
    698         if other is NotImplemented:
    699             return NotImplemented
    700         if context is None:
    701             context = getcontext()
    702         sign = self._sign ^ other._sign
    703         if self._is_special or other._is_special:
    704             ans = self._check_nans(other, context)
    705             if ans:
    706                 return ans
    707             if self._isinfinity() and other._isinfinity():
    708                 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
    709             if self._isinfinity():
    710                 return _SignedInfinity[sign]
    711             if other._isinfinity():
    712                 context._raise_error(Clamped, 'Division by infinity')
    713                 return _dec_from_triple(sign, '0', context.Etiny())
    714         if not other:
    715             if not self:
    716                 return context._raise_error(DivisionUndefined, '0 / 0')
    717             return context._raise_error(DivisionByZero, 'x / 0', sign)
    718         if not self:
    719             exp = self._exp - other._exp
    720             coeff = 0
    721         else:
    722             shift = len(other._int) - len(self._int) + context.prec + 1
    723             exp = self._exp - other._exp - shift
    724             op1 = _WorkRep(self)
    725             op2 = _WorkRep(other)
    726             if shift >= 0:
    727                 coeff, remainder = divmod(op1.int * 10 ** shift, op2.int)
    728             else:
    729                 coeff, remainder = divmod(op1.int, op2.int * 10 ** (-shift))
    730             if remainder:
    731                 if coeff % 5 == 0:
    732                     coeff += 1
    733             else:
    734                 ideal_exp = self._exp - other._exp
    735                 while exp < ideal_exp and coeff % 10 == 0:
    736                     coeff //= 10
    737                     exp += 1
    738 
    739         ans = _dec_from_triple(sign, str(coeff), exp)
    740         return ans._fix(context)
    741 
    742     def _divide(self, other, context):
    743         sign = self._sign ^ other._sign
    744         if other._isinfinity():
    745             ideal_exp = self._exp
    746         else:
    747             ideal_exp = min(self._exp, other._exp)
    748         expdiff = self.adjusted() - other.adjusted()
    749         if not self or other._isinfinity() or expdiff <= -2:
    750             return (_dec_from_triple(sign, '0', 0), self._rescale(ideal_exp, context.rounding))
    751         if expdiff <= context.prec:
    752             op1 = _WorkRep(self)
    753             op2 = _WorkRep(other)
    754             if op1.exp >= op2.exp:
    755                 op1.int *= 10 ** (op1.exp - op2.exp)
    756             else:
    757                 op2.int *= 10 ** (op2.exp - op1.exp)
    758             q, r = divmod(op1.int, op2.int)
    759             if q < 10 ** context.prec:
    760                 return (_dec_from_triple(sign, str(q), 0), _dec_from_triple(self._sign, str(r), ideal_exp))
    761         ans = context._raise_error(DivisionImpossible, 'quotient too large in //, % or divmod')
    762         return (ans, ans)
    763 
    764     def __rtruediv__(self, other, context = None):
    765         other = _convert_other(other)
    766         if other is NotImplemented:
    767             return other
    768         return other.__truediv__(self, context=context)
    769 
    770     __div__ = __truediv__
    771     __rdiv__ = __rtruediv__
    772 
    773     def __divmod__(self, other, context = None):
    774         other = _convert_other(other)
    775         if other is NotImplemented:
    776             return other
    777         if context is None:
    778             context = getcontext()
    779         ans = self._check_nans(other, context)
    780         if ans:
    781             return (ans, ans)
    782         sign = self._sign ^ other._sign
    783         if self._isinfinity():
    784             if other._isinfinity():
    785                 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
    786                 return (ans, ans)
    787             else:
    788                 return (_SignedInfinity[sign], context._raise_error(InvalidOperation, 'INF % x'))
    789         if not other:
    790             if not self:
    791                 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
    792                 return (ans, ans)
    793             else:
    794                 return (context._raise_error(DivisionByZero, 'x // 0', sign), context._raise_error(InvalidOperation, 'x % 0'))
    795         quotient, remainder = self._divide(other, context)
    796         remainder = remainder._fix(context)
    797         return (quotient, remainder)
    798 
    799     def __rdivmod__(self, other, context = None):
    800         other = _convert_other(other)
    801         if other is NotImplemented:
    802             return other
    803         return other.__divmod__(self, context=context)
    804 
    805     def __mod__(self, other, context = None):
    806         other = _convert_other(other)
    807         if other is NotImplemented:
    808             return other
    809         if context is None:
    810             context = getcontext()
    811         ans = self._check_nans(other, context)
    812         if ans:
    813             return ans
    814         if self._isinfinity():
    815             return context._raise_error(InvalidOperation, 'INF % x')
    816         if not other:
    817             if self:
    818                 return context._raise_error(InvalidOperation, 'x % 0')
    819             else:
    820                 return context._raise_error(DivisionUndefined, '0 % 0')
    821         remainder = self._divide(other, context)[1]
    822         remainder = remainder._fix(context)
    823         return remainder
    824 
    825     def __rmod__(self, other, context = None):
    826         other = _convert_other(other)
    827         if other is NotImplemented:
    828             return other
    829         return other.__mod__(self, context=context)
    830 
    831     def remainder_near(self, other, context = None):
    832         if context is None:
    833             context = getcontext()
    834         other = _convert_other(other, raiseit=True)
    835         ans = self._check_nans(other, context)
    836         if ans:
    837             return ans
    838         if self._isinfinity():
    839             return context._raise_error(InvalidOperation, 'remainder_near(infinity, x)')
    840         if not other:
    841             if self:
    842                 return context._raise_error(InvalidOperation, 'remainder_near(x, 0)')
    843             else:
    844                 return context._raise_error(DivisionUndefined, 'remainder_near(0, 0)')
    845         if other._isinfinity():
    846             ans = Decimal(self)
    847             return ans._fix(context)
    848         ideal_exponent = min(self._exp, other._exp)
    849         if not self:
    850             ans = _dec_from_triple(self._sign, '0', ideal_exponent)
    851             return ans._fix(context)
    852         expdiff = self.adjusted() - other.adjusted()
    853         if expdiff >= context.prec + 1:
    854             return context._raise_error(DivisionImpossible)
    855         if expdiff <= -2:
    856             ans = self._rescale(ideal_exponent, context.rounding)
    857             return ans._fix(context)
    858         op1 = _WorkRep(self)
    859         op2 = _WorkRep(other)
    860         if op1.exp >= op2.exp:
    861             op1.int *= 10 ** (op1.exp - op2.exp)
    862         else:
    863             op2.int *= 10 ** (op2.exp - op1.exp)
    864         q, r = divmod(op1.int, op2.int)
    865         if 2 * r + (q & 1) > op2.int:
    866             r -= op2.int
    867             q += 1
    868         if q >= 10 ** context.prec:
    869             return context._raise_error(DivisionImpossible)
    870         sign = self._sign
    871         if r < 0:
    872             sign = 1 - sign
    873             r = -r
    874         ans = _dec_from_triple(sign, str(r), ideal_exponent)
    875         return ans._fix(context)
    876 
    877     def __floordiv__(self, other, context = None):
    878         other = _convert_other(other)
    879         if other is NotImplemented:
    880             return other
    881         if context is None:
    882             context = getcontext()
    883         ans = self._check_nans(other, context)
    884         if ans:
    885             return ans
    886         if self._isinfinity():
    887             if other._isinfinity():
    888                 return context._raise_error(InvalidOperation, 'INF // INF')
    889             else:
    890                 return _SignedInfinity[self._sign ^ other._sign]
    891         if not other:
    892             if self:
    893                 return context._raise_error(DivisionByZero, 'x // 0', self._sign ^ other._sign)
    894             else:
    895                 return context._raise_error(DivisionUndefined, '0 // 0')
    896         return self._divide(other, context)[0]
    897 
    898     def __rfloordiv__(self, other, context = None):
    899         other = _convert_other(other)
    900         if other is NotImplemented:
    901             return other
    902         return other.__floordiv__(self, context=context)
    903 
    904     def __float__(self):
    905         return float(str(self))
    906 
    907     def __int__(self):
    908         if self._is_special:
    909             if self._isnan():
    910                 raise ValueError('Cannot convert NaN to integer')
    911             elif self._isinfinity():
    912                 raise OverflowError('Cannot convert infinity to integer')
    913         s = (-1) ** self._sign
    914         if self._exp >= 0:
    915             return s * int(self._int) * 10 ** self._exp
    916         else:
    917             return s * int(self._int[:self._exp] or '0')
    918 
    919     __trunc__ = __int__
    920 
    921     def real(self):
    922         return self
    923 
    924     real = property(real)
    925 
    926     def imag(self):
    927         return Decimal(0)
    928 
    929     imag = property(imag)
    930 
    931     def conjugate(self):
    932         return self
    933 
    934     def __complex__(self):
    935         return complex(float(self))
    936 
    937     def __long__(self):
    938         return long(self.__int__())
    939 
    940     def _fix_nan(self, context):
    941         payload = self._int
    942         max_payload_len = context.prec - context._clamp
    943         if len(payload) > max_payload_len:
    944             payload = payload[len(payload) - max_payload_len:].lstrip('0')
    945             return _dec_from_triple(self._sign, payload, self._exp, True)
    946         return Decimal(self)
    947 
    948     def _fix(self, context):
    949         if self._is_special:
    950             if self._isnan():
    951                 return self._fix_nan(context)
    952             else:
    953                 return Decimal(self)
    954         Etiny = context.Etiny()
    955         Etop = context.Etop()
    956         if not self:
    957             exp_max = [context.Emax, Etop][context._clamp]
    958             new_exp = min(max(self._exp, Etiny), exp_max)
    959             if new_exp != self._exp:
    960                 context._raise_error(Clamped)
    961                 return _dec_from_triple(self._sign, '0', new_exp)
    962             else:
    963                 return Decimal(self)
    964         exp_min = len(self._int) + self._exp - context.prec
    965         if exp_min > Etop:
    966             ans = context._raise_error(Overflow, 'above Emax', self._sign)
    967             context._raise_error(Inexact)
    968             context._raise_error(Rounded)
    969             return ans
    970         self_is_subnormal = exp_min < Etiny
    971         if self_is_subnormal:
    972             exp_min = Etiny
    973         if self._exp < exp_min:
    974             digits = len(self._int) + self._exp - exp_min
    975             if digits < 0:
    976                 self = _dec_from_triple(self._sign, '1', exp_min - 1)
    977                 digits = 0
    978             rounding_method = self._pick_rounding_function[context.rounding]
    979             changed = getattr(self, rounding_method)(digits)
    980             coeff = self._int[:digits] or '0'
    981             if changed > 0:
    982                 coeff = str(int(coeff) + 1)
    983                 if len(coeff) > context.prec:
    984                     coeff = coeff[:-1]
    985                     exp_min += 1
    986             if exp_min > Etop:
    987                 ans = context._raise_error(Overflow, 'above Emax', self._sign)
    988             else:
    989                 ans = _dec_from_triple(self._sign, coeff, exp_min)
    990             if changed and self_is_subnormal:
    991                 context._raise_error(Underflow)
    992             if self_is_subnormal:
    993                 context._raise_error(Subnormal)
    994             if changed:
    995                 context._raise_error(Inexact)
    996             context._raise_error(Rounded)
    997             if not ans:
    998                 context._raise_error(Clamped)
    999             return ans
   1000         if self_is_subnormal:
   1001             context._raise_error(Subnormal)
   1002         if context._clamp == 1 and self._exp > Etop:
   1003             context._raise_error(Clamped)
   1004             self_padded = self._int + '0' * (self._exp - Etop)
   1005             return _dec_from_triple(self._sign, self_padded, Etop)
   1006         return Decimal(self)
   1007 
   1008     _pick_rounding_function = {}
   1009 
   1010     def _round_down(self, prec):
   1011         if _all_zeros(self._int, prec):
   1012             return 0
   1013         else:
   1014             return -1
   1015 
   1016     def _round_up(self, prec):
   1017         return -self._round_down(prec)
   1018 
   1019     def _round_half_up(self, prec):
   1020         if self._int[prec] in '56789':
   1021             return 1
   1022         elif _all_zeros(self._int, prec):
   1023             return 0
   1024         else:
   1025             return -1
   1026 
   1027     def _round_half_down(self, prec):
   1028         if _exact_half(self._int, prec):
   1029             return -1
   1030         else:
   1031             return self._round_half_up(prec)
   1032 
   1033     def _round_half_even(self, prec):
   1034         if _exact_half(self._int, prec) and (prec == 0 or self._int[prec - 1] in '02468'):
   1035             return -1
   1036         else:
   1037             return self._round_half_up(prec)
   1038 
   1039     def _round_ceiling(self, prec):
   1040         if self._sign:
   1041             return self._round_down(prec)
   1042         else:
   1043             return -self._round_down(prec)
   1044 
   1045     def _round_floor(self, prec):
   1046         if not self._sign:
   1047             return self._round_down(prec)
   1048         else:
   1049             return -self._round_down(prec)
   1050 
   1051     def _round_05up(self, prec):
   1052         if prec and self._int[prec - 1] not in '05':
   1053             return self._round_down(prec)
   1054         else:
   1055             return -self._round_down(prec)
   1056 
   1057     def fma(self, other, third, context = None):
   1058         other = _convert_other(other, raiseit=True)
   1059         if self._is_special or other._is_special:
   1060             if context is None:
   1061                 context = getcontext()
   1062             if self._exp == 'N':
   1063                 return context._raise_error(InvalidOperation, 'sNaN', self)
   1064             if other._exp == 'N':
   1065                 return context._raise_error(InvalidOperation, 'sNaN', other)
   1066             if self._exp == 'n':
   1067                 product = self
   1068             elif other._exp == 'n':
   1069                 product = other
   1070             elif self._exp == 'F':
   1071                 if not other:
   1072                     return context._raise_error(InvalidOperation, 'INF * 0 in fma')
   1073                 product = _SignedInfinity[self._sign ^ other._sign]
   1074             elif other._exp == 'F':
   1075                 if not self:
   1076                     return context._raise_error(InvalidOperation, '0 * INF in fma')
   1077                 product = _SignedInfinity[self._sign ^ other._sign]
   1078         else:
   1079             product = _dec_from_triple(self._sign ^ other._sign, str(int(self._int) * int(other._int)), self._exp + other._exp)
   1080         third = _convert_other(third, raiseit=True)
   1081         return product.__add__(third, context)
   1082 
   1083     def _power_modulo(self, other, modulo, context = None):
   1084         other = _convert_other(other, raiseit=True)
   1085         modulo = _convert_other(modulo, raiseit=True)
   1086         if context is None:
   1087             context = getcontext()
   1088         self_is_nan = self._isnan()
   1089         other_is_nan = other._isnan()
   1090         modulo_is_nan = modulo._isnan()
   1091         if self_is_nan or other_is_nan or modulo_is_nan:
   1092             if self_is_nan == 2:
   1093                 return context._raise_error(InvalidOperation, 'sNaN', self)
   1094             if other_is_nan == 2:
   1095                 return context._raise_error(InvalidOperation, 'sNaN', other)
   1096             if modulo_is_nan == 2:
   1097                 return context._raise_error(InvalidOperation, 'sNaN', modulo)
   1098             if self_is_nan:
   1099                 return self._fix_nan(context)
   1100             if other_is_nan:
   1101                 return other._fix_nan(context)
   1102             return modulo._fix_nan(context)
   1103         if not (self._isinteger() and other._isinteger() and modulo._isinteger()):
   1104             return context._raise_error(InvalidOperation, 'pow() 3rd argument not allowed unless all arguments are integers')
   1105         if other < 0:
   1106             return context._raise_error(InvalidOperation, 'pow() 2nd argument cannot be negative when 3rd argument specified')
   1107         if not modulo:
   1108             return context._raise_error(InvalidOperation, 'pow() 3rd argument cannot be 0')
   1109         if modulo.adjusted() >= context.prec:
   1110             return context._raise_error(InvalidOperation, 'insufficient precision: pow() 3rd argument must not have more than precision digits')
   1111         if not other and not self:
   1112             return context._raise_error(InvalidOperation, 'at least one of pow() 1st argument and 2nd argument must be nonzero ;0**0 is not defined')
   1113         if other._iseven():
   1114             sign = 0
   1115         else:
   1116             sign = self._sign
   1117         modulo = abs(int(modulo))
   1118         base = _WorkRep(self.to_integral_value())
   1119         exponent = _WorkRep(other.to_integral_value())
   1120         base = base.int % modulo * pow(10, base.exp, modulo) % modulo
   1121         for i in xrange(exponent.exp):
   1122             base = pow(base, 10, modulo)
   1123 
   1124         base = pow(base, exponent.int, modulo)
   1125         return _dec_from_triple(sign, str(base), 0)
   1126 
   1127     def _power_exact(self, other, p):
   1128         x = _WorkRep(self)
   1129         xc, xe = x.int, x.exp
   1130         while xc % 10 == 0:
   1131             xc //= 10
   1132             xe += 1
   1133 
   1134         y = _WorkRep(other)
   1135         yc, ye = y.int, y.exp
   1136         while yc % 10 == 0:
   1137             yc //= 10
   1138             ye += 1
   1139 
   1140         if xc == 1:
   1141             xe *= yc
   1142             while xe % 10 == 0:
   1143                 xe //= 10
   1144                 ye += 1
   1145 
   1146             if ye < 0:
   1147                 return None
   1148             exponent = xe * 10 ** ye
   1149             if y.sign == 1:
   1150                 exponent = -exponent
   1151             if other._isinteger() and other._sign == 0:
   1152                 ideal_exponent = self._exp * int(other)
   1153                 zeros = min(exponent - ideal_exponent, p - 1)
   1154             else:
   1155                 zeros = 0
   1156             return _dec_from_triple(0, '1' + '0' * zeros, exponent - zeros)
   1157         if y.sign == 1:
   1158             last_digit = xc % 10
   1159             if last_digit in (2, 4, 6, 8):
   1160                 if xc & -xc != xc:
   1161                     return None
   1162                 e = _nbits(xc) - 1
   1163                 if ye >= 0:
   1164                     y_as_int = yc * 10 ** ye
   1165                     e = e * y_as_int
   1166                     xe = xe * y_as_int
   1167                 else:
   1168                     ten_pow = 10 ** (-ye)
   1169                     e, remainder = divmod(e * yc, ten_pow)
   1170                     if remainder:
   1171                         return None
   1172                     xe, remainder = divmod(xe * yc, ten_pow)
   1173                     if remainder:
   1174                         return None
   1175                 if e * 65 >= p * 93:
   1176                     return None
   1177                 xc = 5 ** e
   1178             elif last_digit == 5:
   1179                 e = _nbits(xc) * 28 // 65
   1180                 xc, remainder = divmod(5 ** e, xc)
   1181                 if remainder:
   1182                     return None
   1183                 while xc % 5 == 0:
   1184                     xc //= 5
   1185                     e -= 1
   1186 
   1187                 if ye >= 0:
   1188                     y_as_integer = yc * 10 ** ye
   1189                     e = e * y_as_integer
   1190                     xe = xe * y_as_integer
   1191                 else:
   1192                     ten_pow = 10 ** (-ye)
   1193                     e, remainder = divmod(e * yc, ten_pow)
   1194                     if remainder:
   1195                         return None
   1196                     xe, remainder = divmod(xe * yc, ten_pow)
   1197                     if remainder:
   1198                         return None
   1199                 if e * 3 >= p * 10:
   1200                     return None
   1201                 xc = 2 ** e
   1202             else:
   1203                 return None
   1204             if xc >= 10 ** p:
   1205                 return None
   1206             xe = -e - xe
   1207             return _dec_from_triple(0, str(xc), xe)
   1208         if ye >= 0:
   1209             m, n = yc * 10 ** ye, 1
   1210         else:
   1211             if xe != 0 and len(str(abs(yc * xe))) <= -ye:
   1212                 return None
   1213             xc_bits = _nbits(xc)
   1214             if xc != 1 and len(str(abs(yc) * xc_bits)) <= -ye:
   1215                 return None
   1216             m, n = yc, 10 ** (-ye)
   1217             while m % 2 == n % 2 == 0:
   1218                 m //= 2
   1219                 n //= 2
   1220 
   1221             while m % 5 == n % 5 == 0:
   1222                 m //= 5
   1223                 n //= 5
   1224 
   1225         if n > 1:
   1226             if xc != 1 and xc_bits <= n:
   1227                 return None
   1228             xe, rem = divmod(xe, n)
   1229             if rem != 0:
   1230                 return None
   1231             a = 1L << -(-_nbits(xc) // n)
   1232             while True:
   1233                 q, r = divmod(xc, a ** (n - 1))
   1234                 if a <= q:
   1235                     break
   1236                 else:
   1237                     a = (a * (n - 1) + q) // n
   1238 
   1239             if not (a == q and r == 0):
   1240                 return None
   1241             xc = a
   1242         if xc > 1 and m > p * 100 // _log10_lb(xc):
   1243             return None
   1244         xc = xc ** m
   1245         xe *= m
   1246         if xc > 10 ** p:
   1247             return None
   1248         str_xc = str(xc)
   1249         if other._isinteger() and other._sign == 0:
   1250             ideal_exponent = self._exp * int(other)
   1251             zeros = min(xe - ideal_exponent, p - len(str_xc))
   1252         else:
   1253             zeros = 0
   1254         return _dec_from_triple(0, str_xc + '0' * zeros, xe - zeros)
   1255 
   1256     def __pow__(self, other, modulo = None, context = None):
   1257         if modulo is not None:
   1258             return self._power_modulo(other, modulo, context)
   1259         other = _convert_other(other)
   1260         if other is NotImplemented:
   1261             return other
   1262         if context is None:
   1263             context = getcontext()
   1264         ans = self._check_nans(other, context)
   1265         if ans:
   1266             return ans
   1267         if not other:
   1268             if not self:
   1269                 return context._raise_error(InvalidOperation, '0 ** 0')
   1270             else:
   1271                 return _One
   1272         result_sign = 0
   1273         if self._sign == 1:
   1274             if other._isinteger():
   1275                 if not other._iseven():
   1276                     result_sign = 1
   1277             elif self:
   1278                 return context._raise_error(InvalidOperation, 'x ** y with x negative and y not an integer')
   1279             self = self.copy_negate()
   1280         if not self:
   1281             if other._sign == 0:
   1282                 return _dec_from_triple(result_sign, '0', 0)
   1283             else:
   1284                 return _SignedInfinity[result_sign]
   1285         if self._isinfinity():
   1286             if other._sign == 0:
   1287                 return _SignedInfinity[result_sign]
   1288             else:
   1289                 return _dec_from_triple(result_sign, '0', 0)
   1290         if self == _One:
   1291             if other._isinteger():
   1292                 if other._sign == 1:
   1293                     multiplier = 0
   1294                 elif other > context.prec:
   1295                     multiplier = context.prec
   1296                 else:
   1297                     multiplier = int(other)
   1298                 exp = self._exp * multiplier
   1299                 if exp < 1 - context.prec:
   1300                     exp = 1 - context.prec
   1301                     context._raise_error(Rounded)
   1302             else:
   1303                 context._raise_error(Inexact)
   1304                 context._raise_error(Rounded)
   1305                 exp = 1 - context.prec
   1306             return _dec_from_triple(result_sign, '1' + '0' * -exp, exp)
   1307         self_adj = self.adjusted()
   1308         if other._isinfinity():
   1309             if (other._sign == 0) == (self_adj < 0):
   1310                 return _dec_from_triple(result_sign, '0', 0)
   1311             else:
   1312                 return _SignedInfinity[result_sign]
   1313         ans = None
   1314         exact = False
   1315         bound = self._log10_exp_bound() + other.adjusted()
   1316         if (self_adj >= 0) == (other._sign == 0):
   1317             if bound >= len(str(context.Emax)):
   1318                 ans = _dec_from_triple(result_sign, '1', context.Emax + 1)
   1319         else:
   1320             Etiny = context.Etiny()
   1321             if bound >= len(str(-Etiny)):
   1322                 ans = _dec_from_triple(result_sign, '1', Etiny - 1)
   1323         if ans is None:
   1324             ans = self._power_exact(other, context.prec + 1)
   1325             if ans is not None:
   1326                 if result_sign == 1:
   1327                     ans = _dec_from_triple(1, ans._int, ans._exp)
   1328                 exact = True
   1329         if ans is None:
   1330             p = context.prec
   1331             x = _WorkRep(self)
   1332             xc, xe = x.int, x.exp
   1333             y = _WorkRep(other)
   1334             yc, ye = y.int, y.exp
   1335             if y.sign == 1:
   1336                 yc = -yc
   1337             extra = 3
   1338             while True:
   1339                 coeff, exp = _dpower(xc, xe, yc, ye, p + extra)
   1340                 if coeff % (5 * 10 ** (len(str(coeff)) - p - 1)):
   1341                     break
   1342                 extra += 3
   1343 
   1344             ans = _dec_from_triple(result_sign, str(coeff), exp)
   1345         if exact and not other._isinteger():
   1346             if len(ans._int) <= context.prec:
   1347                 expdiff = context.prec + 1 - len(ans._int)
   1348                 ans = _dec_from_triple(ans._sign, ans._int + '0' * expdiff, ans._exp - expdiff)
   1349             newcontext = context.copy()
   1350             newcontext.clear_flags()
   1351             for exception in _signals:
   1352                 newcontext.traps[exception] = 0
   1353 
   1354             ans = ans._fix(newcontext)
   1355             newcontext._raise_error(Inexact)
   1356             if newcontext.flags[Subnormal]:
   1357                 newcontext._raise_error(Underflow)
   1358             if newcontext.flags[Overflow]:
   1359                 context._raise_error(Overflow, 'above Emax', ans._sign)
   1360             for exception in (Underflow,
   1361              Subnormal,
   1362              Inexact,
   1363              Rounded,
   1364              Clamped):
   1365                 if newcontext.flags[exception]:
   1366                     context._raise_error(exception)
   1367 
   1368         else:
   1369             ans = ans._fix(context)
   1370         return ans
   1371 
   1372     def __rpow__(self, other, context = None):
   1373         other = _convert_other(other)
   1374         if other is NotImplemented:
   1375             return other
   1376         return other.__pow__(self, context=context)
   1377 
   1378     def normalize(self, context = None):
   1379         if context is None:
   1380             context = getcontext()
   1381         if self._is_special:
   1382             ans = self._check_nans(context=context)
   1383             if ans:
   1384                 return ans
   1385         dup = self._fix(context)
   1386         if dup._isinfinity():
   1387             return dup
   1388         if not dup:
   1389             return _dec_from_triple(dup._sign, '0', 0)
   1390         exp_max = [context.Emax, context.Etop()][context._clamp]
   1391         end = len(dup._int)
   1392         exp = dup._exp
   1393         while dup._int[end - 1] == '0' and exp < exp_max:
   1394             exp += 1
   1395             end -= 1
   1396 
   1397         return _dec_from_triple(dup._sign, dup._int[:end], exp)
   1398 
   1399     def quantize(self, exp, rounding = None, context = None, watchexp = True):
   1400         exp = _convert_other(exp, raiseit=True)
   1401         if context is None:
   1402             context = getcontext()
   1403         if rounding is None:
   1404             rounding = context.rounding
   1405         if self._is_special or exp._is_special:
   1406             ans = self._check_nans(exp, context)
   1407             if ans:
   1408                 return ans
   1409             if exp._isinfinity() or self._isinfinity():
   1410                 if exp._isinfinity() and self._isinfinity():
   1411                     return Decimal(self)
   1412                 return context._raise_error(InvalidOperation, 'quantize with one INF')
   1413         if not watchexp:
   1414             ans = self._rescale(exp._exp, rounding)
   1415             if ans._exp > self._exp:
   1416                 context._raise_error(Rounded)
   1417                 if ans != self:
   1418                     context._raise_error(Inexact)
   1419             return ans
   1420         if not context.Etiny() <= exp._exp <= context.Emax:
   1421             return context._raise_error(InvalidOperation, 'target exponent out of bounds in quantize')
   1422         if not self:
   1423             ans = _dec_from_triple(self._sign, '0', exp._exp)
   1424             return ans._fix(context)
   1425         self_adjusted = self.adjusted()
   1426         if self_adjusted > context.Emax:
   1427             return context._raise_error(InvalidOperation, 'exponent of quantize result too large for current context')
   1428         if self_adjusted - exp._exp + 1 > context.prec:
   1429             return context._raise_error(InvalidOperation, 'quantize result has too many digits for current context')
   1430         ans = self._rescale(exp._exp, rounding)
   1431         if ans.adjusted() > context.Emax:
   1432             return context._raise_error(InvalidOperation, 'exponent of quantize result too large for current context')
   1433         if len(ans._int) > context.prec:
   1434             return context._raise_error(InvalidOperation, 'quantize result has too many digits for current context')
   1435         if ans and ans.adjusted() < context.Emin:
   1436             context._raise_error(Subnormal)
   1437         if ans._exp > self._exp:
   1438             if ans != self:
   1439                 context._raise_error(Inexact)
   1440             context._raise_error(Rounded)
   1441         ans = ans._fix(context)
   1442         return ans
   1443 
   1444     def same_quantum(self, other):
   1445         other = _convert_other(other, raiseit=True)
   1446         if self._is_special or other._is_special:
   1447             return self.is_nan() and other.is_nan() or self.is_infinite() and other.is_infinite()
   1448         return self._exp == other._exp
   1449 
   1450     def _rescale(self, exp, rounding):
   1451         if self._is_special:
   1452             return Decimal(self)
   1453         if not self:
   1454             return _dec_from_triple(self._sign, '0', exp)
   1455         if self._exp >= exp:
   1456             return _dec_from_triple(self._sign, self._int + '0' * (self._exp - exp), exp)
   1457         digits = len(self._int) + self._exp - exp
   1458         if digits < 0:
   1459             self = _dec_from_triple(self._sign, '1', exp - 1)
   1460             digits = 0
   1461         this_function = getattr(self, self._pick_rounding_function[rounding])
   1462         changed = this_function(digits)
   1463         coeff = self._int[:digits] or '0'
   1464         if changed == 1:
   1465             coeff = str(int(coeff) + 1)
   1466         return _dec_from_triple(self._sign, coeff, exp)
   1467 
   1468     def _round(self, places, rounding):
   1469         if places <= 0:
   1470             raise ValueError('argument should be at least 1 in _round')
   1471         if self._is_special or not self:
   1472             return Decimal(self)
   1473         ans = self._rescale(self.adjusted() + 1 - places, rounding)
   1474         if ans.adjusted() != self.adjusted():
   1475             ans = ans._rescale(ans.adjusted() + 1 - places, rounding)
   1476         return ans
   1477 
   1478     def to_integral_exact(self, rounding = None, context = None):
   1479         if self._is_special:
   1480             ans = self._check_nans(context=context)
   1481             if ans:
   1482                 return ans
   1483             return Decimal(self)
   1484         if self._exp >= 0:
   1485             return Decimal(self)
   1486         if not self:
   1487             return _dec_from_triple(self._sign, '0', 0)
   1488         if context is None:
   1489             context = getcontext()
   1490         if rounding is None:
   1491             rounding = context.rounding
   1492         ans = self._rescale(0, rounding)
   1493         if ans != self:
   1494             context._raise_error(Inexact)
   1495         context._raise_error(Rounded)
   1496         return ans
   1497 
   1498     def to_integral_value(self, rounding = None, context = None):
   1499         if context is None:
   1500             context = getcontext()
   1501         if rounding is None:
   1502             rounding = context.rounding
   1503         if self._is_special:
   1504             ans = self._check_nans(context=context)
   1505             if ans:
   1506                 return ans
   1507             return Decimal(self)
   1508         elif self._exp >= 0:
   1509             return Decimal(self)
   1510         else:
   1511             return self._rescale(0, rounding)
   1512 
   1513     to_integral = to_integral_value
   1514 
   1515     def sqrt(self, context = None):
   1516         if context is None:
   1517             context = getcontext()
   1518         if self._is_special:
   1519             ans = self._check_nans(context=context)
   1520             if ans:
   1521                 return ans
   1522             if self._isinfinity() and self._sign == 0:
   1523                 return Decimal(self)
   1524         if not self:
   1525             ans = _dec_from_triple(self._sign, '0', self._exp // 2)
   1526             return ans._fix(context)
   1527         if self._sign == 1:
   1528             return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
   1529         prec = context.prec + 1
   1530         op = _WorkRep(self)
   1531         e = op.exp >> 1
   1532         if op.exp & 1:
   1533             c = op.int * 10
   1534             l = (len(self._int) >> 1) + 1
   1535         else:
   1536             c = op.int
   1537             l = len(self._int) + 1 >> 1
   1538         shift = prec - l
   1539         if shift >= 0:
   1540             c *= 100 ** shift
   1541             exact = True
   1542         else:
   1543             c, remainder = divmod(c, 100 ** (-shift))
   1544             exact = not remainder
   1545         e -= shift
   1546         n = 10 ** prec
   1547         while True:
   1548             q = c // n
   1549             if n <= q:
   1550                 break
   1551             else:
   1552                 n = n + q >> 1
   1553 
   1554         exact = exact and n * n == c
   1555         if exact:
   1556             if shift >= 0:
   1557                 n //= 10 ** shift
   1558             else:
   1559                 n *= 10 ** (-shift)
   1560             e += shift
   1561         elif n % 5 == 0:
   1562             n += 1
   1563         ans = _dec_from_triple(0, str(n), e)
   1564         context = context._shallow_copy()
   1565         rounding = context._set_rounding(ROUND_HALF_EVEN)
   1566         ans = ans._fix(context)
   1567         context.rounding = rounding
   1568         return ans
   1569 
   1570     def max(self, other, context = None):
   1571         other = _convert_other(other, raiseit=True)
   1572         if context is None:
   1573             context = getcontext()
   1574         if self._is_special or other._is_special:
   1575             sn = self._isnan()
   1576             on = other._isnan()
   1577             if sn or on:
   1578                 if on == 1 and sn == 0:
   1579                     return self._fix(context)
   1580                 if sn == 1 and on == 0:
   1581                     return other._fix(context)
   1582                 return self._check_nans(other, context)
   1583         c = self._cmp(other)
   1584         if c == 0:
   1585             c = self.compare_total(other)
   1586         if c == -1:
   1587             ans = other
   1588         else:
   1589             ans = self
   1590         return ans._fix(context)
   1591 
   1592     def min(self, other, context = None):
   1593         other = _convert_other(other, raiseit=True)
   1594         if context is None:
   1595             context = getcontext()
   1596         if self._is_special or other._is_special:
   1597             sn = self._isnan()
   1598             on = other._isnan()
   1599             if sn or on:
   1600                 if on == 1 and sn == 0:
   1601                     return self._fix(context)
   1602                 if sn == 1 and on == 0:
   1603                     return other._fix(context)
   1604                 return self._check_nans(other, context)
   1605         c = self._cmp(other)
   1606         if c == 0:
   1607             c = self.compare_total(other)
   1608         if c == -1:
   1609             ans = self
   1610         else:
   1611             ans = other
   1612         return ans._fix(context)
   1613 
   1614     def _isinteger(self):
   1615         if self._is_special:
   1616             return False
   1617         if self._exp >= 0:
   1618             return True
   1619         rest = self._int[self._exp:]
   1620         return rest == '0' * len(rest)
   1621 
   1622     def _iseven(self):
   1623         if not self or self._exp > 0:
   1624             return True
   1625         return self._int[-1 + self._exp] in '02468'
   1626 
   1627     def adjusted(self):
   1628         try:
   1629             return self._exp + len(self._int) - 1
   1630         except TypeError:
   1631             return 0
   1632 
   1633     def canonical(self, context = None):
   1634         return self
   1635 
   1636     def compare_signal(self, other, context = None):
   1637         other = _convert_other(other, raiseit=True)
   1638         ans = self._compare_check_nans(other, context)
   1639         if ans:
   1640             return ans
   1641         return self.compare(other, context=context)
   1642 
   1643     def compare_total(self, other):
   1644         other = _convert_other(other, raiseit=True)
   1645         if self._sign and not other._sign:
   1646             return _NegativeOne
   1647         if not self._sign and other._sign:
   1648             return _One
   1649         sign = self._sign
   1650         self_nan = self._isnan()
   1651         other_nan = other._isnan()
   1652         if self_nan or other_nan:
   1653             if self_nan == other_nan:
   1654                 self_key = (len(self._int), self._int)
   1655                 other_key = (len(other._int), other._int)
   1656                 if self_key < other_key:
   1657                     if sign:
   1658                         return _One
   1659                     else:
   1660                         return _NegativeOne
   1661                 if self_key > other_key:
   1662                     if sign:
   1663                         return _NegativeOne
   1664                     else:
   1665                         return _One
   1666                 return _Zero
   1667             if sign:
   1668                 if self_nan == 1:
   1669                     return _NegativeOne
   1670                 if other_nan == 1:
   1671                     return _One
   1672                 if self_nan == 2:
   1673                     return _NegativeOne
   1674                 if other_nan == 2:
   1675                     return _One
   1676             else:
   1677                 if self_nan == 1:
   1678                     return _One
   1679                 if other_nan == 1:
   1680                     return _NegativeOne
   1681                 if self_nan == 2:
   1682                     return _One
   1683                 if other_nan == 2:
   1684                     return _NegativeOne
   1685         if self < other:
   1686             return _NegativeOne
   1687         if self > other:
   1688             return _One
   1689         if self._exp < other._exp:
   1690             if sign:
   1691                 return _One
   1692             else:
   1693                 return _NegativeOne
   1694         if self._exp > other._exp:
   1695             if sign:
   1696                 return _NegativeOne
   1697             else:
   1698                 return _One
   1699         return _Zero
   1700 
   1701     def compare_total_mag(self, other):
   1702         other = _convert_other(other, raiseit=True)
   1703         s = self.copy_abs()
   1704         o = other.copy_abs()
   1705         return s.compare_total(o)
   1706 
   1707     def copy_abs(self):
   1708         return _dec_from_triple(0, self._int, self._exp, self._is_special)
   1709 
   1710     def copy_negate(self):
   1711         if self._sign:
   1712             return _dec_from_triple(0, self._int, self._exp, self._is_special)
   1713         else:
   1714             return _dec_from_triple(1, self._int, self._exp, self._is_special)
   1715 
   1716     def copy_sign(self, other):
   1717         other = _convert_other(other, raiseit=True)
   1718         return _dec_from_triple(other._sign, self._int, self._exp, self._is_special)
   1719 
   1720     def exp(self, context = None):
   1721         if context is None:
   1722             context = getcontext()
   1723         ans = self._check_nans(context=context)
   1724         if ans:
   1725             return ans
   1726         if self._isinfinity() == -1:
   1727             return _Zero
   1728         if not self:
   1729             return _One
   1730         if self._isinfinity() == 1:
   1731             return Decimal(self)
   1732         p = context.prec
   1733         adj = self.adjusted()
   1734         if self._sign == 0 and adj > len(str((context.Emax + 1) * 3)):
   1735             ans = _dec_from_triple(0, '1', context.Emax + 1)
   1736         elif self._sign == 1 and adj > len(str((-context.Etiny() + 1) * 3)):
   1737             ans = _dec_from_triple(0, '1', context.Etiny() - 1)
   1738         elif self._sign == 0 and adj < -p:
   1739             ans = _dec_from_triple(0, '1' + '0' * (p - 1) + '1', -p)
   1740         elif self._sign == 1 and adj < -p - 1:
   1741             ans = _dec_from_triple(0, '9' * (p + 1), -p - 1)
   1742         else:
   1743             op = _WorkRep(self)
   1744             c, e = op.int, op.exp
   1745             if op.sign == 1:
   1746                 c = -c
   1747             extra = 3
   1748             while True:
   1749                 coeff, exp = _dexp(c, e, p + extra)
   1750                 if coeff % (5 * 10 ** (len(str(coeff)) - p - 1)):
   1751                     break
   1752                 extra += 3
   1753 
   1754             ans = _dec_from_triple(0, str(coeff), exp)
   1755         context = context._shallow_copy()
   1756         rounding = context._set_rounding(ROUND_HALF_EVEN)
   1757         ans = ans._fix(context)
   1758         context.rounding = rounding
   1759         return ans
   1760 
   1761     def is_canonical(self):
   1762         return True
   1763 
   1764     def is_finite(self):
   1765         return not self._is_special
   1766 
   1767     def is_infinite(self):
   1768         return self._exp == 'F'
   1769 
   1770     def is_nan(self):
   1771         return self._exp in ('n', 'N')
   1772 
   1773     def is_normal(self, context = None):
   1774         if self._is_special or not self:
   1775             return False
   1776         if context is None:
   1777             context = getcontext()
   1778         return context.Emin <= self.adjusted()
   1779 
   1780     def is_qnan(self):
   1781         return self._exp == 'n'
   1782 
   1783     def is_signed(self):
   1784         return self._sign == 1
   1785 
   1786     def is_snan(self):
   1787         return self._exp == 'N'
   1788 
   1789     def is_subnormal(self, context = None):
   1790         if self._is_special or not self:
   1791             return False
   1792         if context is None:
   1793             context = getcontext()
   1794         return self.adjusted() < context.Emin
   1795 
   1796     def is_zero(self):
   1797         return not self._is_special and self._int == '0'
   1798 
   1799     def _ln_exp_bound(self):
   1800         adj = self._exp + len(self._int) - 1
   1801         if adj >= 1:
   1802             return len(str(adj * 23 // 10)) - 1
   1803         if adj <= -2:
   1804             return len(str((-1 - adj) * 23 // 10)) - 1
   1805         op = _WorkRep(self)
   1806         c, e = op.int, op.exp
   1807         if adj == 0:
   1808             num = str(c - 10 ** (-e))
   1809             den = str(c)
   1810             return len(num) - len(den) - (num < den)
   1811         return e + len(str(10 ** (-e) - c)) - 1
   1812 
   1813     def ln(self, context = None):
   1814         if context is None:
   1815             context = getcontext()
   1816         ans = self._check_nans(context=context)
   1817         if ans:
   1818             return ans
   1819         if not self:
   1820             return _NegativeInfinity
   1821         if self._isinfinity() == 1:
   1822             return _Infinity
   1823         if self == _One:
   1824             return _Zero
   1825         if self._sign == 1:
   1826             return context._raise_error(InvalidOperation, 'ln of a negative value')
   1827         op = _WorkRep(self)
   1828         c, e = op.int, op.exp
   1829         p = context.prec
   1830         places = p - self._ln_exp_bound() + 2
   1831         while True:
   1832             coeff = _dlog(c, e, places)
   1833             if coeff % (5 * 10 ** (len(str(abs(coeff))) - p - 1)):
   1834                 break
   1835             places += 3
   1836 
   1837         ans = _dec_from_triple(int(coeff < 0), str(abs(coeff)), -places)
   1838         context = context._shallow_copy()
   1839         rounding = context._set_rounding(ROUND_HALF_EVEN)
   1840         ans = ans._fix(context)
   1841         context.rounding = rounding
   1842         return ans
   1843 
   1844     def _log10_exp_bound(self):
   1845         adj = self._exp + len(self._int) - 1
   1846         if adj >= 1:
   1847             return len(str(adj)) - 1
   1848         if adj <= -2:
   1849             return len(str(-1 - adj)) - 1
   1850         op = _WorkRep(self)
   1851         c, e = op.int, op.exp
   1852         if adj == 0:
   1853             num = str(c - 10 ** (-e))
   1854             den = str(231 * c)
   1855             return len(num) - len(den) - (num < den) + 2
   1856         num = str(10 ** (-e) - c)
   1857         return len(num) + e - (num < '231') - 1
   1858 
   1859     def log10(self, context = None):
   1860         if context is None:
   1861             context = getcontext()
   1862         ans = self._check_nans(context=context)
   1863         if ans:
   1864             return ans
   1865         if not self:
   1866             return _NegativeInfinity
   1867         if self._isinfinity() == 1:
   1868             return _Infinity
   1869         if self._sign == 1:
   1870             return context._raise_error(InvalidOperation, 'log10 of a negative value')
   1871         if self._int[0] == '1' and self._int[1:] == '0' * (len(self._int) - 1):
   1872             ans = Decimal(self._exp + len(self._int) - 1)
   1873         else:
   1874             op = _WorkRep(self)
   1875             c, e = op.int, op.exp
   1876             p = context.prec
   1877             places = p - self._log10_exp_bound() + 2
   1878             while True:
   1879                 coeff = _dlog10(c, e, places)
   1880                 if coeff % (5 * 10 ** (len(str(abs(coeff))) - p - 1)):
   1881                     break
   1882                 places += 3
   1883 
   1884             ans = _dec_from_triple(int(coeff < 0), str(abs(coeff)), -places)
   1885         context = context._shallow_copy()
   1886         rounding = context._set_rounding(ROUND_HALF_EVEN)
   1887         ans = ans._fix(context)
   1888         context.rounding = rounding
   1889         return ans
   1890 
   1891     def logb(self, context = None):
   1892         ans = self._check_nans(context=context)
   1893         if ans:
   1894             return ans
   1895         if context is None:
   1896             context = getcontext()
   1897         if self._isinfinity():
   1898             return _Infinity
   1899         if not self:
   1900             return context._raise_error(DivisionByZero, 'logb(0)', 1)
   1901         ans = Decimal(self.adjusted())
   1902         return ans._fix(context)
   1903 
   1904     def _islogical(self):
   1905         if self._sign != 0 or self._exp != 0:
   1906             return False
   1907         for dig in self._int:
   1908             if dig not in '01':
   1909                 return False
   1910 
   1911         return True
   1912 
   1913     def _fill_logical(self, context, opa, opb):
   1914         dif = context.prec - len(opa)
   1915         if dif > 0:
   1916             opa = '0' * dif + opa
   1917         elif dif < 0:
   1918             opa = opa[-context.prec:]
   1919         dif = context.prec - len(opb)
   1920         if dif > 0:
   1921             opb = '0' * dif + opb
   1922         elif dif < 0:
   1923             opb = opb[-context.prec:]
   1924         return (opa, opb)
   1925 
   1926     def logical_and(self, other, context = None):
   1927         if context is None:
   1928             context = getcontext()
   1929         other = _convert_other(other, raiseit=True)
   1930         if not self._islogical() or not other._islogical():
   1931             return context._raise_error(InvalidOperation)
   1932         opa, opb = self._fill_logical(context, self._int, other._int)
   1933         result = ''.join([ str(int(a) & int(b)) for a, b in zip(opa, opb) ])
   1934         return _dec_from_triple(0, result.lstrip('0') or '0', 0)
   1935 
   1936     def logical_invert(self, context = None):
   1937         if context is None:
   1938             context = getcontext()
   1939         return self.logical_xor(_dec_from_triple(0, '1' * context.prec, 0), context)
   1940 
   1941     def logical_or(self, other, context = None):
   1942         if context is None:
   1943             context = getcontext()
   1944         other = _convert_other(other, raiseit=True)
   1945         if not self._islogical() or not other._islogical():
   1946             return context._raise_error(InvalidOperation)
   1947         opa, opb = self._fill_logical(context, self._int, other._int)
   1948         result = ''.join([ str(int(a) | int(b)) for a, b in zip(opa, opb) ])
   1949         return _dec_from_triple(0, result.lstrip('0') or '0', 0)
   1950 
   1951     def logical_xor(self, other, context = None):
   1952         if context is None:
   1953             context = getcontext()
   1954         other = _convert_other(other, raiseit=True)
   1955         if not self._islogical() or not other._islogical():
   1956             return context._raise_error(InvalidOperation)
   1957         opa, opb = self._fill_logical(context, self._int, other._int)
   1958         result = ''.join([ str(int(a) ^ int(b)) for a, b in zip(opa, opb) ])
   1959         return _dec_from_triple(0, result.lstrip('0') or '0', 0)
   1960 
   1961     def max_mag(self, other, context = None):
   1962         other = _convert_other(other, raiseit=True)
   1963         if context is None:
   1964             context = getcontext()
   1965         if self._is_special or other._is_special:
   1966             sn = self._isnan()
   1967             on = other._isnan()
   1968             if sn or on:
   1969                 if on == 1 and sn == 0:
   1970                     return self._fix(context)
   1971                 if sn == 1 and on == 0:
   1972                     return other._fix(context)
   1973                 return self._check_nans(other, context)
   1974         c = self.copy_abs()._cmp(other.copy_abs())
   1975         if c == 0:
   1976             c = self.compare_total(other)
   1977         if c == -1:
   1978             ans = other
   1979         else:
   1980             ans = self
   1981         return ans._fix(context)
   1982 
   1983     def min_mag(self, other, context = None):
   1984         other = _convert_other(other, raiseit=True)
   1985         if context is None:
   1986             context = getcontext()
   1987         if self._is_special or other._is_special:
   1988             sn = self._isnan()
   1989             on = other._isnan()
   1990             if sn or on:
   1991                 if on == 1 and sn == 0:
   1992                     return self._fix(context)
   1993                 if sn == 1 and on == 0:
   1994                     return other._fix(context)
   1995                 return self._check_nans(other, context)
   1996         c = self.copy_abs()._cmp(other.copy_abs())
   1997         if c == 0:
   1998             c = self.compare_total(other)
   1999         if c == -1:
   2000             ans = self
   2001         else:
   2002             ans = other
   2003         return ans._fix(context)
   2004 
   2005     def next_minus(self, context = None):
   2006         if context is None:
   2007             context = getcontext()
   2008         ans = self._check_nans(context=context)
   2009         if ans:
   2010             return ans
   2011         if self._isinfinity() == -1:
   2012             return _NegativeInfinity
   2013         if self._isinfinity() == 1:
   2014             return _dec_from_triple(0, '9' * context.prec, context.Etop())
   2015         context = context.copy()
   2016         context._set_rounding(ROUND_FLOOR)
   2017         context._ignore_all_flags()
   2018         new_self = self._fix(context)
   2019         if new_self != self:
   2020             return new_self
   2021         return self.__sub__(_dec_from_triple(0, '1', context.Etiny() - 1), context)
   2022 
   2023     def next_plus(self, context = None):
   2024         if context is None:
   2025             context = getcontext()
   2026         ans = self._check_nans(context=context)
   2027         if ans:
   2028             return ans
   2029         if self._isinfinity() == 1:
   2030             return _Infinity
   2031         if self._isinfinity() == -1:
   2032             return _dec_from_triple(1, '9' * context.prec, context.Etop())
   2033         context = context.copy()
   2034         context._set_rounding(ROUND_CEILING)
   2035         context._ignore_all_flags()
   2036         new_self = self._fix(context)
   2037         if new_self != self:
   2038             return new_self
   2039         return self.__add__(_dec_from_triple(0, '1', context.Etiny() - 1), context)
   2040 
   2041     def next_toward(self, other, context = None):
   2042         other = _convert_other(other, raiseit=True)
   2043         if context is None:
   2044             context = getcontext()
   2045         ans = self._check_nans(other, context)
   2046         if ans:
   2047             return ans
   2048         comparison = self._cmp(other)
   2049         if comparison == 0:
   2050             return self.copy_sign(other)
   2051         if comparison == -1:
   2052             ans = self.next_plus(context)
   2053         else:
   2054             ans = self.next_minus(context)
   2055         if ans._isinfinity():
   2056             context._raise_error(Overflow, 'Infinite result from next_toward', ans._sign)
   2057             context._raise_error(Inexact)
   2058             context._raise_error(Rounded)
   2059         elif ans.adjusted() < context.Emin:
   2060             context._raise_error(Underflow)
   2061             context._raise_error(Subnormal)
   2062             context._raise_error(Inexact)
   2063             context._raise_error(Rounded)
   2064             if not ans:
   2065                 context._raise_error(Clamped)
   2066         return ans
   2067 
   2068     def number_class(self, context = None):
   2069         if self.is_snan():
   2070             return 'sNaN'
   2071         elif self.is_qnan():
   2072             return 'NaN'
   2073         inf = self._isinfinity()
   2074         if inf == 1:
   2075             return '+Infinity'
   2076         elif inf == -1:
   2077             return '-Infinity'
   2078         if self.is_zero():
   2079             if self._sign:
   2080                 return '-Zero'
   2081             else:
   2082                 return '+Zero'
   2083         if context is None:
   2084             context = getcontext()
   2085         if self.is_subnormal(context=context):
   2086             if self._sign:
   2087                 return '-Subnormal'
   2088             else:
   2089                 return '+Subnormal'
   2090         if self._sign:
   2091             return '-Normal'
   2092         else:
   2093             return '+Normal'
   2094 
   2095     def radix(self):
   2096         return Decimal(10)
   2097 
   2098     def rotate(self, other, context = None):
   2099         if context is None:
   2100             context = getcontext()
   2101         other = _convert_other(other, raiseit=True)
   2102         ans = self._check_nans(other, context)
   2103         if ans:
   2104             return ans
   2105         if other._exp != 0:
   2106             return context._raise_error(InvalidOperation)
   2107         if not -context.prec <= int(other) <= context.prec:
   2108             return context._raise_error(InvalidOperation)
   2109         if self._isinfinity():
   2110             return Decimal(self)
   2111         torot = int(other)
   2112         rotdig = self._int
   2113         topad = context.prec - len(rotdig)
   2114         if topad > 0:
   2115             rotdig = '0' * topad + rotdig
   2116         elif topad < 0:
   2117             rotdig = rotdig[-topad:]
   2118         rotated = rotdig[torot:] + rotdig[:torot]
   2119         return _dec_from_triple(self._sign, rotated.lstrip('0') or '0', self._exp)
   2120 
   2121     def scaleb(self, other, context = None):
   2122         if context is None:
   2123             context = getcontext()
   2124         other = _convert_other(other, raiseit=True)
   2125         ans = self._check_nans(other, context)
   2126         if ans:
   2127             return ans
   2128         if other._exp != 0:
   2129             return context._raise_error(InvalidOperation)
   2130         liminf = -2 * (context.Emax + context.prec)
   2131         limsup = 2 * (context.Emax + context.prec)
   2132         if not liminf <= int(other) <= limsup:
   2133             return context._raise_error(InvalidOperation)
   2134         if self._isinfinity():
   2135             return Decimal(self)
   2136         d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
   2137         d = d._fix(context)
   2138         return d
   2139 
   2140     def shift(self, other, context = None):
   2141         if context is None:
   2142             context = getcontext()
   2143         other = _convert_other(other, raiseit=True)
   2144         ans = self._check_nans(other, context)
   2145         if ans:
   2146             return ans
   2147         if other._exp != 0:
   2148             return context._raise_error(InvalidOperation)
   2149         if not -context.prec <= int(other) <= context.prec:
   2150             return context._raise_error(InvalidOperation)
   2151         if self._isinfinity():
   2152             return Decimal(self)
   2153         torot = int(other)
   2154         rotdig = self._int
   2155         topad = context.prec - len(rotdig)
   2156         if topad > 0:
   2157             rotdig = '0' * topad + rotdig
   2158         elif topad < 0:
   2159             rotdig = rotdig[-topad:]
   2160         if torot < 0:
   2161             shifted = rotdig[:torot]
   2162         else:
   2163             shifted = rotdig + '0' * torot
   2164             shifted = shifted[-context.prec:]
   2165         return _dec_from_triple(self._sign, shifted.lstrip('0') or '0', self._exp)
   2166 
   2167     def __reduce__(self):
   2168         return (self.__class__, (str(self),))
   2169 
   2170     def __copy__(self):
   2171         if type(self) is Decimal:
   2172             return self
   2173         return self.__class__(str(self))
   2174 
   2175     def __deepcopy__(self, memo):
   2176         if type(self) is Decimal:
   2177             return self
   2178         return self.__class__(str(self))
   2179 
   2180     def __format__(self, specifier, context = None, _localeconv = None):
   2181         if context is None:
   2182             context = getcontext()
   2183         spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
   2184         if self._is_special:
   2185             sign = _format_sign(self._sign, spec)
   2186             body = str(self.copy_abs())
   2187             return _format_align(sign, body, spec)
   2188         if spec['type'] is None:
   2189             spec['type'] = ['g', 'G'][context.capitals]
   2190         if spec['type'] == '%':
   2191             self = _dec_from_triple(self._sign, self._int, self._exp + 2)
   2192         rounding = context.rounding
   2193         precision = spec['precision']
   2194         if precision is not None:
   2195             if spec['type'] in 'eE':
   2196                 self = self._round(precision + 1, rounding)
   2197             elif spec['type'] in 'fF%':
   2198                 self = self._rescale(-precision, rounding)
   2199             elif spec['type'] in 'gG' and len(self._int) > precision:
   2200                 self = self._round(precision, rounding)
   2201         if not self and self._exp > 0 and spec['type'] in 'fF%':
   2202             self = self._rescale(0, rounding)
   2203         leftdigits = self._exp + len(self._int)
   2204         if spec['type'] in 'eE':
   2205             if not self and precision is not None:
   2206                 dotplace = 1 - precision
   2207             else:
   2208                 dotplace = 1
   2209         elif spec['type'] in 'fF%':
   2210             dotplace = leftdigits
   2211         elif spec['type'] in 'gG':
   2212             if self._exp <= 0 and leftdigits > -6:
   2213                 dotplace = leftdigits
   2214             else:
   2215                 dotplace = 1
   2216         if dotplace < 0:
   2217             intpart = '0'
   2218             fracpart = '0' * -dotplace + self._int
   2219         elif dotplace > len(self._int):
   2220             intpart = self._int + '0' * (dotplace - len(self._int))
   2221             fracpart = ''
   2222         else:
   2223             intpart = self._int[:dotplace] or '0'
   2224             fracpart = self._int[dotplace:]
   2225         exp = leftdigits - dotplace
   2226         return _format_number(self._sign, intpart, fracpart, exp, spec)
   2227 
   2228 
   2229 def _dec_from_triple(sign, coefficient, exponent, special = False):
   2230     self = object.__new__(Decimal)
   2231     self._sign = sign
   2232     self._int = coefficient
   2233     self._exp = exponent
   2234     self._is_special = special
   2235     return self
   2236 
   2237 
   2238 _numbers.Number.register(Decimal)
   2239 rounding_functions = [ name for name in Decimal.__dict__.keys() if name.startswith('_round_') ]
   2240 for name in rounding_functions:
   2241     globalname = name[1:].upper()
   2242     val = globals()[globalname]
   2243     Decimal._pick_rounding_function[val] = name
   2244 
   2245 del name
   2246 del val
   2247 del globalname
   2248 del rounding_functions
   2249 
   2250 class _ContextManager(object):
   2251 
   2252     def __init__(self, new_context):
   2253         self.new_context = new_context.copy()
   2254 
   2255     def __enter__(self):
   2256         self.saved_context = getcontext()
   2257         setcontext(self.new_context)
   2258         return self.new_context
   2259 
   2260     def __exit__(self, t, v, tb):
   2261         setcontext(self.saved_context)
   2262 
   2263 
   2264 class Context(object):
   2265 
   2266     def __init__(self, prec = None, rounding = None, traps = None, flags = None, Emin = None, Emax = None, capitals = None, _clamp = 0, _ignored_flags = None):
   2267         try:
   2268             dc = DefaultContext
   2269         except NameError:
   2270             pass
   2271 
   2272         self.prec = prec if prec is not None else dc.prec
   2273         self.rounding = rounding if rounding is not None else dc.rounding
   2274         self.Emin = Emin if Emin is not None else dc.Emin
   2275         self.Emax = Emax if Emax is not None else dc.Emax
   2276         self.capitals = capitals if capitals is not None else dc.capitals
   2277         self._clamp = _clamp if _clamp is not None else dc._clamp
   2278         if _ignored_flags is None:
   2279             self._ignored_flags = []
   2280         else:
   2281             self._ignored_flags = _ignored_flags
   2282         if traps is None:
   2283             self.traps = dc.traps.copy()
   2284         elif not isinstance(traps, dict):
   2285             self.traps = dict(((s, int(s in traps)) for s in _signals))
   2286         else:
   2287             self.traps = traps
   2288         if flags is None:
   2289             self.flags = dict.fromkeys(_signals, 0)
   2290         elif not isinstance(flags, dict):
   2291             self.flags = dict(((s, int(s in flags)) for s in _signals))
   2292         else:
   2293             self.flags = flags
   2294 
   2295     def __repr__(self):
   2296         s = []
   2297         s.append('Context(prec=%(prec)d, rounding=%(rounding)s, Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' % vars(self))
   2298         names = [ f.__name__ for f, v in self.flags.items() if v ]
   2299         s.append('flags=[' + ', '.join(names) + ']')
   2300         names = [ t.__name__ for t, v in self.traps.items() if v ]
   2301         s.append('traps=[' + ', '.join(names) + ']')
   2302         return ', '.join(s) + ')'
   2303 
   2304     def clear_flags(self):
   2305         for flag in self.flags:
   2306             self.flags[flag] = 0
   2307 
   2308     def _shallow_copy(self):
   2309         nc = Context(self.prec, self.rounding, self.traps, self.flags, self.Emin, self.Emax, self.capitals, self._clamp, self._ignored_flags)
   2310         return nc
   2311 
   2312     def copy(self):
   2313         nc = Context(self.prec, self.rounding, self.traps.copy(), self.flags.copy(), self.Emin, self.Emax, self.capitals, self._clamp, self._ignored_flags)
   2314         return nc
   2315 
   2316     __copy__ = copy
   2317 
   2318     def _raise_error(self, condition, explanation = None, *args):
   2319         error = _condition_map.get(condition, condition)
   2320         if error in self._ignored_flags:
   2321             return error().handle(self, *args)
   2322         self.flags[error] = 1
   2323         if not self.traps[error]:
   2324             return condition().handle(self, *args)
   2325         raise error(explanation)
   2326 
   2327     def _ignore_all_flags(self):
   2328         return self._ignore_flags(*_signals)
   2329 
   2330     def _ignore_flags(self, *flags):
   2331         self._ignored_flags = self._ignored_flags + list(flags)
   2332         return list(flags)
   2333 
   2334     def _regard_flags(self, *flags):
   2335         if flags and isinstance(flags[0], (tuple, list)):
   2336             flags = flags[0]
   2337         for flag in flags:
   2338             self._ignored_flags.remove(flag)
   2339 
   2340     __hash__ = None
   2341 
   2342     def Etiny(self):
   2343         return int(self.Emin - self.prec + 1)
   2344 
   2345     def Etop(self):
   2346         return int(self.Emax - self.prec + 1)
   2347 
   2348     def _set_rounding(self, type):
   2349         rounding = self.rounding
   2350         self.rounding = type
   2351         return rounding
   2352 
   2353     def create_decimal(self, num = '0'):
   2354         if isinstance(num, basestring) and num != num.strip():
   2355             return self._raise_error(ConversionSyntax, 'no trailing or leading whitespace is permitted.')
   2356         d = Decimal(num, context=self)
   2357         if d._isnan() and len(d._int) > self.prec - self._clamp:
   2358             return self._raise_error(ConversionSyntax, 'diagnostic info too long in NaN')
   2359         return d._fix(self)
   2360 
   2361     def create_decimal_from_float(self, f):
   2362         d = Decimal.from_float(f)
   2363         return d._fix(self)
   2364 
   2365     def abs(self, a):
   2366         a = _convert_other(a, raiseit=True)
   2367         return a.__abs__(context=self)
   2368 
   2369     def add(self, a, b):
   2370         a = _convert_other(a, raiseit=True)
   2371         r = a.__add__(b, context=self)
   2372         if r is NotImplemented:
   2373             raise TypeError('Unable to convert %s to Decimal' % b)
   2374         else:
   2375             return r
   2376 
   2377     def _apply(self, a):
   2378         return str(a._fix(self))
   2379 
   2380     def canonical(self, a):
   2381         return a.canonical(context=self)
   2382 
   2383     def compare(self, a, b):
   2384         a = _convert_other(a, raiseit=True)
   2385         return a.compare(b, context=self)
   2386 
   2387     def compare_signal(self, a, b):
   2388         a = _convert_other(a, raiseit=True)
   2389         return a.compare_signal(b, context=self)
   2390 
   2391     def compare_total(self, a, b):
   2392         a = _convert_other(a, raiseit=True)
   2393         return a.compare_total(b)
   2394 
   2395     def compare_total_mag(self, a, b):
   2396         a = _convert_other(a, raiseit=True)
   2397         return a.compare_total_mag(b)
   2398 
   2399     def copy_abs(self, a):
   2400         a = _convert_other(a, raiseit=True)
   2401         return a.copy_abs()
   2402 
   2403     def copy_decimal(self, a):
   2404         a = _convert_other(a, raiseit=True)
   2405         return Decimal(a)
   2406 
   2407     def copy_negate(self, a):
   2408         a = _convert_other(a, raiseit=True)
   2409         return a.copy_negate()
   2410 
   2411     def copy_sign(self, a, b):
   2412         a = _convert_other(a, raiseit=True)
   2413         return a.copy_sign(b)
   2414 
   2415     def divide(self, a, b):
   2416         a = _convert_other(a, raiseit=True)
   2417         r = a.__div__(b, context=self)
   2418         if r is NotImplemented:
   2419             raise TypeError('Unable to convert %s to Decimal' % b)
   2420         else:
   2421             return r
   2422 
   2423     def divide_int(self, a, b):
   2424         a = _convert_other(a, raiseit=True)
   2425         r = a.__floordiv__(b, context=self)
   2426         if r is NotImplemented:
   2427             raise TypeError('Unable to convert %s to Decimal' % b)
   2428         else:
   2429             return r
   2430 
   2431     def divmod(self, a, b):
   2432         a = _convert_other(a, raiseit=True)
   2433         r = a.__divmod__(b, context=self)
   2434         if r is NotImplemented:
   2435             raise TypeError('Unable to convert %s to Decimal' % b)
   2436         else:
   2437             return r
   2438 
   2439     def exp(self, a):
   2440         a = _convert_other(a, raiseit=True)
   2441         return a.exp(context=self)
   2442 
   2443     def fma(self, a, b, c):
   2444         a = _convert_other(a, raiseit=True)
   2445         return a.fma(b, c, context=self)
   2446 
   2447     def is_canonical(self, a):
   2448         return a.is_canonical()
   2449 
   2450     def is_finite(self, a):
   2451         a = _convert_other(a, raiseit=True)
   2452         return a.is_finite()
   2453 
   2454     def is_infinite(self, a):
   2455         a = _convert_other(a, raiseit=True)
   2456         return a.is_infinite()
   2457 
   2458     def is_nan(self, a):
   2459         a = _convert_other(a, raiseit=True)
   2460         return a.is_nan()
   2461 
   2462     def is_normal(self, a):
   2463         a = _convert_other(a, raiseit=True)
   2464         return a.is_normal(context=self)
   2465 
   2466     def is_qnan(self, a):
   2467         a = _convert_other(a, raiseit=True)
   2468         return a.is_qnan()
   2469 
   2470     def is_signed(self, a):
   2471         a = _convert_other(a, raiseit=True)
   2472         return a.is_signed()
   2473 
   2474     def is_snan(self, a):
   2475         a = _convert_other(a, raiseit=True)
   2476         return a.is_snan()
   2477 
   2478     def is_subnormal(self, a):
   2479         a = _convert_other(a, raiseit=True)
   2480         return a.is_subnormal(context=self)
   2481 
   2482     def is_zero(self, a):
   2483         a = _convert_other(a, raiseit=True)
   2484         return a.is_zero()
   2485 
   2486     def ln(self, a):
   2487         a = _convert_other(a, raiseit=True)
   2488         return a.ln(context=self)
   2489 
   2490     def log10(self, a):
   2491         a = _convert_other(a, raiseit=True)
   2492         return a.log10(context=self)
   2493 
   2494     def logb(self, a):
   2495         a = _convert_other(a, raiseit=True)
   2496         return a.logb(context=self)
   2497 
   2498     def logical_and(self, a, b):
   2499         a = _convert_other(a, raiseit=True)
   2500         return a.logical_and(b, context=self)
   2501 
   2502     def logical_invert(self, a):
   2503         a = _convert_other(a, raiseit=True)
   2504         return a.logical_invert(context=self)
   2505 
   2506     def logical_or(self, a, b):
   2507         a = _convert_other(a, raiseit=True)
   2508         return a.logical_or(b, context=self)
   2509 
   2510     def logical_xor(self, a, b):
   2511         a = _convert_other(a, raiseit=True)
   2512         return a.logical_xor(b, context=self)
   2513 
   2514     def max(self, a, b):
   2515         a = _convert_other(a, raiseit=True)
   2516         return a.max(b, context=self)
   2517 
   2518     def max_mag(self, a, b):
   2519         a = _convert_other(a, raiseit=True)
   2520         return a.max_mag(b, context=self)
   2521 
   2522     def min(self, a, b):
   2523         a = _convert_other(a, raiseit=True)
   2524         return a.min(b, context=self)
   2525 
   2526     def min_mag(self, a, b):
   2527         a = _convert_other(a, raiseit=True)
   2528         return a.min_mag(b, context=self)
   2529 
   2530     def minus(self, a):
   2531         a = _convert_other(a, raiseit=True)
   2532         return a.__neg__(context=self)
   2533 
   2534     def multiply(self, a, b):
   2535         a = _convert_other(a, raiseit=True)
   2536         r = a.__mul__(b, context=self)
   2537         if r is NotImplemented:
   2538             raise TypeError('Unable to convert %s to Decimal' % b)
   2539         else:
   2540             return r
   2541 
   2542     def next_minus(self, a):
   2543         a = _convert_other(a, raiseit=True)
   2544         return a.next_minus(context=self)
   2545 
   2546     def next_plus(self, a):
   2547         a = _convert_other(a, raiseit=True)
   2548         return a.next_plus(context=self)
   2549 
   2550     def next_toward(self, a, b):
   2551         a = _convert_other(a, raiseit=True)
   2552         return a.next_toward(b, context=self)
   2553 
   2554     def normalize(self, a):
   2555         a = _convert_other(a, raiseit=True)
   2556         return a.normalize(context=self)
   2557 
   2558     def number_class(self, a):
   2559         a = _convert_other(a, raiseit=True)
   2560         return a.number_class(context=self)
   2561 
   2562     def plus(self, a):
   2563         a = _convert_other(a, raiseit=True)
   2564         return a.__pos__(context=self)
   2565 
   2566     def power(self, a, b, modulo = None):
   2567         a = _convert_other(a, raiseit=True)
   2568         r = a.__pow__(b, modulo, context=self)
   2569         if r is NotImplemented:
   2570             raise TypeError('Unable to convert %s to Decimal' % b)
   2571         else:
   2572             return r
   2573 
   2574     def quantize(self, a, b):
   2575         a = _convert_other(a, raiseit=True)
   2576         return a.quantize(b, context=self)
   2577 
   2578     def radix(self):
   2579         return Decimal(10)
   2580 
   2581     def remainder(self, a, b):
   2582         a = _convert_other(a, raiseit=True)
   2583         r = a.__mod__(b, context=self)
   2584         if r is NotImplemented:
   2585             raise TypeError('Unable to convert %s to Decimal' % b)
   2586         else:
   2587             return r
   2588 
   2589     def remainder_near(self, a, b):
   2590         a = _convert_other(a, raiseit=True)
   2591         return a.remainder_near(b, context=self)
   2592 
   2593     def rotate(self, a, b):
   2594         a = _convert_other(a, raiseit=True)
   2595         return a.rotate(b, context=self)
   2596 
   2597     def same_quantum(self, a, b):
   2598         a = _convert_other(a, raiseit=True)
   2599         return a.same_quantum(b)
   2600 
   2601     def scaleb(self, a, b):
   2602         a = _convert_other(a, raiseit=True)
   2603         return a.scaleb(b, context=self)
   2604 
   2605     def shift(self, a, b):
   2606         a = _convert_other(a, raiseit=True)
   2607         return a.shift(b, context=self)
   2608 
   2609     def sqrt(self, a):
   2610         a = _convert_other(a, raiseit=True)
   2611         return a.sqrt(context=self)
   2612 
   2613     def subtract(self, a, b):
   2614         a = _convert_other(a, raiseit=True)
   2615         r = a.__sub__(b, context=self)
   2616         if r is NotImplemented:
   2617             raise TypeError('Unable to convert %s to Decimal' % b)
   2618         else:
   2619             return r
   2620 
   2621     def to_eng_string(self, a):
   2622         a = _convert_other(a, raiseit=True)
   2623         return a.to_eng_string(context=self)
   2624 
   2625     def to_sci_string(self, a):
   2626         a = _convert_other(a, raiseit=True)
   2627         return a.__str__(context=self)
   2628 
   2629     def to_integral_exact(self, a):
   2630         a = _convert_other(a, raiseit=True)
   2631         return a.to_integral_exact(context=self)
   2632 
   2633     def to_integral_value(self, a):
   2634         a = _convert_other(a, raiseit=True)
   2635         return a.to_integral_value(context=self)
   2636 
   2637     to_integral = to_integral_value
   2638 
   2639 
   2640 class _WorkRep(object):
   2641     __slots__ = ('sign', 'int', 'exp')
   2642 
   2643     def __init__(self, value = None):
   2644         if value is None:
   2645             self.sign = None
   2646             self.int = 0
   2647             self.exp = None
   2648         elif isinstance(value, Decimal):
   2649             self.sign = value._sign
   2650             self.int = int(value._int)
   2651             self.exp = value._exp
   2652         else:
   2653             self.sign = value[0]
   2654             self.int = value[1]
   2655             self.exp = value[2]
   2656 
   2657     def __repr__(self):
   2658         return '(%r, %r, %r)' % (self.sign, self.int, self.exp)
   2659 
   2660     __str__ = __repr__
   2661 
   2662 
   2663 def _normalize(op1, op2, prec = 0):
   2664     if op1.exp < op2.exp:
   2665         tmp = op2
   2666         other = op1
   2667     else:
   2668         tmp = op1
   2669         other = op2
   2670     tmp_len = len(str(tmp.int))
   2671     other_len = len(str(other.int))
   2672     exp = tmp.exp + min(-1, tmp_len - prec - 2)
   2673     if other_len + other.exp - 1 < exp:
   2674         other.int = 1
   2675         other.exp = exp
   2676     tmp.int *= 10 ** (tmp.exp - other.exp)
   2677     tmp.exp = other.exp
   2678     return (op1, op2)
   2679 
   2680 
   2681 def _nbits(n, correction = {'0': 4,
   2682  '1': 3,
   2683  '2': 2,
   2684  '3': 2,
   2685  '4': 1,
   2686  '5': 1,
   2687  '6': 1,
   2688  '7': 1,
   2689  '8': 0,
   2690  '9': 0,
   2691  'a': 0,
   2692  'b': 0,
   2693  'c': 0,
   2694  'd': 0,
   2695  'e': 0,
   2696  'f': 0}):
   2697     if n < 0:
   2698         raise ValueError('The argument to _nbits should be nonnegative.')
   2699     hex_n = '%x' % n
   2700     return 4 * len(hex_n) - correction[hex_n[0]]
   2701 
   2702 
   2703 def _sqrt_nearest(n, a):
   2704     if n <= 0 or a <= 0:
   2705         raise ValueError('Both arguments to _sqrt_nearest should be positive.')
   2706     b = 0
   2707     while a != b:
   2708         b, a = a, a - -n // a >> 1
   2709 
   2710     return a
   2711 
   2712 
   2713 def _rshift_nearest(x, shift):
   2714     b, q = 1L << shift, x >> shift
   2715     return q + (2 * (x & b - 1) + (q & 1) > b)
   2716 
   2717 
   2718 def _div_nearest(a, b):
   2719     q, r = divmod(a, b)
   2720     return q + (2 * r + (q & 1) > b)
   2721 
   2722 
   2723 def _ilog(x, M, L = 8):
   2724     y = x - M
   2725     R = 0
   2726     while R <= L and long(abs(y)) << L - R >= M or R > L and abs(y) >> R - L >= M:
   2727         y = _div_nearest(long(M * y) << 1, M + _sqrt_nearest(M * (M + _rshift_nearest(y, R)), M))
   2728         R += 1
   2729 
   2730     T = -int(-10 * len(str(M)) // (3 * L))
   2731     yshift = _rshift_nearest(y, R)
   2732     w = _div_nearest(M, T)
   2733     for k in xrange(T - 1, 0, -1):
   2734         w = _div_nearest(M, k) - _div_nearest(yshift * w, M)
   2735 
   2736     return _div_nearest(w * y, M)
   2737 
   2738 
   2739 def _dlog10(c, e, p):
   2740     p += 2
   2741     l = len(str(c))
   2742     f = e + l - (e + l >= 1)
   2743     if p > 0:
   2744         M = 10 ** p
   2745         k = e + p - f
   2746         if k >= 0:
   2747             c *= 10 ** k
   2748         else:
   2749             c = _div_nearest(c, 10 ** (-k))
   2750         log_d = _ilog(c, M)
   2751         log_10 = _log10_digits(p)
   2752         log_d = _div_nearest(log_d * M, log_10)
   2753         log_tenpower = f * M
   2754     else:
   2755         log_d = 0
   2756         log_tenpower = _div_nearest(f, 10 ** (-p))
   2757     return _div_nearest(log_tenpower + log_d, 100)
   2758 
   2759 
   2760 def _dlog(c, e, p):
   2761     p += 2
   2762     l = len(str(c))
   2763     f = e + l - (e + l >= 1)
   2764     if p > 0:
   2765         k = e + p - f
   2766         if k >= 0:
   2767             c *= 10 ** k
   2768         else:
   2769             c = _div_nearest(c, 10 ** (-k))
   2770         log_d = _ilog(c, 10 ** p)
   2771     else:
   2772         log_d = 0
   2773     if f:
   2774         extra = len(str(abs(f))) - 1
   2775         if p + extra >= 0:
   2776             f_log_ten = _div_nearest(f * _log10_digits(p + extra), 10 ** extra)
   2777         else:
   2778             f_log_ten = 0
   2779     else:
   2780         f_log_ten = 0
   2781     return _div_nearest(f_log_ten + log_d, 100)
   2782 
   2783 
   2784 class _Log10Memoize(object):
   2785 
   2786     def __init__(self):
   2787         self.digits = '23025850929940456840179914546843642076011014886'
   2788 
   2789     def getdigits(self, p):
   2790         if p < 0:
   2791             raise ValueError('p should be nonnegative')
   2792         if p >= len(self.digits):
   2793             extra = 3
   2794             while True:
   2795                 M = 10 ** (p + extra + 2)
   2796                 digits = str(_div_nearest(_ilog(10 * M, M), 100))
   2797                 if digits[-extra:] != '0' * extra:
   2798                     break
   2799                 extra += 3
   2800 
   2801             self.digits = digits.rstrip('0')[:-1]
   2802         return int(self.digits[:p + 1])
   2803 
   2804 
   2805 _log10_digits = _Log10Memoize().getdigits
   2806 
   2807 def _iexp(x, M, L = 8):
   2808     R = _nbits((long(x) << L) // M)
   2809     T = -int(-10 * len(str(M)) // (3 * L))
   2810     y = _div_nearest(x, T)
   2811     Mshift = long(M) << R
   2812     for i in xrange(T - 1, 0, -1):
   2813         y = _div_nearest(x * (Mshift + y), Mshift * i)
   2814 
   2815     for k in xrange(R - 1, -1, -1):
   2816         Mshift = long(M) << k + 2
   2817         y = _div_nearest(y * (y + Mshift), Mshift)
   2818 
   2819     return M + y
   2820 
   2821 
   2822 def _dexp(c, e, p):
   2823     p += 2
   2824     extra = max(0, e + len(str(c)) - 1)
   2825     q = p + extra
   2826     shift = e + q
   2827     if shift >= 0:
   2828         cshift = c * 10 ** shift
   2829     else:
   2830         cshift = c // 10 ** (-shift)
   2831     quot, rem = divmod(cshift, _log10_digits(q))
   2832     rem = _div_nearest(rem, 10 ** extra)
   2833     return (_div_nearest(_iexp(rem, 10 ** p), 1000), quot - p + 3)
   2834 
   2835 
   2836 def _dpower(xc, xe, yc, ye, p):
   2837     b = len(str(abs(yc))) + ye
   2838     lxc = _dlog(xc, xe, p + b + 1)
   2839     shift = ye - b
   2840     if shift >= 0:
   2841         pc = lxc * yc * 10 ** shift
   2842     else:
   2843         pc = _div_nearest(lxc * yc, 10 ** (-shift))
   2844     if pc == 0:
   2845         if (len(str(xc)) + xe >= 1) == (yc > 0):
   2846             coeff, exp = 10 ** (p - 1) + 1, 1 - p
   2847         else:
   2848             coeff, exp = 10 ** p - 1, -p
   2849     else:
   2850         coeff, exp = _dexp(pc, -(p + 1), p + 1)
   2851         coeff = _div_nearest(coeff, 10)
   2852         exp += 1
   2853     return (coeff, exp)
   2854 
   2855 
   2856 def _log10_lb(c, correction = {'1': 100,
   2857  '2': 70,
   2858  '3': 53,
   2859  '4': 40,
   2860  '5': 31,
   2861  '6': 23,
   2862  '7': 16,
   2863  '8': 10,
   2864  '9': 5}):
   2865     if c <= 0:
   2866         raise ValueError('The argument to _log10_lb should be nonnegative.')
   2867     str_c = str(c)
   2868     return 100 * len(str_c) - correction[str_c[0]]
   2869 
   2870 
   2871 def _convert_other(other, raiseit = False, allow_float = False):
   2872     if isinstance(other, Decimal):
   2873         return other
   2874     if isinstance(other, (int, long)):
   2875         return Decimal(other)
   2876     if allow_float and isinstance(other, float):
   2877         return Decimal.from_float(other)
   2878     if raiseit:
   2879         raise TypeError('Unable to convert %s to Decimal' % other)
   2880     return NotImplemented
   2881 
   2882 
   2883 DefaultContext = Context(prec=28, rounding=ROUND_HALF_EVEN, traps=[DivisionByZero, Overflow, InvalidOperation], flags=[], Emax=999999999, Emin=-999999999, capitals=1)
   2884 BasicContext = Context(prec=9, rounding=ROUND_HALF_UP, traps=[DivisionByZero,
   2885  Overflow,
   2886  InvalidOperation,
   2887  Clamped,
   2888  Underflow], flags=[])
   2889 ExtendedContext = Context(prec=9, rounding=ROUND_HALF_EVEN, traps=[], flags=[])
   2890 import re
   2891 _parser = re.compile('        # A numeric string consists of:\n#    \\s*\n    (?P<sign>[-+])?              # an optional sign, followed by either...\n    (\n        (?=\\d|\\.\\d)              # ...a number (with at least one digit)\n        (?P<int>\\d*)             # having a (possibly empty) integer part\n        (\\.(?P<frac>\\d*))?       # followed by an optional fractional part\n        (E(?P<exp>[-+]?\\d+))?    # followed by an optional exponent, or...\n    |\n        Inf(inity)?              # ...an infinity, or...\n    |\n        (?P<signal>s)?           # ...an (optionally signaling)\n        NaN                      # NaN\n        (?P<diag>\\d*)            # with (possibly empty) diagnostic info.\n    )\n#    \\s*\n    \\Z\n', re.VERBOSE | re.IGNORECASE | re.UNICODE).match
   2892 _all_zeros = re.compile('0*$').match
   2893 _exact_half = re.compile('50*$').match
   2894 _parse_format_specifier_regex = re.compile('\\A\n(?:\n   (?P<fill>.)?\n   (?P<align>[<>=^])\n)?\n(?P<sign>[-+ ])?\n(?P<zeropad>0)?\n(?P<minimumwidth>(?!0)\\d+)?\n(?P<thousands_sep>,)?\n(?:\\.(?P<precision>0|(?!0)\\d+))?\n(?P<type>[eEfFgGn%])?\n\\Z\n', re.VERBOSE)
   2895 del re
   2896 try:
   2897     import locale as _locale
   2898 except ImportError:
   2899     pass
   2900 
   2901 def _parse_format_specifier(format_spec, _localeconv = None):
   2902     m = _parse_format_specifier_regex.match(format_spec)
   2903     if m is None:
   2904         raise ValueError('Invalid format specifier: ' + format_spec)
   2905     format_dict = m.groupdict()
   2906     fill = format_dict['fill']
   2907     align = format_dict['align']
   2908     format_dict['zeropad'] = format_dict['zeropad'] is not None
   2909     if format_dict['zeropad']:
   2910         if fill is not None:
   2911             raise ValueError("Fill character conflicts with '0' in format specifier: " + format_spec)
   2912         if align is not None:
   2913             raise ValueError("Alignment conflicts with '0' in format specifier: " + format_spec)
   2914     format_dict['fill'] = fill or ' '
   2915     format_dict['align'] = align or '>'
   2916     if format_dict['sign'] is None:
   2917         format_dict['sign'] = '-'
   2918     format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
   2919     if format_dict['precision'] is not None:
   2920         format_dict['precision'] = int(format_dict['precision'])
   2921     if format_dict['precision'] == 0:
   2922         if format_dict['type'] is None or format_dict['type'] in 'gG':
   2923             format_dict['precision'] = 1
   2924     if format_dict['type'] == 'n':
   2925         format_dict['type'] = 'g'
   2926         if _localeconv is None:
   2927             _localeconv = _locale.localeconv()
   2928         if format_dict['thousands_sep'] is not None:
   2929             raise ValueError("Explicit thousands separator conflicts with 'n' type in format specifier: " + format_spec)
   2930         format_dict['thousands_sep'] = _localeconv['thousands_sep']
   2931         format_dict['grouping'] = _localeconv['grouping']
   2932         format_dict['decimal_point'] = _localeconv['decimal_point']
   2933     else:
   2934         if format_dict['thousands_sep'] is None:
   2935             format_dict['thousands_sep'] = ''
   2936         format_dict['grouping'] = [3, 0]
   2937         format_dict['decimal_point'] = '.'
   2938     format_dict['unicode'] = isinstance(format_spec, unicode)
   2939     return format_dict
   2940 
   2941 
   2942 def _format_align(sign, body, spec):
   2943     minimumwidth = spec['minimumwidth']
   2944     fill = spec['fill']
   2945     padding = fill * (minimumwidth - len(sign) - len(body))
   2946     align = spec['align']
   2947     if align == '<':
   2948         result = sign + body + padding
   2949     elif align == '>':
   2950         result = padding + sign + body
   2951     elif align == '=':
   2952         result = sign + padding + body
   2953     elif align == '^':
   2954         half = len(padding) // 2
   2955         result = padding[:half] + sign + body + padding[half:]
   2956     else:
   2957         raise ValueError('Unrecognised alignment field')
   2958     if spec['unicode']:
   2959         result = unicode(result)
   2960     return result
   2961 
   2962 
   2963 def _group_lengths(grouping):
   2964     from itertools import chain, repeat
   2965     if not grouping:
   2966         return []
   2967     if grouping[-1] == 0 and len(grouping) >= 2:
   2968         return chain(grouping[:-1], repeat(grouping[-2]))
   2969     if grouping[-1] == _locale.CHAR_MAX:
   2970         return grouping[:-1]
   2971     raise ValueError('unrecognised format for grouping')
   2972 
   2973 
   2974 def _insert_thousands_sep(digits, spec, min_width = 1):
   2975     sep = spec['thousands_sep']
   2976     grouping = spec['grouping']
   2977     groups = []
   2978     for l in _group_lengths(grouping):
   2979         if l <= 0:
   2980             raise ValueError('group length should be positive')
   2981         l = min(max(len(digits), min_width, 1), l)
   2982         groups.append('0' * (l - len(digits)) + digits[-l:])
   2983         digits = digits[:-l]
   2984         min_width -= l
   2985         if not digits and min_width <= 0:
   2986             break
   2987         min_width -= len(sep)
   2988     else:
   2989         l = max(len(digits), min_width, 1)
   2990         groups.append('0' * (l - len(digits)) + digits[-l:])
   2991 
   2992     return sep.join(reversed(groups))
   2993 
   2994 
   2995 def _format_sign(is_negative, spec):
   2996     if is_negative:
   2997         return '-'
   2998     elif spec['sign'] in ' +':
   2999         return spec['sign']
   3000     else:
   3001         return ''
   3002 
   3003 
   3004 def _format_number(is_negative, intpart, fracpart, exp, spec):
   3005     sign = _format_sign(is_negative, spec)
   3006     if fracpart:
   3007         fracpart = spec['decimal_point'] + fracpart
   3008     if exp != 0 or spec['type'] in 'eE':
   3009         echar = {'E': 'E',
   3010          'e': 'e',
   3011          'G': 'E',
   3012          'g': 'e'}[spec['type']]
   3013         fracpart += '{0}{1:+}'.format(echar, exp)
   3014     if spec['type'] == '%':
   3015         fracpart += '%'
   3016     if spec['zeropad']:
   3017         min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
   3018     else:
   3019         min_width = 0
   3020     intpart = _insert_thousands_sep(intpart, spec, min_width)
   3021     return _format_align(sign, intpart + fracpart, spec)
   3022 
   3023 
   3024 _Infinity = Decimal('Inf')
   3025 _NegativeInfinity = Decimal('-Inf')
   3026 _NaN = Decimal('NaN')
   3027 _Zero = Decimal(0)
   3028 _One = Decimal(1)
   3029 _NegativeOne = Decimal(-1)
   3030 _SignedInfinity = (_Infinity, _NegativeInfinity)
   3031 if __name__ == '__main__':
   3032     import doctest, sys
   3033     doctest.testmod(sys.modules[__name__])