Back to index

python3.2  3.2.2
decimal.py
Go to the documentation of this file.
00001 # Copyright (c) 2004 Python Software Foundation.
00002 # All rights reserved.
00003 
00004 # Written by Eric Price <eprice at tjhsst.edu>
00005 #    and Facundo Batista <facundo at taniquetil.com.ar>
00006 #    and Raymond Hettinger <python at rcn.com>
00007 #    and Aahz <aahz at pobox.com>
00008 #    and Tim Peters
00009 
00010 # This module should be kept in sync with the latest updates of the
00011 # IBM specification as it evolves.  Those updates will be treated
00012 # as bug fixes (deviation from the spec is a compatibility, usability
00013 # bug) and will be backported.  At this point the spec is stabilizing
00014 # and the updates are becoming fewer, smaller, and less significant.
00015 
00016 """
00017 This is an implementation of decimal floating point arithmetic based on
00018 the General Decimal Arithmetic Specification:
00019 
00020     http://speleotrove.com/decimal/decarith.html
00021 
00022 and IEEE standard 854-1987:
00023 
00024     www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
00025 
00026 Decimal floating point has finite precision with arbitrarily large bounds.
00027 
00028 The purpose of this module is to support arithmetic using familiar
00029 "schoolhouse" rules and to avoid some of the tricky representation
00030 issues associated with binary floating point.  The package is especially
00031 useful for financial applications or for contexts where users have
00032 expectations that are at odds with binary floating point (for instance,
00033 in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
00034 of 0.0; Decimal('1.00') % Decimal('0.1') returns the expected
00035 Decimal('0.00')).
00036 
00037 Here are some examples of using the decimal module:
00038 
00039 >>> from decimal import *
00040 >>> setcontext(ExtendedContext)
00041 >>> Decimal(0)
00042 Decimal('0')
00043 >>> Decimal('1')
00044 Decimal('1')
00045 >>> Decimal('-.0123')
00046 Decimal('-0.0123')
00047 >>> Decimal(123456)
00048 Decimal('123456')
00049 >>> Decimal('123.45e12345678901234567890')
00050 Decimal('1.2345E+12345678901234567892')
00051 >>> Decimal('1.33') + Decimal('1.27')
00052 Decimal('2.60')
00053 >>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
00054 Decimal('-2.20')
00055 >>> dig = Decimal(1)
00056 >>> print(dig / Decimal(3))
00057 0.333333333
00058 >>> getcontext().prec = 18
00059 >>> print(dig / Decimal(3))
00060 0.333333333333333333
00061 >>> print(dig.sqrt())
00062 1
00063 >>> print(Decimal(3).sqrt())
00064 1.73205080756887729
00065 >>> print(Decimal(3) ** 123)
00066 4.85192780976896427E+58
00067 >>> inf = Decimal(1) / Decimal(0)
00068 >>> print(inf)
00069 Infinity
00070 >>> neginf = Decimal(-1) / Decimal(0)
00071 >>> print(neginf)
00072 -Infinity
00073 >>> print(neginf + inf)
00074 NaN
00075 >>> print(neginf * inf)
00076 -Infinity
00077 >>> print(dig / 0)
00078 Infinity
00079 >>> getcontext().traps[DivisionByZero] = 1
00080 >>> print(dig / 0)
00081 Traceback (most recent call last):
00082   ...
00083   ...
00084   ...
00085 decimal.DivisionByZero: x / 0
00086 >>> c = Context()
00087 >>> c.traps[InvalidOperation] = 0
00088 >>> print(c.flags[InvalidOperation])
00089 0
00090 >>> c.divide(Decimal(0), Decimal(0))
00091 Decimal('NaN')
00092 >>> c.traps[InvalidOperation] = 1
00093 >>> print(c.flags[InvalidOperation])
00094 1
00095 >>> c.flags[InvalidOperation] = 0
00096 >>> print(c.flags[InvalidOperation])
00097 0
00098 >>> print(c.divide(Decimal(0), Decimal(0)))
00099 Traceback (most recent call last):
00100   ...
00101   ...
00102   ...
00103 decimal.InvalidOperation: 0 / 0
00104 >>> print(c.flags[InvalidOperation])
00105 1
00106 >>> c.flags[InvalidOperation] = 0
00107 >>> c.traps[InvalidOperation] = 0
00108 >>> print(c.divide(Decimal(0), Decimal(0)))
00109 NaN
00110 >>> print(c.flags[InvalidOperation])
00111 1
00112 >>>
00113 """
00114 
00115 __all__ = [
00116     # Two major classes
00117     'Decimal', 'Context',
00118 
00119     # Contexts
00120     'DefaultContext', 'BasicContext', 'ExtendedContext',
00121 
00122     # Exceptions
00123     'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
00124     'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
00125 
00126     # Constants for use in setting up contexts
00127     'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
00128     'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
00129 
00130     # Functions for manipulating contexts
00131     'setcontext', 'getcontext', 'localcontext'
00132 ]
00133 
00134 __version__ = '1.70'    # Highest version of the spec this complies with
00135                         # See http://speleotrove.com/decimal/
00136 
00137 import copy as _copy
00138 import math as _math
00139 import numbers as _numbers
00140 
00141 try:
00142     from collections import namedtuple as _namedtuple
00143     DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
00144 except ImportError:
00145     DecimalTuple = lambda *args: args
00146 
00147 # Rounding
00148 ROUND_DOWN = 'ROUND_DOWN'
00149 ROUND_HALF_UP = 'ROUND_HALF_UP'
00150 ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
00151 ROUND_CEILING = 'ROUND_CEILING'
00152 ROUND_FLOOR = 'ROUND_FLOOR'
00153 ROUND_UP = 'ROUND_UP'
00154 ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
00155 ROUND_05UP = 'ROUND_05UP'
00156 
00157 # Errors
00158 
00159 class DecimalException(ArithmeticError):
00160     """Base exception class.
00161 
00162     Used exceptions derive from this.
00163     If an exception derives from another exception besides this (such as
00164     Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
00165     called if the others are present.  This isn't actually used for
00166     anything, though.
00167 
00168     handle  -- Called when context._raise_error is called and the
00169                trap_enabler is not set.  First argument is self, second is the
00170                context.  More arguments can be given, those being after
00171                the explanation in _raise_error (For example,
00172                context._raise_error(NewError, '(-x)!', self._sign) would
00173                call NewError().handle(context, self._sign).)
00174 
00175     To define a new exception, it should be sufficient to have it derive
00176     from DecimalException.
00177     """
00178     def handle(self, context, *args):
00179         pass
00180 
00181 
00182 class Clamped(DecimalException):
00183     """Exponent of a 0 changed to fit bounds.
00184 
00185     This occurs and signals clamped if the exponent of a result has been
00186     altered in order to fit the constraints of a specific concrete
00187     representation.  This may occur when the exponent of a zero result would
00188     be outside the bounds of a representation, or when a large normal
00189     number would have an encoded exponent that cannot be represented.  In
00190     this latter case, the exponent is reduced to fit and the corresponding
00191     number of zero digits are appended to the coefficient ("fold-down").
00192     """
00193 
00194 class InvalidOperation(DecimalException):
00195     """An invalid operation was performed.
00196 
00197     Various bad things cause this:
00198 
00199     Something creates a signaling NaN
00200     -INF + INF
00201     0 * (+-)INF
00202     (+-)INF / (+-)INF
00203     x % 0
00204     (+-)INF % x
00205     x._rescale( non-integer )
00206     sqrt(-x) , x > 0
00207     0 ** 0
00208     x ** (non-integer)
00209     x ** (+-)INF
00210     An operand is invalid
00211 
00212     The result of the operation after these is a quiet positive NaN,
00213     except when the cause is a signaling NaN, in which case the result is
00214     also a quiet NaN, but with the original sign, and an optional
00215     diagnostic information.
00216     """
00217     def handle(self, context, *args):
00218         if args:
00219             ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
00220             return ans._fix_nan(context)
00221         return _NaN
00222 
00223 class ConversionSyntax(InvalidOperation):
00224     """Trying to convert badly formed string.
00225 
00226     This occurs and signals invalid-operation if an string is being
00227     converted to a number and it does not conform to the numeric string
00228     syntax.  The result is [0,qNaN].
00229     """
00230     def handle(self, context, *args):
00231         return _NaN
00232 
00233 class DivisionByZero(DecimalException, ZeroDivisionError):
00234     """Division by 0.
00235 
00236     This occurs and signals division-by-zero if division of a finite number
00237     by zero was attempted (during a divide-integer or divide operation, or a
00238     power operation with negative right-hand operand), and the dividend was
00239     not zero.
00240 
00241     The result of the operation is [sign,inf], where sign is the exclusive
00242     or of the signs of the operands for divide, or is 1 for an odd power of
00243     -0, for power.
00244     """
00245 
00246     def handle(self, context, sign, *args):
00247         return _SignedInfinity[sign]
00248 
00249 class DivisionImpossible(InvalidOperation):
00250     """Cannot perform the division adequately.
00251 
00252     This occurs and signals invalid-operation if the integer result of a
00253     divide-integer or remainder operation had too many digits (would be
00254     longer than precision).  The result is [0,qNaN].
00255     """
00256 
00257     def handle(self, context, *args):
00258         return _NaN
00259 
00260 class DivisionUndefined(InvalidOperation, ZeroDivisionError):
00261     """Undefined result of division.
00262 
00263     This occurs and signals invalid-operation if division by zero was
00264     attempted (during a divide-integer, divide, or remainder operation), and
00265     the dividend is also zero.  The result is [0,qNaN].
00266     """
00267 
00268     def handle(self, context, *args):
00269         return _NaN
00270 
00271 class Inexact(DecimalException):
00272     """Had to round, losing information.
00273 
00274     This occurs and signals inexact whenever the result of an operation is
00275     not exact (that is, it needed to be rounded and any discarded digits
00276     were non-zero), or if an overflow or underflow condition occurs.  The
00277     result in all cases is unchanged.
00278 
00279     The inexact signal may be tested (or trapped) to determine if a given
00280     operation (or sequence of operations) was inexact.
00281     """
00282 
00283 class InvalidContext(InvalidOperation):
00284     """Invalid context.  Unknown rounding, for example.
00285 
00286     This occurs and signals invalid-operation if an invalid context was
00287     detected during an operation.  This can occur if contexts are not checked
00288     on creation and either the precision exceeds the capability of the
00289     underlying concrete representation or an unknown or unsupported rounding
00290     was specified.  These aspects of the context need only be checked when
00291     the values are required to be used.  The result is [0,qNaN].
00292     """
00293 
00294     def handle(self, context, *args):
00295         return _NaN
00296 
00297 class Rounded(DecimalException):
00298     """Number got rounded (not  necessarily changed during rounding).
00299 
00300     This occurs and signals rounded whenever the result of an operation is
00301     rounded (that is, some zero or non-zero digits were discarded from the
00302     coefficient), or if an overflow or underflow condition occurs.  The
00303     result in all cases is unchanged.
00304 
00305     The rounded signal may be tested (or trapped) to determine if a given
00306     operation (or sequence of operations) caused a loss of precision.
00307     """
00308 
00309 class Subnormal(DecimalException):
00310     """Exponent < Emin before rounding.
00311 
00312     This occurs and signals subnormal whenever the result of a conversion or
00313     operation is subnormal (that is, its adjusted exponent is less than
00314     Emin, before any rounding).  The result in all cases is unchanged.
00315 
00316     The subnormal signal may be tested (or trapped) to determine if a given
00317     or operation (or sequence of operations) yielded a subnormal result.
00318     """
00319 
00320 class Overflow(Inexact, Rounded):
00321     """Numerical overflow.
00322 
00323     This occurs and signals overflow if the adjusted exponent of a result
00324     (from a conversion or from an operation that is not an attempt to divide
00325     by zero), after rounding, would be greater than the largest value that
00326     can be handled by the implementation (the value Emax).
00327 
00328     The result depends on the rounding mode:
00329 
00330     For round-half-up and round-half-even (and for round-half-down and
00331     round-up, if implemented), the result of the operation is [sign,inf],
00332     where sign is the sign of the intermediate result.  For round-down, the
00333     result is the largest finite number that can be represented in the
00334     current precision, with the sign of the intermediate result.  For
00335     round-ceiling, the result is the same as for round-down if the sign of
00336     the intermediate result is 1, or is [0,inf] otherwise.  For round-floor,
00337     the result is the same as for round-down if the sign of the intermediate
00338     result is 0, or is [1,inf] otherwise.  In all cases, Inexact and Rounded
00339     will also be raised.
00340     """
00341 
00342     def handle(self, context, sign, *args):
00343         if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
00344                                 ROUND_HALF_DOWN, ROUND_UP):
00345             return _SignedInfinity[sign]
00346         if sign == 0:
00347             if context.rounding == ROUND_CEILING:
00348                 return _SignedInfinity[sign]
00349             return _dec_from_triple(sign, '9'*context.prec,
00350                             context.Emax-context.prec+1)
00351         if sign == 1:
00352             if context.rounding == ROUND_FLOOR:
00353                 return _SignedInfinity[sign]
00354             return _dec_from_triple(sign, '9'*context.prec,
00355                              context.Emax-context.prec+1)
00356 
00357 
00358 class Underflow(Inexact, Rounded, Subnormal):
00359     """Numerical underflow with result rounded to 0.
00360 
00361     This occurs and signals underflow if a result is inexact and the
00362     adjusted exponent of the result would be smaller (more negative) than
00363     the smallest value that can be handled by the implementation (the value
00364     Emin).  That is, the result is both inexact and subnormal.
00365 
00366     The result after an underflow will be a subnormal number rounded, if
00367     necessary, so that its exponent is not less than Etiny.  This may result
00368     in 0 with the sign of the intermediate result and an exponent of Etiny.
00369 
00370     In all cases, Inexact, Rounded, and Subnormal will also be raised.
00371     """
00372 
00373 # List of public traps and flags
00374 _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
00375            Underflow, InvalidOperation, Subnormal]
00376 
00377 # Map conditions (per the spec) to signals
00378 _condition_map = {ConversionSyntax:InvalidOperation,
00379                   DivisionImpossible:InvalidOperation,
00380                   DivisionUndefined:InvalidOperation,
00381                   InvalidContext:InvalidOperation}
00382 
00383 ##### Context Functions ##################################################
00384 
00385 # The getcontext() and setcontext() function manage access to a thread-local
00386 # current context.  Py2.4 offers direct support for thread locals.  If that
00387 # is not available, use threading.current_thread() which is slower but will
00388 # work for older Pythons.  If threads are not part of the build, create a
00389 # mock threading object with threading.local() returning the module namespace.
00390 
00391 try:
00392     import threading
00393 except ImportError:
00394     # Python was compiled without threads; create a mock object instead
00395     import sys
00396     class MockThreading(object):
00397         def local(self, sys=sys):
00398             return sys.modules[__name__]
00399     threading = MockThreading()
00400     del sys, MockThreading
00401 
00402 try:
00403     threading.local
00404 
00405 except AttributeError:
00406 
00407     # To fix reloading, force it to create a new context
00408     # Old contexts have different exceptions in their dicts, making problems.
00409     if hasattr(threading.current_thread(), '__decimal_context__'):
00410         del threading.current_thread().__decimal_context__
00411 
00412     def setcontext(context):
00413         """Set this thread's context to context."""
00414         if context in (DefaultContext, BasicContext, ExtendedContext):
00415             context = context.copy()
00416             context.clear_flags()
00417         threading.current_thread().__decimal_context__ = context
00418 
00419     def getcontext():
00420         """Returns this thread's context.
00421 
00422         If this thread does not yet have a context, returns
00423         a new context and sets this thread's context.
00424         New contexts are copies of DefaultContext.
00425         """
00426         try:
00427             return threading.current_thread().__decimal_context__
00428         except AttributeError:
00429             context = Context()
00430             threading.current_thread().__decimal_context__ = context
00431             return context
00432 
00433 else:
00434 
00435     local = threading.local()
00436     if hasattr(local, '__decimal_context__'):
00437         del local.__decimal_context__
00438 
00439     def getcontext(_local=local):
00440         """Returns this thread's context.
00441 
00442         If this thread does not yet have a context, returns
00443         a new context and sets this thread's context.
00444         New contexts are copies of DefaultContext.
00445         """
00446         try:
00447             return _local.__decimal_context__
00448         except AttributeError:
00449             context = Context()
00450             _local.__decimal_context__ = context
00451             return context
00452 
00453     def setcontext(context, _local=local):
00454         """Set this thread's context to context."""
00455         if context in (DefaultContext, BasicContext, ExtendedContext):
00456             context = context.copy()
00457             context.clear_flags()
00458         _local.__decimal_context__ = context
00459 
00460     del threading, local        # Don't contaminate the namespace
00461 
00462 def localcontext(ctx=None):
00463     """Return a context manager for a copy of the supplied context
00464 
00465     Uses a copy of the current context if no context is specified
00466     The returned context manager creates a local decimal context
00467     in a with statement:
00468         def sin(x):
00469              with localcontext() as ctx:
00470                  ctx.prec += 2
00471                  # Rest of sin calculation algorithm
00472                  # uses a precision 2 greater than normal
00473              return +s  # Convert result to normal precision
00474 
00475          def sin(x):
00476              with localcontext(ExtendedContext):
00477                  # Rest of sin calculation algorithm
00478                  # uses the Extended Context from the
00479                  # General Decimal Arithmetic Specification
00480              return +s  # Convert result to normal context
00481 
00482     >>> setcontext(DefaultContext)
00483     >>> print(getcontext().prec)
00484     28
00485     >>> with localcontext():
00486     ...     ctx = getcontext()
00487     ...     ctx.prec += 2
00488     ...     print(ctx.prec)
00489     ...
00490     30
00491     >>> with localcontext(ExtendedContext):
00492     ...     print(getcontext().prec)
00493     ...
00494     9
00495     >>> print(getcontext().prec)
00496     28
00497     """
00498     if ctx is None: ctx = getcontext()
00499     return _ContextManager(ctx)
00500 
00501 
00502 ##### Decimal class #######################################################
00503 
00504 # Do not subclass Decimal from numbers.Real and do not register it as such
00505 # (because Decimals are not interoperable with floats).  See the notes in
00506 # numbers.py for more detail.
00507 
00508 class Decimal(object):
00509     """Floating point class for decimal arithmetic."""
00510 
00511     __slots__ = ('_exp','_int','_sign', '_is_special')
00512     # Generally, the value of the Decimal instance is given by
00513     #  (-1)**_sign * _int * 10**_exp
00514     # Special values are signified by _is_special == True
00515 
00516     # We're immutable, so use __new__ not __init__
00517     def __new__(cls, value="0", context=None):
00518         """Create a decimal point instance.
00519 
00520         >>> Decimal('3.14')              # string input
00521         Decimal('3.14')
00522         >>> Decimal((0, (3, 1, 4), -2))  # tuple (sign, digit_tuple, exponent)
00523         Decimal('3.14')
00524         >>> Decimal(314)                 # int
00525         Decimal('314')
00526         >>> Decimal(Decimal(314))        # another decimal instance
00527         Decimal('314')
00528         >>> Decimal('  3.14  \\n')        # leading and trailing whitespace okay
00529         Decimal('3.14')
00530         """
00531 
00532         # Note that the coefficient, self._int, is actually stored as
00533         # a string rather than as a tuple of digits.  This speeds up
00534         # the "digits to integer" and "integer to digits" conversions
00535         # that are used in almost every arithmetic operation on
00536         # Decimals.  This is an internal detail: the as_tuple function
00537         # and the Decimal constructor still deal with tuples of
00538         # digits.
00539 
00540         self = object.__new__(cls)
00541 
00542         # From a string
00543         # REs insist on real strings, so we can too.
00544         if isinstance(value, str):
00545             m = _parser(value.strip())
00546             if m is None:
00547                 if context is None:
00548                     context = getcontext()
00549                 return context._raise_error(ConversionSyntax,
00550                                 "Invalid literal for Decimal: %r" % value)
00551 
00552             if m.group('sign') == "-":
00553                 self._sign = 1
00554             else:
00555                 self._sign = 0
00556             intpart = m.group('int')
00557             if intpart is not None:
00558                 # finite number
00559                 fracpart = m.group('frac') or ''
00560                 exp = int(m.group('exp') or '0')
00561                 self._int = str(int(intpart+fracpart))
00562                 self._exp = exp - len(fracpart)
00563                 self._is_special = False
00564             else:
00565                 diag = m.group('diag')
00566                 if diag is not None:
00567                     # NaN
00568                     self._int = str(int(diag or '0')).lstrip('0')
00569                     if m.group('signal'):
00570                         self._exp = 'N'
00571                     else:
00572                         self._exp = 'n'
00573                 else:
00574                     # infinity
00575                     self._int = '0'
00576                     self._exp = 'F'
00577                 self._is_special = True
00578             return self
00579 
00580         # From an integer
00581         if isinstance(value, int):
00582             if value >= 0:
00583                 self._sign = 0
00584             else:
00585                 self._sign = 1
00586             self._exp = 0
00587             self._int = str(abs(value))
00588             self._is_special = False
00589             return self
00590 
00591         # From another decimal
00592         if isinstance(value, Decimal):
00593             self._exp  = value._exp
00594             self._sign = value._sign
00595             self._int  = value._int
00596             self._is_special  = value._is_special
00597             return self
00598 
00599         # From an internal working value
00600         if isinstance(value, _WorkRep):
00601             self._sign = value.sign
00602             self._int = str(value.int)
00603             self._exp = int(value.exp)
00604             self._is_special = False
00605             return self
00606 
00607         # tuple/list conversion (possibly from as_tuple())
00608         if isinstance(value, (list,tuple)):
00609             if len(value) != 3:
00610                 raise ValueError('Invalid tuple size in creation of Decimal '
00611                                  'from list or tuple.  The list or tuple '
00612                                  'should have exactly three elements.')
00613             # process sign.  The isinstance test rejects floats
00614             if not (isinstance(value[0], int) and value[0] in (0,1)):
00615                 raise ValueError("Invalid sign.  The first value in the tuple "
00616                                  "should be an integer; either 0 for a "
00617                                  "positive number or 1 for a negative number.")
00618             self._sign = value[0]
00619             if value[2] == 'F':
00620                 # infinity: value[1] is ignored
00621                 self._int = '0'
00622                 self._exp = value[2]
00623                 self._is_special = True
00624             else:
00625                 # process and validate the digits in value[1]
00626                 digits = []
00627                 for digit in value[1]:
00628                     if isinstance(digit, int) and 0 <= digit <= 9:
00629                         # skip leading zeros
00630                         if digits or digit != 0:
00631                             digits.append(digit)
00632                     else:
00633                         raise ValueError("The second value in the tuple must "
00634                                          "be composed of integers in the range "
00635                                          "0 through 9.")
00636                 if value[2] in ('n', 'N'):
00637                     # NaN: digits form the diagnostic
00638                     self._int = ''.join(map(str, digits))
00639                     self._exp = value[2]
00640                     self._is_special = True
00641                 elif isinstance(value[2], int):
00642                     # finite number: digits give the coefficient
00643                     self._int = ''.join(map(str, digits or [0]))
00644                     self._exp = value[2]
00645                     self._is_special = False
00646                 else:
00647                     raise ValueError("The third value in the tuple must "
00648                                      "be an integer, or one of the "
00649                                      "strings 'F', 'n', 'N'.")
00650             return self
00651 
00652         if isinstance(value, float):
00653             value = Decimal.from_float(value)
00654             self._exp  = value._exp
00655             self._sign = value._sign
00656             self._int  = value._int
00657             self._is_special  = value._is_special
00658             return self
00659 
00660         raise TypeError("Cannot convert %r to Decimal" % value)
00661 
00662     # @classmethod, but @decorator is not valid Python 2.3 syntax, so
00663     # don't use it (see notes on Py2.3 compatibility at top of file)
00664     def from_float(cls, f):
00665         """Converts a float to a decimal number, exactly.
00666 
00667         Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
00668         Since 0.1 is not exactly representable in binary floating point, the
00669         value is stored as the nearest representable value which is
00670         0x1.999999999999ap-4.  The exact equivalent of the value in decimal
00671         is 0.1000000000000000055511151231257827021181583404541015625.
00672 
00673         >>> Decimal.from_float(0.1)
00674         Decimal('0.1000000000000000055511151231257827021181583404541015625')
00675         >>> Decimal.from_float(float('nan'))
00676         Decimal('NaN')
00677         >>> Decimal.from_float(float('inf'))
00678         Decimal('Infinity')
00679         >>> Decimal.from_float(-float('inf'))
00680         Decimal('-Infinity')
00681         >>> Decimal.from_float(-0.0)
00682         Decimal('-0')
00683 
00684         """
00685         if isinstance(f, int):                # handle integer inputs
00686             return cls(f)
00687         if _math.isinf(f) or _math.isnan(f):  # raises TypeError if not a float
00688             return cls(repr(f))
00689         if _math.copysign(1.0, f) == 1.0:
00690             sign = 0
00691         else:
00692             sign = 1
00693         n, d = abs(f).as_integer_ratio()
00694         k = d.bit_length() - 1
00695         result = _dec_from_triple(sign, str(n*5**k), -k)
00696         if cls is Decimal:
00697             return result
00698         else:
00699             return cls(result)
00700     from_float = classmethod(from_float)
00701 
00702     def _isnan(self):
00703         """Returns whether the number is not actually one.
00704 
00705         0 if a number
00706         1 if NaN
00707         2 if sNaN
00708         """
00709         if self._is_special:
00710             exp = self._exp
00711             if exp == 'n':
00712                 return 1
00713             elif exp == 'N':
00714                 return 2
00715         return 0
00716 
00717     def _isinfinity(self):
00718         """Returns whether the number is infinite
00719 
00720         0 if finite or not a number
00721         1 if +INF
00722         -1 if -INF
00723         """
00724         if self._exp == 'F':
00725             if self._sign:
00726                 return -1
00727             return 1
00728         return 0
00729 
00730     def _check_nans(self, other=None, context=None):
00731         """Returns whether the number is not actually one.
00732 
00733         if self, other are sNaN, signal
00734         if self, other are NaN return nan
00735         return 0
00736 
00737         Done before operations.
00738         """
00739 
00740         self_is_nan = self._isnan()
00741         if other is None:
00742             other_is_nan = False
00743         else:
00744             other_is_nan = other._isnan()
00745 
00746         if self_is_nan or other_is_nan:
00747             if context is None:
00748                 context = getcontext()
00749 
00750             if self_is_nan == 2:
00751                 return context._raise_error(InvalidOperation, 'sNaN',
00752                                         self)
00753             if other_is_nan == 2:
00754                 return context._raise_error(InvalidOperation, 'sNaN',
00755                                         other)
00756             if self_is_nan:
00757                 return self._fix_nan(context)
00758 
00759             return other._fix_nan(context)
00760         return 0
00761 
00762     def _compare_check_nans(self, other, context):
00763         """Version of _check_nans used for the signaling comparisons
00764         compare_signal, __le__, __lt__, __ge__, __gt__.
00765 
00766         Signal InvalidOperation if either self or other is a (quiet
00767         or signaling) NaN.  Signaling NaNs take precedence over quiet
00768         NaNs.
00769 
00770         Return 0 if neither operand is a NaN.
00771 
00772         """
00773         if context is None:
00774             context = getcontext()
00775 
00776         if self._is_special or other._is_special:
00777             if self.is_snan():
00778                 return context._raise_error(InvalidOperation,
00779                                             'comparison involving sNaN',
00780                                             self)
00781             elif other.is_snan():
00782                 return context._raise_error(InvalidOperation,
00783                                             'comparison involving sNaN',
00784                                             other)
00785             elif self.is_qnan():
00786                 return context._raise_error(InvalidOperation,
00787                                             'comparison involving NaN',
00788                                             self)
00789             elif other.is_qnan():
00790                 return context._raise_error(InvalidOperation,
00791                                             'comparison involving NaN',
00792                                             other)
00793         return 0
00794 
00795     def __bool__(self):
00796         """Return True if self is nonzero; otherwise return False.
00797 
00798         NaNs and infinities are considered nonzero.
00799         """
00800         return self._is_special or self._int != '0'
00801 
00802     def _cmp(self, other):
00803         """Compare the two non-NaN decimal instances self and other.
00804 
00805         Returns -1 if self < other, 0 if self == other and 1
00806         if self > other.  This routine is for internal use only."""
00807 
00808         if self._is_special or other._is_special:
00809             self_inf = self._isinfinity()
00810             other_inf = other._isinfinity()
00811             if self_inf == other_inf:
00812                 return 0
00813             elif self_inf < other_inf:
00814                 return -1
00815             else:
00816                 return 1
00817 
00818         # check for zeros;  Decimal('0') == Decimal('-0')
00819         if not self:
00820             if not other:
00821                 return 0
00822             else:
00823                 return -((-1)**other._sign)
00824         if not other:
00825             return (-1)**self._sign
00826 
00827         # If different signs, neg one is less
00828         if other._sign < self._sign:
00829             return -1
00830         if self._sign < other._sign:
00831             return 1
00832 
00833         self_adjusted = self.adjusted()
00834         other_adjusted = other.adjusted()
00835         if self_adjusted == other_adjusted:
00836             self_padded = self._int + '0'*(self._exp - other._exp)
00837             other_padded = other._int + '0'*(other._exp - self._exp)
00838             if self_padded == other_padded:
00839                 return 0
00840             elif self_padded < other_padded:
00841                 return -(-1)**self._sign
00842             else:
00843                 return (-1)**self._sign
00844         elif self_adjusted > other_adjusted:
00845             return (-1)**self._sign
00846         else: # self_adjusted < other_adjusted
00847             return -((-1)**self._sign)
00848 
00849     # Note: The Decimal standard doesn't cover rich comparisons for
00850     # Decimals.  In particular, the specification is silent on the
00851     # subject of what should happen for a comparison involving a NaN.
00852     # We take the following approach:
00853     #
00854     #   == comparisons involving a quiet NaN always return False
00855     #   != comparisons involving a quiet NaN always return True
00856     #   == or != comparisons involving a signaling NaN signal
00857     #      InvalidOperation, and return False or True as above if the
00858     #      InvalidOperation is not trapped.
00859     #   <, >, <= and >= comparisons involving a (quiet or signaling)
00860     #      NaN signal InvalidOperation, and return False if the
00861     #      InvalidOperation is not trapped.
00862     #
00863     # This behavior is designed to conform as closely as possible to
00864     # that specified by IEEE 754.
00865 
00866     def __eq__(self, other, context=None):
00867         self, other = _convert_for_comparison(self, other, equality_op=True)
00868         if other is NotImplemented:
00869             return other
00870         if self._check_nans(other, context):
00871             return False
00872         return self._cmp(other) == 0
00873 
00874     def __ne__(self, other, context=None):
00875         self, other = _convert_for_comparison(self, other, equality_op=True)
00876         if other is NotImplemented:
00877             return other
00878         if self._check_nans(other, context):
00879             return True
00880         return self._cmp(other) != 0
00881 
00882 
00883     def __lt__(self, other, context=None):
00884         self, other = _convert_for_comparison(self, other)
00885         if other is NotImplemented:
00886             return other
00887         ans = self._compare_check_nans(other, context)
00888         if ans:
00889             return False
00890         return self._cmp(other) < 0
00891 
00892     def __le__(self, other, context=None):
00893         self, other = _convert_for_comparison(self, other)
00894         if other is NotImplemented:
00895             return other
00896         ans = self._compare_check_nans(other, context)
00897         if ans:
00898             return False
00899         return self._cmp(other) <= 0
00900 
00901     def __gt__(self, other, context=None):
00902         self, other = _convert_for_comparison(self, other)
00903         if other is NotImplemented:
00904             return other
00905         ans = self._compare_check_nans(other, context)
00906         if ans:
00907             return False
00908         return self._cmp(other) > 0
00909 
00910     def __ge__(self, other, context=None):
00911         self, other = _convert_for_comparison(self, other)
00912         if other is NotImplemented:
00913             return other
00914         ans = self._compare_check_nans(other, context)
00915         if ans:
00916             return False
00917         return self._cmp(other) >= 0
00918 
00919     def compare(self, other, context=None):
00920         """Compares one to another.
00921 
00922         -1 => a < b
00923         0  => a = b
00924         1  => a > b
00925         NaN => one is NaN
00926         Like __cmp__, but returns Decimal instances.
00927         """
00928         other = _convert_other(other, raiseit=True)
00929 
00930         # Compare(NaN, NaN) = NaN
00931         if (self._is_special or other and other._is_special):
00932             ans = self._check_nans(other, context)
00933             if ans:
00934                 return ans
00935 
00936         return Decimal(self._cmp(other))
00937 
00938     def __hash__(self):
00939         """x.__hash__() <==> hash(x)"""
00940 
00941         # In order to make sure that the hash of a Decimal instance
00942         # agrees with the hash of a numerically equal integer, float
00943         # or Fraction, we follow the rules for numeric hashes outlined
00944         # in the documentation.  (See library docs, 'Built-in Types').
00945         if self._is_special:
00946             if self.is_snan():
00947                 raise TypeError('Cannot hash a signaling NaN value.')
00948             elif self.is_nan():
00949                 return _PyHASH_NAN
00950             else:
00951                 if self._sign:
00952                     return -_PyHASH_INF
00953                 else:
00954                     return _PyHASH_INF
00955 
00956         if self._exp >= 0:
00957             exp_hash = pow(10, self._exp, _PyHASH_MODULUS)
00958         else:
00959             exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS)
00960         hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS
00961         ans = hash_ if self >= 0 else -hash_
00962         return -2 if ans == -1 else ans
00963 
00964     def as_tuple(self):
00965         """Represents the number as a triple tuple.
00966 
00967         To show the internals exactly as they are.
00968         """
00969         return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
00970 
00971     def __repr__(self):
00972         """Represents the number as an instance of Decimal."""
00973         # Invariant:  eval(repr(d)) == d
00974         return "Decimal('%s')" % str(self)
00975 
00976     def __str__(self, eng=False, context=None):
00977         """Return string representation of the number in scientific notation.
00978 
00979         Captures all of the information in the underlying representation.
00980         """
00981 
00982         sign = ['', '-'][self._sign]
00983         if self._is_special:
00984             if self._exp == 'F':
00985                 return sign + 'Infinity'
00986             elif self._exp == 'n':
00987                 return sign + 'NaN' + self._int
00988             else: # self._exp == 'N'
00989                 return sign + 'sNaN' + self._int
00990 
00991         # number of digits of self._int to left of decimal point
00992         leftdigits = self._exp + len(self._int)
00993 
00994         # dotplace is number of digits of self._int to the left of the
00995         # decimal point in the mantissa of the output string (that is,
00996         # after adjusting the exponent)
00997         if self._exp <= 0 and leftdigits > -6:
00998             # no exponent required
00999             dotplace = leftdigits
01000         elif not eng:
01001             # usual scientific notation: 1 digit on left of the point
01002             dotplace = 1
01003         elif self._int == '0':
01004             # engineering notation, zero
01005             dotplace = (leftdigits + 1) % 3 - 1
01006         else:
01007             # engineering notation, nonzero
01008             dotplace = (leftdigits - 1) % 3 + 1
01009 
01010         if dotplace <= 0:
01011             intpart = '0'
01012             fracpart = '.' + '0'*(-dotplace) + self._int
01013         elif dotplace >= len(self._int):
01014             intpart = self._int+'0'*(dotplace-len(self._int))
01015             fracpart = ''
01016         else:
01017             intpart = self._int[:dotplace]
01018             fracpart = '.' + self._int[dotplace:]
01019         if leftdigits == dotplace:
01020             exp = ''
01021         else:
01022             if context is None:
01023                 context = getcontext()
01024             exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
01025 
01026         return sign + intpart + fracpart + exp
01027 
01028     def to_eng_string(self, context=None):
01029         """Convert to engineering-type string.
01030 
01031         Engineering notation has an exponent which is a multiple of 3, so there
01032         are up to 3 digits left of the decimal place.
01033 
01034         Same rules for when in exponential and when as a value as in __str__.
01035         """
01036         return self.__str__(eng=True, context=context)
01037 
01038     def __neg__(self, context=None):
01039         """Returns a copy with the sign switched.
01040 
01041         Rounds, if it has reason.
01042         """
01043         if self._is_special:
01044             ans = self._check_nans(context=context)
01045             if ans:
01046                 return ans
01047 
01048         if context is None:
01049             context = getcontext()
01050 
01051         if not self and context.rounding != ROUND_FLOOR:
01052             # -Decimal('0') is Decimal('0'), not Decimal('-0'), except
01053             # in ROUND_FLOOR rounding mode.
01054             ans = self.copy_abs()
01055         else:
01056             ans = self.copy_negate()
01057 
01058         return ans._fix(context)
01059 
01060     def __pos__(self, context=None):
01061         """Returns a copy, unless it is a sNaN.
01062 
01063         Rounds the number (if more then precision digits)
01064         """
01065         if self._is_special:
01066             ans = self._check_nans(context=context)
01067             if ans:
01068                 return ans
01069 
01070         if context is None:
01071             context = getcontext()
01072 
01073         if not self and context.rounding != ROUND_FLOOR:
01074             # + (-0) = 0, except in ROUND_FLOOR rounding mode.
01075             ans = self.copy_abs()
01076         else:
01077             ans = Decimal(self)
01078 
01079         return ans._fix(context)
01080 
01081     def __abs__(self, round=True, context=None):
01082         """Returns the absolute value of self.
01083 
01084         If the keyword argument 'round' is false, do not round.  The
01085         expression self.__abs__(round=False) is equivalent to
01086         self.copy_abs().
01087         """
01088         if not round:
01089             return self.copy_abs()
01090 
01091         if self._is_special:
01092             ans = self._check_nans(context=context)
01093             if ans:
01094                 return ans
01095 
01096         if self._sign:
01097             ans = self.__neg__(context=context)
01098         else:
01099             ans = self.__pos__(context=context)
01100 
01101         return ans
01102 
01103     def __add__(self, other, context=None):
01104         """Returns self + other.
01105 
01106         -INF + INF (or the reverse) cause InvalidOperation errors.
01107         """
01108         other = _convert_other(other)
01109         if other is NotImplemented:
01110             return other
01111 
01112         if context is None:
01113             context = getcontext()
01114 
01115         if self._is_special or other._is_special:
01116             ans = self._check_nans(other, context)
01117             if ans:
01118                 return ans
01119 
01120             if self._isinfinity():
01121                 # If both INF, same sign => same as both, opposite => error.
01122                 if self._sign != other._sign and other._isinfinity():
01123                     return context._raise_error(InvalidOperation, '-INF + INF')
01124                 return Decimal(self)
01125             if other._isinfinity():
01126                 return Decimal(other)  # Can't both be infinity here
01127 
01128         exp = min(self._exp, other._exp)
01129         negativezero = 0
01130         if context.rounding == ROUND_FLOOR and self._sign != other._sign:
01131             # If the answer is 0, the sign should be negative, in this case.
01132             negativezero = 1
01133 
01134         if not self and not other:
01135             sign = min(self._sign, other._sign)
01136             if negativezero:
01137                 sign = 1
01138             ans = _dec_from_triple(sign, '0', exp)
01139             ans = ans._fix(context)
01140             return ans
01141         if not self:
01142             exp = max(exp, other._exp - context.prec-1)
01143             ans = other._rescale(exp, context.rounding)
01144             ans = ans._fix(context)
01145             return ans
01146         if not other:
01147             exp = max(exp, self._exp - context.prec-1)
01148             ans = self._rescale(exp, context.rounding)
01149             ans = ans._fix(context)
01150             return ans
01151 
01152         op1 = _WorkRep(self)
01153         op2 = _WorkRep(other)
01154         op1, op2 = _normalize(op1, op2, context.prec)
01155 
01156         result = _WorkRep()
01157         if op1.sign != op2.sign:
01158             # Equal and opposite
01159             if op1.int == op2.int:
01160                 ans = _dec_from_triple(negativezero, '0', exp)
01161                 ans = ans._fix(context)
01162                 return ans
01163             if op1.int < op2.int:
01164                 op1, op2 = op2, op1
01165                 # OK, now abs(op1) > abs(op2)
01166             if op1.sign == 1:
01167                 result.sign = 1
01168                 op1.sign, op2.sign = op2.sign, op1.sign
01169             else:
01170                 result.sign = 0
01171                 # So we know the sign, and op1 > 0.
01172         elif op1.sign == 1:
01173             result.sign = 1
01174             op1.sign, op2.sign = (0, 0)
01175         else:
01176             result.sign = 0
01177         # Now, op1 > abs(op2) > 0
01178 
01179         if op2.sign == 0:
01180             result.int = op1.int + op2.int
01181         else:
01182             result.int = op1.int - op2.int
01183 
01184         result.exp = op1.exp
01185         ans = Decimal(result)
01186         ans = ans._fix(context)
01187         return ans
01188 
01189     __radd__ = __add__
01190 
01191     def __sub__(self, other, context=None):
01192         """Return self - other"""
01193         other = _convert_other(other)
01194         if other is NotImplemented:
01195             return other
01196 
01197         if self._is_special or other._is_special:
01198             ans = self._check_nans(other, context=context)
01199             if ans:
01200                 return ans
01201 
01202         # self - other is computed as self + other.copy_negate()
01203         return self.__add__(other.copy_negate(), context=context)
01204 
01205     def __rsub__(self, other, context=None):
01206         """Return other - self"""
01207         other = _convert_other(other)
01208         if other is NotImplemented:
01209             return other
01210 
01211         return other.__sub__(self, context=context)
01212 
01213     def __mul__(self, other, context=None):
01214         """Return self * other.
01215 
01216         (+-) INF * 0 (or its reverse) raise InvalidOperation.
01217         """
01218         other = _convert_other(other)
01219         if other is NotImplemented:
01220             return other
01221 
01222         if context is None:
01223             context = getcontext()
01224 
01225         resultsign = self._sign ^ other._sign
01226 
01227         if self._is_special or other._is_special:
01228             ans = self._check_nans(other, context)
01229             if ans:
01230                 return ans
01231 
01232             if self._isinfinity():
01233                 if not other:
01234                     return context._raise_error(InvalidOperation, '(+-)INF * 0')
01235                 return _SignedInfinity[resultsign]
01236 
01237             if other._isinfinity():
01238                 if not self:
01239                     return context._raise_error(InvalidOperation, '0 * (+-)INF')
01240                 return _SignedInfinity[resultsign]
01241 
01242         resultexp = self._exp + other._exp
01243 
01244         # Special case for multiplying by zero
01245         if not self or not other:
01246             ans = _dec_from_triple(resultsign, '0', resultexp)
01247             # Fixing in case the exponent is out of bounds
01248             ans = ans._fix(context)
01249             return ans
01250 
01251         # Special case for multiplying by power of 10
01252         if self._int == '1':
01253             ans = _dec_from_triple(resultsign, other._int, resultexp)
01254             ans = ans._fix(context)
01255             return ans
01256         if other._int == '1':
01257             ans = _dec_from_triple(resultsign, self._int, resultexp)
01258             ans = ans._fix(context)
01259             return ans
01260 
01261         op1 = _WorkRep(self)
01262         op2 = _WorkRep(other)
01263 
01264         ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
01265         ans = ans._fix(context)
01266 
01267         return ans
01268     __rmul__ = __mul__
01269 
01270     def __truediv__(self, other, context=None):
01271         """Return self / other."""
01272         other = _convert_other(other)
01273         if other is NotImplemented:
01274             return NotImplemented
01275 
01276         if context is None:
01277             context = getcontext()
01278 
01279         sign = self._sign ^ other._sign
01280 
01281         if self._is_special or other._is_special:
01282             ans = self._check_nans(other, context)
01283             if ans:
01284                 return ans
01285 
01286             if self._isinfinity() and other._isinfinity():
01287                 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
01288 
01289             if self._isinfinity():
01290                 return _SignedInfinity[sign]
01291 
01292             if other._isinfinity():
01293                 context._raise_error(Clamped, 'Division by infinity')
01294                 return _dec_from_triple(sign, '0', context.Etiny())
01295 
01296         # Special cases for zeroes
01297         if not other:
01298             if not self:
01299                 return context._raise_error(DivisionUndefined, '0 / 0')
01300             return context._raise_error(DivisionByZero, 'x / 0', sign)
01301 
01302         if not self:
01303             exp = self._exp - other._exp
01304             coeff = 0
01305         else:
01306             # OK, so neither = 0, INF or NaN
01307             shift = len(other._int) - len(self._int) + context.prec + 1
01308             exp = self._exp - other._exp - shift
01309             op1 = _WorkRep(self)
01310             op2 = _WorkRep(other)
01311             if shift >= 0:
01312                 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
01313             else:
01314                 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
01315             if remainder:
01316                 # result is not exact; adjust to ensure correct rounding
01317                 if coeff % 5 == 0:
01318                     coeff += 1
01319             else:
01320                 # result is exact; get as close to ideal exponent as possible
01321                 ideal_exp = self._exp - other._exp
01322                 while exp < ideal_exp and coeff % 10 == 0:
01323                     coeff //= 10
01324                     exp += 1
01325 
01326         ans = _dec_from_triple(sign, str(coeff), exp)
01327         return ans._fix(context)
01328 
01329     def _divide(self, other, context):
01330         """Return (self // other, self % other), to context.prec precision.
01331 
01332         Assumes that neither self nor other is a NaN, that self is not
01333         infinite and that other is nonzero.
01334         """
01335         sign = self._sign ^ other._sign
01336         if other._isinfinity():
01337             ideal_exp = self._exp
01338         else:
01339             ideal_exp = min(self._exp, other._exp)
01340 
01341         expdiff = self.adjusted() - other.adjusted()
01342         if not self or other._isinfinity() or expdiff <= -2:
01343             return (_dec_from_triple(sign, '0', 0),
01344                     self._rescale(ideal_exp, context.rounding))
01345         if expdiff <= context.prec:
01346             op1 = _WorkRep(self)
01347             op2 = _WorkRep(other)
01348             if op1.exp >= op2.exp:
01349                 op1.int *= 10**(op1.exp - op2.exp)
01350             else:
01351                 op2.int *= 10**(op2.exp - op1.exp)
01352             q, r = divmod(op1.int, op2.int)
01353             if q < 10**context.prec:
01354                 return (_dec_from_triple(sign, str(q), 0),
01355                         _dec_from_triple(self._sign, str(r), ideal_exp))
01356 
01357         # Here the quotient is too large to be representable
01358         ans = context._raise_error(DivisionImpossible,
01359                                    'quotient too large in //, % or divmod')
01360         return ans, ans
01361 
01362     def __rtruediv__(self, other, context=None):
01363         """Swaps self/other and returns __truediv__."""
01364         other = _convert_other(other)
01365         if other is NotImplemented:
01366             return other
01367         return other.__truediv__(self, context=context)
01368 
01369     def __divmod__(self, other, context=None):
01370         """
01371         Return (self // other, self % other)
01372         """
01373         other = _convert_other(other)
01374         if other is NotImplemented:
01375             return other
01376 
01377         if context is None:
01378             context = getcontext()
01379 
01380         ans = self._check_nans(other, context)
01381         if ans:
01382             return (ans, ans)
01383 
01384         sign = self._sign ^ other._sign
01385         if self._isinfinity():
01386             if other._isinfinity():
01387                 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
01388                 return ans, ans
01389             else:
01390                 return (_SignedInfinity[sign],
01391                         context._raise_error(InvalidOperation, 'INF % x'))
01392 
01393         if not other:
01394             if not self:
01395                 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
01396                 return ans, ans
01397             else:
01398                 return (context._raise_error(DivisionByZero, 'x // 0', sign),
01399                         context._raise_error(InvalidOperation, 'x % 0'))
01400 
01401         quotient, remainder = self._divide(other, context)
01402         remainder = remainder._fix(context)
01403         return quotient, remainder
01404 
01405     def __rdivmod__(self, other, context=None):
01406         """Swaps self/other and returns __divmod__."""
01407         other = _convert_other(other)
01408         if other is NotImplemented:
01409             return other
01410         return other.__divmod__(self, context=context)
01411 
01412     def __mod__(self, other, context=None):
01413         """
01414         self % other
01415         """
01416         other = _convert_other(other)
01417         if other is NotImplemented:
01418             return other
01419 
01420         if context is None:
01421             context = getcontext()
01422 
01423         ans = self._check_nans(other, context)
01424         if ans:
01425             return ans
01426 
01427         if self._isinfinity():
01428             return context._raise_error(InvalidOperation, 'INF % x')
01429         elif not other:
01430             if self:
01431                 return context._raise_error(InvalidOperation, 'x % 0')
01432             else:
01433                 return context._raise_error(DivisionUndefined, '0 % 0')
01434 
01435         remainder = self._divide(other, context)[1]
01436         remainder = remainder._fix(context)
01437         return remainder
01438 
01439     def __rmod__(self, other, context=None):
01440         """Swaps self/other and returns __mod__."""
01441         other = _convert_other(other)
01442         if other is NotImplemented:
01443             return other
01444         return other.__mod__(self, context=context)
01445 
01446     def remainder_near(self, other, context=None):
01447         """
01448         Remainder nearest to 0-  abs(remainder-near) <= other/2
01449         """
01450         if context is None:
01451             context = getcontext()
01452 
01453         other = _convert_other(other, raiseit=True)
01454 
01455         ans = self._check_nans(other, context)
01456         if ans:
01457             return ans
01458 
01459         # self == +/-infinity -> InvalidOperation
01460         if self._isinfinity():
01461             return context._raise_error(InvalidOperation,
01462                                         'remainder_near(infinity, x)')
01463 
01464         # other == 0 -> either InvalidOperation or DivisionUndefined
01465         if not other:
01466             if self:
01467                 return context._raise_error(InvalidOperation,
01468                                             'remainder_near(x, 0)')
01469             else:
01470                 return context._raise_error(DivisionUndefined,
01471                                             'remainder_near(0, 0)')
01472 
01473         # other = +/-infinity -> remainder = self
01474         if other._isinfinity():
01475             ans = Decimal(self)
01476             return ans._fix(context)
01477 
01478         # self = 0 -> remainder = self, with ideal exponent
01479         ideal_exponent = min(self._exp, other._exp)
01480         if not self:
01481             ans = _dec_from_triple(self._sign, '0', ideal_exponent)
01482             return ans._fix(context)
01483 
01484         # catch most cases of large or small quotient
01485         expdiff = self.adjusted() - other.adjusted()
01486         if expdiff >= context.prec + 1:
01487             # expdiff >= prec+1 => abs(self/other) > 10**prec
01488             return context._raise_error(DivisionImpossible)
01489         if expdiff <= -2:
01490             # expdiff <= -2 => abs(self/other) < 0.1
01491             ans = self._rescale(ideal_exponent, context.rounding)
01492             return ans._fix(context)
01493 
01494         # adjust both arguments to have the same exponent, then divide
01495         op1 = _WorkRep(self)
01496         op2 = _WorkRep(other)
01497         if op1.exp >= op2.exp:
01498             op1.int *= 10**(op1.exp - op2.exp)
01499         else:
01500             op2.int *= 10**(op2.exp - op1.exp)
01501         q, r = divmod(op1.int, op2.int)
01502         # remainder is r*10**ideal_exponent; other is +/-op2.int *
01503         # 10**ideal_exponent.   Apply correction to ensure that
01504         # abs(remainder) <= abs(other)/2
01505         if 2*r + (q&1) > op2.int:
01506             r -= op2.int
01507             q += 1
01508 
01509         if q >= 10**context.prec:
01510             return context._raise_error(DivisionImpossible)
01511 
01512         # result has same sign as self unless r is negative
01513         sign = self._sign
01514         if r < 0:
01515             sign = 1-sign
01516             r = -r
01517 
01518         ans = _dec_from_triple(sign, str(r), ideal_exponent)
01519         return ans._fix(context)
01520 
01521     def __floordiv__(self, other, context=None):
01522         """self // other"""
01523         other = _convert_other(other)
01524         if other is NotImplemented:
01525             return other
01526 
01527         if context is None:
01528             context = getcontext()
01529 
01530         ans = self._check_nans(other, context)
01531         if ans:
01532             return ans
01533 
01534         if self._isinfinity():
01535             if other._isinfinity():
01536                 return context._raise_error(InvalidOperation, 'INF // INF')
01537             else:
01538                 return _SignedInfinity[self._sign ^ other._sign]
01539 
01540         if not other:
01541             if self:
01542                 return context._raise_error(DivisionByZero, 'x // 0',
01543                                             self._sign ^ other._sign)
01544             else:
01545                 return context._raise_error(DivisionUndefined, '0 // 0')
01546 
01547         return self._divide(other, context)[0]
01548 
01549     def __rfloordiv__(self, other, context=None):
01550         """Swaps self/other and returns __floordiv__."""
01551         other = _convert_other(other)
01552         if other is NotImplemented:
01553             return other
01554         return other.__floordiv__(self, context=context)
01555 
01556     def __float__(self):
01557         """Float representation."""
01558         return float(str(self))
01559 
01560     def __int__(self):
01561         """Converts self to an int, truncating if necessary."""
01562         if self._is_special:
01563             if self._isnan():
01564                 raise ValueError("Cannot convert NaN to integer")
01565             elif self._isinfinity():
01566                 raise OverflowError("Cannot convert infinity to integer")
01567         s = (-1)**self._sign
01568         if self._exp >= 0:
01569             return s*int(self._int)*10**self._exp
01570         else:
01571             return s*int(self._int[:self._exp] or '0')
01572 
01573     __trunc__ = __int__
01574 
01575     def real(self):
01576         return self
01577     real = property(real)
01578 
01579     def imag(self):
01580         return Decimal(0)
01581     imag = property(imag)
01582 
01583     def conjugate(self):
01584         return self
01585 
01586     def __complex__(self):
01587         return complex(float(self))
01588 
01589     def _fix_nan(self, context):
01590         """Decapitate the payload of a NaN to fit the context"""
01591         payload = self._int
01592 
01593         # maximum length of payload is precision if clamp=0,
01594         # precision-1 if clamp=1.
01595         max_payload_len = context.prec - context.clamp
01596         if len(payload) > max_payload_len:
01597             payload = payload[len(payload)-max_payload_len:].lstrip('0')
01598             return _dec_from_triple(self._sign, payload, self._exp, True)
01599         return Decimal(self)
01600 
01601     def _fix(self, context):
01602         """Round if it is necessary to keep self within prec precision.
01603 
01604         Rounds and fixes the exponent.  Does not raise on a sNaN.
01605 
01606         Arguments:
01607         self - Decimal instance
01608         context - context used.
01609         """
01610 
01611         if self._is_special:
01612             if self._isnan():
01613                 # decapitate payload if necessary
01614                 return self._fix_nan(context)
01615             else:
01616                 # self is +/-Infinity; return unaltered
01617                 return Decimal(self)
01618 
01619         # if self is zero then exponent should be between Etiny and
01620         # Emax if clamp==0, and between Etiny and Etop if clamp==1.
01621         Etiny = context.Etiny()
01622         Etop = context.Etop()
01623         if not self:
01624             exp_max = [context.Emax, Etop][context.clamp]
01625             new_exp = min(max(self._exp, Etiny), exp_max)
01626             if new_exp != self._exp:
01627                 context._raise_error(Clamped)
01628                 return _dec_from_triple(self._sign, '0', new_exp)
01629             else:
01630                 return Decimal(self)
01631 
01632         # exp_min is the smallest allowable exponent of the result,
01633         # equal to max(self.adjusted()-context.prec+1, Etiny)
01634         exp_min = len(self._int) + self._exp - context.prec
01635         if exp_min > Etop:
01636             # overflow: exp_min > Etop iff self.adjusted() > Emax
01637             ans = context._raise_error(Overflow, 'above Emax', self._sign)
01638             context._raise_error(Inexact)
01639             context._raise_error(Rounded)
01640             return ans
01641 
01642         self_is_subnormal = exp_min < Etiny
01643         if self_is_subnormal:
01644             exp_min = Etiny
01645 
01646         # round if self has too many digits
01647         if self._exp < exp_min:
01648             digits = len(self._int) + self._exp - exp_min
01649             if digits < 0:
01650                 self = _dec_from_triple(self._sign, '1', exp_min-1)
01651                 digits = 0
01652             rounding_method = self._pick_rounding_function[context.rounding]
01653             changed = rounding_method(self, digits)
01654             coeff = self._int[:digits] or '0'
01655             if changed > 0:
01656                 coeff = str(int(coeff)+1)
01657                 if len(coeff) > context.prec:
01658                     coeff = coeff[:-1]
01659                     exp_min += 1
01660 
01661             # check whether the rounding pushed the exponent out of range
01662             if exp_min > Etop:
01663                 ans = context._raise_error(Overflow, 'above Emax', self._sign)
01664             else:
01665                 ans = _dec_from_triple(self._sign, coeff, exp_min)
01666 
01667             # raise the appropriate signals, taking care to respect
01668             # the precedence described in the specification
01669             if changed and self_is_subnormal:
01670                 context._raise_error(Underflow)
01671             if self_is_subnormal:
01672                 context._raise_error(Subnormal)
01673             if changed:
01674                 context._raise_error(Inexact)
01675             context._raise_error(Rounded)
01676             if not ans:
01677                 # raise Clamped on underflow to 0
01678                 context._raise_error(Clamped)
01679             return ans
01680 
01681         if self_is_subnormal:
01682             context._raise_error(Subnormal)
01683 
01684         # fold down if clamp == 1 and self has too few digits
01685         if context.clamp == 1 and self._exp > Etop:
01686             context._raise_error(Clamped)
01687             self_padded = self._int + '0'*(self._exp - Etop)
01688             return _dec_from_triple(self._sign, self_padded, Etop)
01689 
01690         # here self was representable to begin with; return unchanged
01691         return Decimal(self)
01692 
01693     # for each of the rounding functions below:
01694     #   self is a finite, nonzero Decimal
01695     #   prec is an integer satisfying 0 <= prec < len(self._int)
01696     #
01697     # each function returns either -1, 0, or 1, as follows:
01698     #   1 indicates that self should be rounded up (away from zero)
01699     #   0 indicates that self should be truncated, and that all the
01700     #     digits to be truncated are zeros (so the value is unchanged)
01701     #  -1 indicates that there are nonzero digits to be truncated
01702 
01703     def _round_down(self, prec):
01704         """Also known as round-towards-0, truncate."""
01705         if _all_zeros(self._int, prec):
01706             return 0
01707         else:
01708             return -1
01709 
01710     def _round_up(self, prec):
01711         """Rounds away from 0."""
01712         return -self._round_down(prec)
01713 
01714     def _round_half_up(self, prec):
01715         """Rounds 5 up (away from 0)"""
01716         if self._int[prec] in '56789':
01717             return 1
01718         elif _all_zeros(self._int, prec):
01719             return 0
01720         else:
01721             return -1
01722 
01723     def _round_half_down(self, prec):
01724         """Round 5 down"""
01725         if _exact_half(self._int, prec):
01726             return -1
01727         else:
01728             return self._round_half_up(prec)
01729 
01730     def _round_half_even(self, prec):
01731         """Round 5 to even, rest to nearest."""
01732         if _exact_half(self._int, prec) and \
01733                 (prec == 0 or self._int[prec-1] in '02468'):
01734             return -1
01735         else:
01736             return self._round_half_up(prec)
01737 
01738     def _round_ceiling(self, prec):
01739         """Rounds up (not away from 0 if negative.)"""
01740         if self._sign:
01741             return self._round_down(prec)
01742         else:
01743             return -self._round_down(prec)
01744 
01745     def _round_floor(self, prec):
01746         """Rounds down (not towards 0 if negative)"""
01747         if not self._sign:
01748             return self._round_down(prec)
01749         else:
01750             return -self._round_down(prec)
01751 
01752     def _round_05up(self, prec):
01753         """Round down unless digit prec-1 is 0 or 5."""
01754         if prec and self._int[prec-1] not in '05':
01755             return self._round_down(prec)
01756         else:
01757             return -self._round_down(prec)
01758 
01759     _pick_rounding_function = dict(
01760         ROUND_DOWN = _round_down,
01761         ROUND_UP = _round_up,
01762         ROUND_HALF_UP = _round_half_up,
01763         ROUND_HALF_DOWN = _round_half_down,
01764         ROUND_HALF_EVEN = _round_half_even,
01765         ROUND_CEILING = _round_ceiling,
01766         ROUND_FLOOR = _round_floor,
01767         ROUND_05UP = _round_05up,
01768     )
01769 
01770     def __round__(self, n=None):
01771         """Round self to the nearest integer, or to a given precision.
01772 
01773         If only one argument is supplied, round a finite Decimal
01774         instance self to the nearest integer.  If self is infinite or
01775         a NaN then a Python exception is raised.  If self is finite
01776         and lies exactly halfway between two integers then it is
01777         rounded to the integer with even last digit.
01778 
01779         >>> round(Decimal('123.456'))
01780         123
01781         >>> round(Decimal('-456.789'))
01782         -457
01783         >>> round(Decimal('-3.0'))
01784         -3
01785         >>> round(Decimal('2.5'))
01786         2
01787         >>> round(Decimal('3.5'))
01788         4
01789         >>> round(Decimal('Inf'))
01790         Traceback (most recent call last):
01791           ...
01792         OverflowError: cannot round an infinity
01793         >>> round(Decimal('NaN'))
01794         Traceback (most recent call last):
01795           ...
01796         ValueError: cannot round a NaN
01797 
01798         If a second argument n is supplied, self is rounded to n
01799         decimal places using the rounding mode for the current
01800         context.
01801 
01802         For an integer n, round(self, -n) is exactly equivalent to
01803         self.quantize(Decimal('1En')).
01804 
01805         >>> round(Decimal('123.456'), 0)
01806         Decimal('123')
01807         >>> round(Decimal('123.456'), 2)
01808         Decimal('123.46')
01809         >>> round(Decimal('123.456'), -2)
01810         Decimal('1E+2')
01811         >>> round(Decimal('-Infinity'), 37)
01812         Decimal('NaN')
01813         >>> round(Decimal('sNaN123'), 0)
01814         Decimal('NaN123')
01815 
01816         """
01817         if n is not None:
01818             # two-argument form: use the equivalent quantize call
01819             if not isinstance(n, int):
01820                 raise TypeError('Second argument to round should be integral')
01821             exp = _dec_from_triple(0, '1', -n)
01822             return self.quantize(exp)
01823 
01824         # one-argument form
01825         if self._is_special:
01826             if self.is_nan():
01827                 raise ValueError("cannot round a NaN")
01828             else:
01829                 raise OverflowError("cannot round an infinity")
01830         return int(self._rescale(0, ROUND_HALF_EVEN))
01831 
01832     def __floor__(self):
01833         """Return the floor of self, as an integer.
01834 
01835         For a finite Decimal instance self, return the greatest
01836         integer n such that n <= self.  If self is infinite or a NaN
01837         then a Python exception is raised.
01838 
01839         """
01840         if self._is_special:
01841             if self.is_nan():
01842                 raise ValueError("cannot round a NaN")
01843             else:
01844                 raise OverflowError("cannot round an infinity")
01845         return int(self._rescale(0, ROUND_FLOOR))
01846 
01847     def __ceil__(self):
01848         """Return the ceiling of self, as an integer.
01849 
01850         For a finite Decimal instance self, return the least integer n
01851         such that n >= self.  If self is infinite or a NaN then a
01852         Python exception is raised.
01853 
01854         """
01855         if self._is_special:
01856             if self.is_nan():
01857                 raise ValueError("cannot round a NaN")
01858             else:
01859                 raise OverflowError("cannot round an infinity")
01860         return int(self._rescale(0, ROUND_CEILING))
01861 
01862     def fma(self, other, third, context=None):
01863         """Fused multiply-add.
01864 
01865         Returns self*other+third with no rounding of the intermediate
01866         product self*other.
01867 
01868         self and other are multiplied together, with no rounding of
01869         the result.  The third operand is then added to the result,
01870         and a single final rounding is performed.
01871         """
01872 
01873         other = _convert_other(other, raiseit=True)
01874 
01875         # compute product; raise InvalidOperation if either operand is
01876         # a signaling NaN or if the product is zero times infinity.
01877         if self._is_special or other._is_special:
01878             if context is None:
01879                 context = getcontext()
01880             if self._exp == 'N':
01881                 return context._raise_error(InvalidOperation, 'sNaN', self)
01882             if other._exp == 'N':
01883                 return context._raise_error(InvalidOperation, 'sNaN', other)
01884             if self._exp == 'n':
01885                 product = self
01886             elif other._exp == 'n':
01887                 product = other
01888             elif self._exp == 'F':
01889                 if not other:
01890                     return context._raise_error(InvalidOperation,
01891                                                 'INF * 0 in fma')
01892                 product = _SignedInfinity[self._sign ^ other._sign]
01893             elif other._exp == 'F':
01894                 if not self:
01895                     return context._raise_error(InvalidOperation,
01896                                                 '0 * INF in fma')
01897                 product = _SignedInfinity[self._sign ^ other._sign]
01898         else:
01899             product = _dec_from_triple(self._sign ^ other._sign,
01900                                        str(int(self._int) * int(other._int)),
01901                                        self._exp + other._exp)
01902 
01903         third = _convert_other(third, raiseit=True)
01904         return product.__add__(third, context)
01905 
01906     def _power_modulo(self, other, modulo, context=None):
01907         """Three argument version of __pow__"""
01908 
01909         # if can't convert other and modulo to Decimal, raise
01910         # TypeError; there's no point returning NotImplemented (no
01911         # equivalent of __rpow__ for three argument pow)
01912         other = _convert_other(other, raiseit=True)
01913         modulo = _convert_other(modulo, raiseit=True)
01914 
01915         if context is None:
01916             context = getcontext()
01917 
01918         # deal with NaNs: if there are any sNaNs then first one wins,
01919         # (i.e. behaviour for NaNs is identical to that of fma)
01920         self_is_nan = self._isnan()
01921         other_is_nan = other._isnan()
01922         modulo_is_nan = modulo._isnan()
01923         if self_is_nan or other_is_nan or modulo_is_nan:
01924             if self_is_nan == 2:
01925                 return context._raise_error(InvalidOperation, 'sNaN',
01926                                         self)
01927             if other_is_nan == 2:
01928                 return context._raise_error(InvalidOperation, 'sNaN',
01929                                         other)
01930             if modulo_is_nan == 2:
01931                 return context._raise_error(InvalidOperation, 'sNaN',
01932                                         modulo)
01933             if self_is_nan:
01934                 return self._fix_nan(context)
01935             if other_is_nan:
01936                 return other._fix_nan(context)
01937             return modulo._fix_nan(context)
01938 
01939         # check inputs: we apply same restrictions as Python's pow()
01940         if not (self._isinteger() and
01941                 other._isinteger() and
01942                 modulo._isinteger()):
01943             return context._raise_error(InvalidOperation,
01944                                         'pow() 3rd argument not allowed '
01945                                         'unless all arguments are integers')
01946         if other < 0:
01947             return context._raise_error(InvalidOperation,
01948                                         'pow() 2nd argument cannot be '
01949                                         'negative when 3rd argument specified')
01950         if not modulo:
01951             return context._raise_error(InvalidOperation,
01952                                         'pow() 3rd argument cannot be 0')
01953 
01954         # additional restriction for decimal: the modulus must be less
01955         # than 10**prec in absolute value
01956         if modulo.adjusted() >= context.prec:
01957             return context._raise_error(InvalidOperation,
01958                                         'insufficient precision: pow() 3rd '
01959                                         'argument must not have more than '
01960                                         'precision digits')
01961 
01962         # define 0**0 == NaN, for consistency with two-argument pow
01963         # (even though it hurts!)
01964         if not other and not self:
01965             return context._raise_error(InvalidOperation,
01966                                         'at least one of pow() 1st argument '
01967                                         'and 2nd argument must be nonzero ;'
01968                                         '0**0 is not defined')
01969 
01970         # compute sign of result
01971         if other._iseven():
01972             sign = 0
01973         else:
01974             sign = self._sign
01975 
01976         # convert modulo to a Python integer, and self and other to
01977         # Decimal integers (i.e. force their exponents to be >= 0)
01978         modulo = abs(int(modulo))
01979         base = _WorkRep(self.to_integral_value())
01980         exponent = _WorkRep(other.to_integral_value())
01981 
01982         # compute result using integer pow()
01983         base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
01984         for i in range(exponent.exp):
01985             base = pow(base, 10, modulo)
01986         base = pow(base, exponent.int, modulo)
01987 
01988         return _dec_from_triple(sign, str(base), 0)
01989 
01990     def _power_exact(self, other, p):
01991         """Attempt to compute self**other exactly.
01992 
01993         Given Decimals self and other and an integer p, attempt to
01994         compute an exact result for the power self**other, with p
01995         digits of precision.  Return None if self**other is not
01996         exactly representable in p digits.
01997 
01998         Assumes that elimination of special cases has already been
01999         performed: self and other must both be nonspecial; self must
02000         be positive and not numerically equal to 1; other must be
02001         nonzero.  For efficiency, other._exp should not be too large,
02002         so that 10**abs(other._exp) is a feasible calculation."""
02003 
02004         # In the comments below, we write x for the value of self and
02005         # y for the value of other.  Write x = xc*10**xe and y =
02006         # yc*10**ye.
02007 
02008         # The main purpose of this method is to identify the *failure*
02009         # of x**y to be exactly representable with as little effort as
02010         # possible.  So we look for cheap and easy tests that
02011         # eliminate the possibility of x**y being exact.  Only if all
02012         # these tests are passed do we go on to actually compute x**y.
02013 
02014         # Here's the main idea.  First normalize both x and y.  We
02015         # express y as a rational m/n, with m and n relatively prime
02016         # and n>0.  Then for x**y to be exactly representable (at
02017         # *any* precision), xc must be the nth power of a positive
02018         # integer and xe must be divisible by n.  If m is negative
02019         # then additionally xc must be a power of either 2 or 5, hence
02020         # a power of 2**n or 5**n.
02021         #
02022         # There's a limit to how small |y| can be: if y=m/n as above
02023         # then:
02024         #
02025         #  (1) if xc != 1 then for the result to be representable we
02026         #      need xc**(1/n) >= 2, and hence also xc**|y| >= 2.  So
02027         #      if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
02028         #      2**(1/|y|), hence xc**|y| < 2 and the result is not
02029         #      representable.
02030         #
02031         #  (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1.  Hence if
02032         #      |y| < 1/|xe| then the result is not representable.
02033         #
02034         # Note that since x is not equal to 1, at least one of (1) and
02035         # (2) must apply.  Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
02036         # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
02037         #
02038         # There's also a limit to how large y can be, at least if it's
02039         # positive: the normalized result will have coefficient xc**y,
02040         # so if it's representable then xc**y < 10**p, and y <
02041         # p/log10(xc).  Hence if y*log10(xc) >= p then the result is
02042         # not exactly representable.
02043 
02044         # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
02045         # so |y| < 1/xe and the result is not representable.
02046         # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
02047         # < 1/nbits(xc).
02048 
02049         x = _WorkRep(self)
02050         xc, xe = x.int, x.exp
02051         while xc % 10 == 0:
02052             xc //= 10
02053             xe += 1
02054 
02055         y = _WorkRep(other)
02056         yc, ye = y.int, y.exp
02057         while yc % 10 == 0:
02058             yc //= 10
02059             ye += 1
02060 
02061         # case where xc == 1: result is 10**(xe*y), with xe*y
02062         # required to be an integer
02063         if xc == 1:
02064             xe *= yc
02065             # result is now 10**(xe * 10**ye);  xe * 10**ye must be integral
02066             while xe % 10 == 0:
02067                 xe //= 10
02068                 ye += 1
02069             if ye < 0:
02070                 return None
02071             exponent = xe * 10**ye
02072             if y.sign == 1:
02073                 exponent = -exponent
02074             # if other is a nonnegative integer, use ideal exponent
02075             if other._isinteger() and other._sign == 0:
02076                 ideal_exponent = self._exp*int(other)
02077                 zeros = min(exponent-ideal_exponent, p-1)
02078             else:
02079                 zeros = 0
02080             return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
02081 
02082         # case where y is negative: xc must be either a power
02083         # of 2 or a power of 5.
02084         if y.sign == 1:
02085             last_digit = xc % 10
02086             if last_digit in (2,4,6,8):
02087                 # quick test for power of 2
02088                 if xc & -xc != xc:
02089                     return None
02090                 # now xc is a power of 2; e is its exponent
02091                 e = _nbits(xc)-1
02092                 # find e*y and xe*y; both must be integers
02093                 if ye >= 0:
02094                     y_as_int = yc*10**ye
02095                     e = e*y_as_int
02096                     xe = xe*y_as_int
02097                 else:
02098                     ten_pow = 10**-ye
02099                     e, remainder = divmod(e*yc, ten_pow)
02100                     if remainder:
02101                         return None
02102                     xe, remainder = divmod(xe*yc, ten_pow)
02103                     if remainder:
02104                         return None
02105 
02106                 if e*65 >= p*93: # 93/65 > log(10)/log(5)
02107                     return None
02108                 xc = 5**e
02109 
02110             elif last_digit == 5:
02111                 # e >= log_5(xc) if xc is a power of 5; we have
02112                 # equality all the way up to xc=5**2658
02113                 e = _nbits(xc)*28//65
02114                 xc, remainder = divmod(5**e, xc)
02115                 if remainder:
02116                     return None
02117                 while xc % 5 == 0:
02118                     xc //= 5
02119                     e -= 1
02120                 if ye >= 0:
02121                     y_as_integer = yc*10**ye
02122                     e = e*y_as_integer
02123                     xe = xe*y_as_integer
02124                 else:
02125                     ten_pow = 10**-ye
02126                     e, remainder = divmod(e*yc, ten_pow)
02127                     if remainder:
02128                         return None
02129                     xe, remainder = divmod(xe*yc, ten_pow)
02130                     if remainder:
02131                         return None
02132                 if e*3 >= p*10: # 10/3 > log(10)/log(2)
02133                     return None
02134                 xc = 2**e
02135             else:
02136                 return None
02137 
02138             if xc >= 10**p:
02139                 return None
02140             xe = -e-xe
02141             return _dec_from_triple(0, str(xc), xe)
02142 
02143         # now y is positive; find m and n such that y = m/n
02144         if ye >= 0:
02145             m, n = yc*10**ye, 1
02146         else:
02147             if xe != 0 and len(str(abs(yc*xe))) <= -ye:
02148                 return None
02149             xc_bits = _nbits(xc)
02150             if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
02151                 return None
02152             m, n = yc, 10**(-ye)
02153             while m % 2 == n % 2 == 0:
02154                 m //= 2
02155                 n //= 2
02156             while m % 5 == n % 5 == 0:
02157                 m //= 5
02158                 n //= 5
02159 
02160         # compute nth root of xc*10**xe
02161         if n > 1:
02162             # if 1 < xc < 2**n then xc isn't an nth power
02163             if xc != 1 and xc_bits <= n:
02164                 return None
02165 
02166             xe, rem = divmod(xe, n)
02167             if rem != 0:
02168                 return None
02169 
02170             # compute nth root of xc using Newton's method
02171             a = 1 << -(-_nbits(xc)//n) # initial estimate
02172             while True:
02173                 q, r = divmod(xc, a**(n-1))
02174                 if a <= q:
02175                     break
02176                 else:
02177                     a = (a*(n-1) + q)//n
02178             if not (a == q and r == 0):
02179                 return None
02180             xc = a
02181 
02182         # now xc*10**xe is the nth root of the original xc*10**xe
02183         # compute mth power of xc*10**xe
02184 
02185         # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
02186         # 10**p and the result is not representable.
02187         if xc > 1 and m > p*100//_log10_lb(xc):
02188             return None
02189         xc = xc**m
02190         xe *= m
02191         if xc > 10**p:
02192             return None
02193 
02194         # by this point the result *is* exactly representable
02195         # adjust the exponent to get as close as possible to the ideal
02196         # exponent, if necessary
02197         str_xc = str(xc)
02198         if other._isinteger() and other._sign == 0:
02199             ideal_exponent = self._exp*int(other)
02200             zeros = min(xe-ideal_exponent, p-len(str_xc))
02201         else:
02202             zeros = 0
02203         return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
02204 
02205     def __pow__(self, other, modulo=None, context=None):
02206         """Return self ** other [ % modulo].
02207 
02208         With two arguments, compute self**other.
02209 
02210         With three arguments, compute (self**other) % modulo.  For the
02211         three argument form, the following restrictions on the
02212         arguments hold:
02213 
02214          - all three arguments must be integral
02215          - other must be nonnegative
02216          - either self or other (or both) must be nonzero
02217          - modulo must be nonzero and must have at most p digits,
02218            where p is the context precision.
02219 
02220         If any of these restrictions is violated the InvalidOperation
02221         flag is raised.
02222 
02223         The result of pow(self, other, modulo) is identical to the
02224         result that would be obtained by computing (self**other) %
02225         modulo with unbounded precision, but is computed more
02226         efficiently.  It is always exact.
02227         """
02228 
02229         if modulo is not None:
02230             return self._power_modulo(other, modulo, context)
02231 
02232         other = _convert_other(other)
02233         if other is NotImplemented:
02234             return other
02235 
02236         if context is None:
02237             context = getcontext()
02238 
02239         # either argument is a NaN => result is NaN
02240         ans = self._check_nans(other, context)
02241         if ans:
02242             return ans
02243 
02244         # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
02245         if not other:
02246             if not self:
02247                 return context._raise_error(InvalidOperation, '0 ** 0')
02248             else:
02249                 return _One
02250 
02251         # result has sign 1 iff self._sign is 1 and other is an odd integer
02252         result_sign = 0
02253         if self._sign == 1:
02254             if other._isinteger():
02255                 if not other._iseven():
02256                     result_sign = 1
02257             else:
02258                 # -ve**noninteger = NaN
02259                 # (-0)**noninteger = 0**noninteger
02260                 if self:
02261                     return context._raise_error(InvalidOperation,
02262                         'x ** y with x negative and y not an integer')
02263             # negate self, without doing any unwanted rounding
02264             self = self.copy_negate()
02265 
02266         # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
02267         if not self:
02268             if other._sign == 0:
02269                 return _dec_from_triple(result_sign, '0', 0)
02270             else:
02271                 return _SignedInfinity[result_sign]
02272 
02273         # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
02274         if self._isinfinity():
02275             if other._sign == 0:
02276                 return _SignedInfinity[result_sign]
02277             else:
02278                 return _dec_from_triple(result_sign, '0', 0)
02279 
02280         # 1**other = 1, but the choice of exponent and the flags
02281         # depend on the exponent of self, and on whether other is a
02282         # positive integer, a negative integer, or neither
02283         if self == _One:
02284             if other._isinteger():
02285                 # exp = max(self._exp*max(int(other), 0),
02286                 # 1-context.prec) but evaluating int(other) directly
02287                 # is dangerous until we know other is small (other
02288                 # could be 1e999999999)
02289                 if other._sign == 1:
02290                     multiplier = 0
02291                 elif other > context.prec:
02292                     multiplier = context.prec
02293                 else:
02294                     multiplier = int(other)
02295 
02296                 exp = self._exp * multiplier
02297                 if exp < 1-context.prec:
02298                     exp = 1-context.prec
02299                     context._raise_error(Rounded)
02300             else:
02301                 context._raise_error(Inexact)
02302                 context._raise_error(Rounded)
02303                 exp = 1-context.prec
02304 
02305             return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
02306 
02307         # compute adjusted exponent of self
02308         self_adj = self.adjusted()
02309 
02310         # self ** infinity is infinity if self > 1, 0 if self < 1
02311         # self ** -infinity is infinity if self < 1, 0 if self > 1
02312         if other._isinfinity():
02313             if (other._sign == 0) == (self_adj < 0):
02314                 return _dec_from_triple(result_sign, '0', 0)
02315             else:
02316                 return _SignedInfinity[result_sign]
02317 
02318         # from here on, the result always goes through the call
02319         # to _fix at the end of this function.
02320         ans = None
02321         exact = False
02322 
02323         # crude test to catch cases of extreme overflow/underflow.  If
02324         # log10(self)*other >= 10**bound and bound >= len(str(Emax))
02325         # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
02326         # self**other >= 10**(Emax+1), so overflow occurs.  The test
02327         # for underflow is similar.
02328         bound = self._log10_exp_bound() + other.adjusted()
02329         if (self_adj >= 0) == (other._sign == 0):
02330             # self > 1 and other +ve, or self < 1 and other -ve
02331             # possibility of overflow
02332             if bound >= len(str(context.Emax)):
02333                 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
02334         else:
02335             # self > 1 and other -ve, or self < 1 and other +ve
02336             # possibility of underflow to 0
02337             Etiny = context.Etiny()
02338             if bound >= len(str(-Etiny)):
02339                 ans = _dec_from_triple(result_sign, '1', Etiny-1)
02340 
02341         # try for an exact result with precision +1
02342         if ans is None:
02343             ans = self._power_exact(other, context.prec + 1)
02344             if ans is not None:
02345                 if result_sign == 1:
02346                     ans = _dec_from_triple(1, ans._int, ans._exp)
02347                 exact = True
02348 
02349         # usual case: inexact result, x**y computed directly as exp(y*log(x))
02350         if ans is None:
02351             p = context.prec
02352             x = _WorkRep(self)
02353             xc, xe = x.int, x.exp
02354             y = _WorkRep(other)
02355             yc, ye = y.int, y.exp
02356             if y.sign == 1:
02357                 yc = -yc
02358 
02359             # compute correctly rounded result:  start with precision +3,
02360             # then increase precision until result is unambiguously roundable
02361             extra = 3
02362             while True:
02363                 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
02364                 if coeff % (5*10**(len(str(coeff))-p-1)):
02365                     break
02366                 extra += 3
02367 
02368             ans = _dec_from_triple(result_sign, str(coeff), exp)
02369 
02370         # unlike exp, ln and log10, the power function respects the
02371         # rounding mode; no need to switch to ROUND_HALF_EVEN here
02372 
02373         # There's a difficulty here when 'other' is not an integer and
02374         # the result is exact.  In this case, the specification
02375         # requires that the Inexact flag be raised (in spite of
02376         # exactness), but since the result is exact _fix won't do this
02377         # for us.  (Correspondingly, the Underflow signal should also
02378         # be raised for subnormal results.)  We can't directly raise
02379         # these signals either before or after calling _fix, since
02380         # that would violate the precedence for signals.  So we wrap
02381         # the ._fix call in a temporary context, and reraise
02382         # afterwards.
02383         if exact and not other._isinteger():
02384             # pad with zeros up to length context.prec+1 if necessary; this
02385             # ensures that the Rounded signal will be raised.
02386             if len(ans._int) <= context.prec:
02387                 expdiff = context.prec + 1 - len(ans._int)
02388                 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
02389                                        ans._exp-expdiff)
02390 
02391             # create a copy of the current context, with cleared flags/traps
02392             newcontext = context.copy()
02393             newcontext.clear_flags()
02394             for exception in _signals:
02395                 newcontext.traps[exception] = 0
02396 
02397             # round in the new context
02398             ans = ans._fix(newcontext)
02399 
02400             # raise Inexact, and if necessary, Underflow
02401             newcontext._raise_error(Inexact)
02402             if newcontext.flags[Subnormal]:
02403                 newcontext._raise_error(Underflow)
02404 
02405             # propagate signals to the original context; _fix could
02406             # have raised any of Overflow, Underflow, Subnormal,
02407             # Inexact, Rounded, Clamped.  Overflow needs the correct
02408             # arguments.  Note that the order of the exceptions is
02409             # important here.
02410             if newcontext.flags[Overflow]:
02411                 context._raise_error(Overflow, 'above Emax', ans._sign)
02412             for exception in Underflow, Subnormal, Inexact, Rounded, Clamped:
02413                 if newcontext.flags[exception]:
02414                     context._raise_error(exception)
02415 
02416         else:
02417             ans = ans._fix(context)
02418 
02419         return ans
02420 
02421     def __rpow__(self, other, context=None):
02422         """Swaps self/other and returns __pow__."""
02423         other = _convert_other(other)
02424         if other is NotImplemented:
02425             return other
02426         return other.__pow__(self, context=context)
02427 
02428     def normalize(self, context=None):
02429         """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
02430 
02431         if context is None:
02432             context = getcontext()
02433 
02434         if self._is_special:
02435             ans = self._check_nans(context=context)
02436             if ans:
02437                 return ans
02438 
02439         dup = self._fix(context)
02440         if dup._isinfinity():
02441             return dup
02442 
02443         if not dup:
02444             return _dec_from_triple(dup._sign, '0', 0)
02445         exp_max = [context.Emax, context.Etop()][context.clamp]
02446         end = len(dup._int)
02447         exp = dup._exp
02448         while dup._int[end-1] == '0' and exp < exp_max:
02449             exp += 1
02450             end -= 1
02451         return _dec_from_triple(dup._sign, dup._int[:end], exp)
02452 
02453     def quantize(self, exp, rounding=None, context=None, watchexp=True):
02454         """Quantize self so its exponent is the same as that of exp.
02455 
02456         Similar to self._rescale(exp._exp) but with error checking.
02457         """
02458         exp = _convert_other(exp, raiseit=True)
02459 
02460         if context is None:
02461             context = getcontext()
02462         if rounding is None:
02463             rounding = context.rounding
02464 
02465         if self._is_special or exp._is_special:
02466             ans = self._check_nans(exp, context)
02467             if ans:
02468                 return ans
02469 
02470             if exp._isinfinity() or self._isinfinity():
02471                 if exp._isinfinity() and self._isinfinity():
02472                     return Decimal(self)  # if both are inf, it is OK
02473                 return context._raise_error(InvalidOperation,
02474                                         'quantize with one INF')
02475 
02476         # if we're not watching exponents, do a simple rescale
02477         if not watchexp:
02478             ans = self._rescale(exp._exp, rounding)
02479             # raise Inexact and Rounded where appropriate
02480             if ans._exp > self._exp:
02481                 context._raise_error(Rounded)
02482                 if ans != self:
02483                     context._raise_error(Inexact)
02484             return ans
02485 
02486         # exp._exp should be between Etiny and Emax
02487         if not (context.Etiny() <= exp._exp <= context.Emax):
02488             return context._raise_error(InvalidOperation,
02489                    'target exponent out of bounds in quantize')
02490 
02491         if not self:
02492             ans = _dec_from_triple(self._sign, '0', exp._exp)
02493             return ans._fix(context)
02494 
02495         self_adjusted = self.adjusted()
02496         if self_adjusted > context.Emax:
02497             return context._raise_error(InvalidOperation,
02498                                         'exponent of quantize result too large for current context')
02499         if self_adjusted - exp._exp + 1 > context.prec:
02500             return context._raise_error(InvalidOperation,
02501                                         'quantize result has too many digits for current context')
02502 
02503         ans = self._rescale(exp._exp, rounding)
02504         if ans.adjusted() > context.Emax:
02505             return context._raise_error(InvalidOperation,
02506                                         'exponent of quantize result too large for current context')
02507         if len(ans._int) > context.prec:
02508             return context._raise_error(InvalidOperation,
02509                                         'quantize result has too many digits for current context')
02510 
02511         # raise appropriate flags
02512         if ans and ans.adjusted() < context.Emin:
02513             context._raise_error(Subnormal)
02514         if ans._exp > self._exp:
02515             if ans != self:
02516                 context._raise_error(Inexact)
02517             context._raise_error(Rounded)
02518 
02519         # call to fix takes care of any necessary folddown, and
02520         # signals Clamped if necessary
02521         ans = ans._fix(context)
02522         return ans
02523 
02524     def same_quantum(self, other):
02525         """Return True if self and other have the same exponent; otherwise
02526         return False.
02527 
02528         If either operand is a special value, the following rules are used:
02529            * return True if both operands are infinities
02530            * return True if both operands are NaNs
02531            * otherwise, return False.
02532         """
02533         other = _convert_other(other, raiseit=True)
02534         if self._is_special or other._is_special:
02535             return (self.is_nan() and other.is_nan() or
02536                     self.is_infinite() and other.is_infinite())
02537         return self._exp == other._exp
02538 
02539     def _rescale(self, exp, rounding):
02540         """Rescale self so that the exponent is exp, either by padding with zeros
02541         or by truncating digits, using the given rounding mode.
02542 
02543         Specials are returned without change.  This operation is
02544         quiet: it raises no flags, and uses no information from the
02545         context.
02546 
02547         exp = exp to scale to (an integer)
02548         rounding = rounding mode
02549         """
02550         if self._is_special:
02551             return Decimal(self)
02552         if not self:
02553             return _dec_from_triple(self._sign, '0', exp)
02554 
02555         if self._exp >= exp:
02556             # pad answer with zeros if necessary
02557             return _dec_from_triple(self._sign,
02558                                         self._int + '0'*(self._exp - exp), exp)
02559 
02560         # too many digits; round and lose data.  If self.adjusted() <
02561         # exp-1, replace self by 10**(exp-1) before rounding
02562         digits = len(self._int) + self._exp - exp
02563         if digits < 0:
02564             self = _dec_from_triple(self._sign, '1', exp-1)
02565             digits = 0
02566         this_function = self._pick_rounding_function[rounding]
02567         changed = this_function(self, digits)
02568         coeff = self._int[:digits] or '0'
02569         if changed == 1:
02570             coeff = str(int(coeff)+1)
02571         return _dec_from_triple(self._sign, coeff, exp)
02572 
02573     def _round(self, places, rounding):
02574         """Round a nonzero, nonspecial Decimal to a fixed number of
02575         significant figures, using the given rounding mode.
02576 
02577         Infinities, NaNs and zeros are returned unaltered.
02578 
02579         This operation is quiet: it raises no flags, and uses no
02580         information from the context.
02581 
02582         """
02583         if places <= 0:
02584             raise ValueError("argument should be at least 1 in _round")
02585         if self._is_special or not self:
02586             return Decimal(self)
02587         ans = self._rescale(self.adjusted()+1-places, rounding)
02588         # it can happen that the rescale alters the adjusted exponent;
02589         # for example when rounding 99.97 to 3 significant figures.
02590         # When this happens we end up with an extra 0 at the end of
02591         # the number; a second rescale fixes this.
02592         if ans.adjusted() != self.adjusted():
02593             ans = ans._rescale(ans.adjusted()+1-places, rounding)
02594         return ans
02595 
02596     def to_integral_exact(self, rounding=None, context=None):
02597         """Rounds to a nearby integer.
02598 
02599         If no rounding mode is specified, take the rounding mode from
02600         the context.  This method raises the Rounded and Inexact flags
02601         when appropriate.
02602 
02603         See also: to_integral_value, which does exactly the same as
02604         this method except that it doesn't raise Inexact or Rounded.
02605         """
02606         if self._is_special:
02607             ans = self._check_nans(context=context)
02608             if ans:
02609                 return ans
02610             return Decimal(self)
02611         if self._exp >= 0:
02612             return Decimal(self)
02613         if not self:
02614             return _dec_from_triple(self._sign, '0', 0)
02615         if context is None:
02616             context = getcontext()
02617         if rounding is None:
02618             rounding = context.rounding
02619         ans = self._rescale(0, rounding)
02620         if ans != self:
02621             context._raise_error(Inexact)
02622         context._raise_error(Rounded)
02623         return ans
02624 
02625     def to_integral_value(self, rounding=None, context=None):
02626         """Rounds to the nearest integer, without raising inexact, rounded."""
02627         if context is None:
02628             context = getcontext()
02629         if rounding is None:
02630             rounding = context.rounding
02631         if self._is_special:
02632             ans = self._check_nans(context=context)
02633             if ans:
02634                 return ans
02635             return Decimal(self)
02636         if self._exp >= 0:
02637             return Decimal(self)
02638         else:
02639             return self._rescale(0, rounding)
02640 
02641     # the method name changed, but we provide also the old one, for compatibility
02642     to_integral = to_integral_value
02643 
02644     def sqrt(self, context=None):
02645         """Return the square root of self."""
02646         if context is None:
02647             context = getcontext()
02648 
02649         if self._is_special:
02650             ans = self._check_nans(context=context)
02651             if ans:
02652                 return ans
02653 
02654             if self._isinfinity() and self._sign == 0:
02655                 return Decimal(self)
02656 
02657         if not self:
02658             # exponent = self._exp // 2.  sqrt(-0) = -0
02659             ans = _dec_from_triple(self._sign, '0', self._exp // 2)
02660             return ans._fix(context)
02661 
02662         if self._sign == 1:
02663             return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
02664 
02665         # At this point self represents a positive number.  Let p be
02666         # the desired precision and express self in the form c*100**e
02667         # with c a positive real number and e an integer, c and e
02668         # being chosen so that 100**(p-1) <= c < 100**p.  Then the
02669         # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
02670         # <= sqrt(c) < 10**p, so the closest representable Decimal at
02671         # precision p is n*10**e where n = round_half_even(sqrt(c)),
02672         # the closest integer to sqrt(c) with the even integer chosen
02673         # in the case of a tie.
02674         #
02675         # To ensure correct rounding in all cases, we use the
02676         # following trick: we compute the square root to an extra
02677         # place (precision p+1 instead of precision p), rounding down.
02678         # Then, if the result is inexact and its last digit is 0 or 5,
02679         # we increase the last digit to 1 or 6 respectively; if it's
02680         # exact we leave the last digit alone.  Now the final round to
02681         # p places (or fewer in the case of underflow) will round
02682         # correctly and raise the appropriate flags.
02683 
02684         # use an extra digit of precision
02685         prec = context.prec+1
02686 
02687         # write argument in the form c*100**e where e = self._exp//2
02688         # is the 'ideal' exponent, to be used if the square root is
02689         # exactly representable.  l is the number of 'digits' of c in
02690         # base 100, so that 100**(l-1) <= c < 100**l.
02691         op = _WorkRep(self)
02692         e = op.exp >> 1
02693         if op.exp & 1:
02694             c = op.int * 10
02695             l = (len(self._int) >> 1) + 1
02696         else:
02697             c = op.int
02698             l = len(self._int)+1 >> 1
02699 
02700         # rescale so that c has exactly prec base 100 'digits'
02701         shift = prec-l
02702         if shift >= 0:
02703             c *= 100**shift
02704             exact = True
02705         else:
02706             c, remainder = divmod(c, 100**-shift)
02707             exact = not remainder
02708         e -= shift
02709 
02710         # find n = floor(sqrt(c)) using Newton's method
02711         n = 10**prec
02712         while True:
02713             q = c//n
02714             if n <= q:
02715                 break
02716             else:
02717                 n = n + q >> 1
02718         exact = exact and n*n == c
02719 
02720         if exact:
02721             # result is exact; rescale to use ideal exponent e
02722             if shift >= 0:
02723                 # assert n % 10**shift == 0
02724                 n //= 10**shift
02725             else:
02726                 n *= 10**-shift
02727             e += shift
02728         else:
02729             # result is not exact; fix last digit as described above
02730             if n % 5 == 0:
02731                 n += 1
02732 
02733         ans = _dec_from_triple(0, str(n), e)
02734 
02735         # round, and fit to current context
02736         context = context._shallow_copy()
02737         rounding = context._set_rounding(ROUND_HALF_EVEN)
02738         ans = ans._fix(context)
02739         context.rounding = rounding
02740 
02741         return ans
02742 
02743     def max(self, other, context=None):
02744         """Returns the larger value.
02745 
02746         Like max(self, other) except if one is not a number, returns
02747         NaN (and signals if one is sNaN).  Also rounds.
02748         """
02749         other = _convert_other(other, raiseit=True)
02750 
02751         if context is None:
02752             context = getcontext()
02753 
02754         if self._is_special or other._is_special:
02755             # If one operand is a quiet NaN and the other is number, then the
02756             # number is always returned
02757             sn = self._isnan()
02758             on = other._isnan()
02759             if sn or on:
02760                 if on == 1 and sn == 0:
02761                     return self._fix(context)
02762                 if sn == 1 and on == 0:
02763                     return other._fix(context)
02764                 return self._check_nans(other, context)
02765 
02766         c = self._cmp(other)
02767         if c == 0:
02768             # If both operands are finite and equal in numerical value
02769             # then an ordering is applied:
02770             #
02771             # If the signs differ then max returns the operand with the
02772             # positive sign and min returns the operand with the negative sign
02773             #
02774             # If the signs are the same then the exponent is used to select
02775             # the result.  This is exactly the ordering used in compare_total.
02776             c = self.compare_total(other)
02777 
02778         if c == -1:
02779             ans = other
02780         else:
02781             ans = self
02782 
02783         return ans._fix(context)
02784 
02785     def min(self, other, context=None):
02786         """Returns the smaller value.
02787 
02788         Like min(self, other) except if one is not a number, returns
02789         NaN (and signals if one is sNaN).  Also rounds.
02790         """
02791         other = _convert_other(other, raiseit=True)
02792 
02793         if context is None:
02794             context = getcontext()
02795 
02796         if self._is_special or other._is_special:
02797             # If one operand is a quiet NaN and the other is number, then the
02798             # number is always returned
02799             sn = self._isnan()
02800             on = other._isnan()
02801             if sn or on:
02802                 if on == 1 and sn == 0:
02803                     return self._fix(context)
02804                 if sn == 1 and on == 0:
02805                     return other._fix(context)
02806                 return self._check_nans(other, context)
02807 
02808         c = self._cmp(other)
02809         if c == 0:
02810             c = self.compare_total(other)
02811 
02812         if c == -1:
02813             ans = self
02814         else:
02815             ans = other
02816 
02817         return ans._fix(context)
02818 
02819     def _isinteger(self):
02820         """Returns whether self is an integer"""
02821         if self._is_special:
02822             return False
02823         if self._exp >= 0:
02824             return True
02825         rest = self._int[self._exp:]
02826         return rest == '0'*len(rest)
02827 
02828     def _iseven(self):
02829         """Returns True if self is even.  Assumes self is an integer."""
02830         if not self or self._exp > 0:
02831             return True
02832         return self._int[-1+self._exp] in '02468'
02833 
02834     def adjusted(self):
02835         """Return the adjusted exponent of self"""
02836         try:
02837             return self._exp + len(self._int) - 1
02838         # If NaN or Infinity, self._exp is string
02839         except TypeError:
02840             return 0
02841 
02842     def canonical(self, context=None):
02843         """Returns the same Decimal object.
02844 
02845         As we do not have different encodings for the same number, the
02846         received object already is in its canonical form.
02847         """
02848         return self
02849 
02850     def compare_signal(self, other, context=None):
02851         """Compares self to the other operand numerically.
02852 
02853         It's pretty much like compare(), but all NaNs signal, with signaling
02854         NaNs taking precedence over quiet NaNs.
02855         """
02856         other = _convert_other(other, raiseit = True)
02857         ans = self._compare_check_nans(other, context)
02858         if ans:
02859             return ans
02860         return self.compare(other, context=context)
02861 
02862     def compare_total(self, other):
02863         """Compares self to other using the abstract representations.
02864 
02865         This is not like the standard compare, which use their numerical
02866         value. Note that a total ordering is defined for all possible abstract
02867         representations.
02868         """
02869         other = _convert_other(other, raiseit=True)
02870 
02871         # if one is negative and the other is positive, it's easy
02872         if self._sign and not other._sign:
02873             return _NegativeOne
02874         if not self._sign and other._sign:
02875             return _One
02876         sign = self._sign
02877 
02878         # let's handle both NaN types
02879         self_nan = self._isnan()
02880         other_nan = other._isnan()
02881         if self_nan or other_nan:
02882             if self_nan == other_nan:
02883                 # compare payloads as though they're integers
02884                 self_key = len(self._int), self._int
02885                 other_key = len(other._int), other._int
02886                 if self_key < other_key:
02887                     if sign:
02888                         return _One
02889                     else:
02890                         return _NegativeOne
02891                 if self_key > other_key:
02892                     if sign:
02893                         return _NegativeOne
02894                     else:
02895                         return _One
02896                 return _Zero
02897 
02898             if sign:
02899                 if self_nan == 1:
02900                     return _NegativeOne
02901                 if other_nan == 1:
02902                     return _One
02903                 if self_nan == 2:
02904                     return _NegativeOne
02905                 if other_nan == 2:
02906                     return _One
02907             else:
02908                 if self_nan == 1:
02909                     return _One
02910                 if other_nan == 1:
02911                     return _NegativeOne
02912                 if self_nan == 2:
02913                     return _One
02914                 if other_nan == 2:
02915                     return _NegativeOne
02916 
02917         if self < other:
02918             return _NegativeOne
02919         if self > other:
02920             return _One
02921 
02922         if self._exp < other._exp:
02923             if sign:
02924                 return _One
02925             else:
02926                 return _NegativeOne
02927         if self._exp > other._exp:
02928             if sign:
02929                 return _NegativeOne
02930             else:
02931                 return _One
02932         return _Zero
02933 
02934 
02935     def compare_total_mag(self, other):
02936         """Compares self to other using abstract repr., ignoring sign.
02937 
02938         Like compare_total, but with operand's sign ignored and assumed to be 0.
02939         """
02940         other = _convert_other(other, raiseit=True)
02941 
02942         s = self.copy_abs()
02943         o = other.copy_abs()
02944         return s.compare_total(o)
02945 
02946     def copy_abs(self):
02947         """Returns a copy with the sign set to 0. """
02948         return _dec_from_triple(0, self._int, self._exp, self._is_special)
02949 
02950     def copy_negate(self):
02951         """Returns a copy with the sign inverted."""
02952         if self._sign:
02953             return _dec_from_triple(0, self._int, self._exp, self._is_special)
02954         else:
02955             return _dec_from_triple(1, self._int, self._exp, self._is_special)
02956 
02957     def copy_sign(self, other):
02958         """Returns self with the sign of other."""
02959         other = _convert_other(other, raiseit=True)
02960         return _dec_from_triple(other._sign, self._int,
02961                                 self._exp, self._is_special)
02962 
02963     def exp(self, context=None):
02964         """Returns e ** self."""
02965 
02966         if context is None:
02967             context = getcontext()
02968 
02969         # exp(NaN) = NaN
02970         ans = self._check_nans(context=context)
02971         if ans:
02972             return ans
02973 
02974         # exp(-Infinity) = 0
02975         if self._isinfinity() == -1:
02976             return _Zero
02977 
02978         # exp(0) = 1
02979         if not self:
02980             return _One
02981 
02982         # exp(Infinity) = Infinity
02983         if self._isinfinity() == 1:
02984             return Decimal(self)
02985 
02986         # the result is now guaranteed to be inexact (the true
02987         # mathematical result is transcendental). There's no need to
02988         # raise Rounded and Inexact here---they'll always be raised as
02989         # a result of the call to _fix.
02990         p = context.prec
02991         adj = self.adjusted()
02992 
02993         # we only need to do any computation for quite a small range
02994         # of adjusted exponents---for example, -29 <= adj <= 10 for
02995         # the default context.  For smaller exponent the result is
02996         # indistinguishable from 1 at the given precision, while for
02997         # larger exponent the result either overflows or underflows.
02998         if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
02999             # overflow
03000             ans = _dec_from_triple(0, '1', context.Emax+1)
03001         elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
03002             # underflow to 0
03003             ans = _dec_from_triple(0, '1', context.Etiny()-1)
03004         elif self._sign == 0 and adj < -p:
03005             # p+1 digits; final round will raise correct flags
03006             ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
03007         elif self._sign == 1 and adj < -p-1:
03008             # p+1 digits; final round will raise correct flags
03009             ans = _dec_from_triple(0, '9'*(p+1), -p-1)
03010         # general case
03011         else:
03012             op = _WorkRep(self)
03013             c, e = op.int, op.exp
03014             if op.sign == 1:
03015                 c = -c
03016 
03017             # compute correctly rounded result: increase precision by
03018             # 3 digits at a time until we get an unambiguously
03019             # roundable result
03020             extra = 3
03021             while True:
03022                 coeff, exp = _dexp(c, e, p+extra)
03023                 if coeff % (5*10**(len(str(coeff))-p-1)):
03024                     break
03025                 extra += 3
03026 
03027             ans = _dec_from_triple(0, str(coeff), exp)
03028 
03029         # at this stage, ans should round correctly with *any*
03030         # rounding mode, not just with ROUND_HALF_EVEN
03031         context = context._shallow_copy()
03032         rounding = context._set_rounding(ROUND_HALF_EVEN)
03033         ans = ans._fix(context)
03034         context.rounding = rounding
03035 
03036         return ans
03037 
03038     def is_canonical(self):
03039         """Return True if self is canonical; otherwise return False.
03040 
03041         Currently, the encoding of a Decimal instance is always
03042         canonical, so this method returns True for any Decimal.
03043         """
03044         return True
03045 
03046     def is_finite(self):
03047         """Return True if self is finite; otherwise return False.
03048 
03049         A Decimal instance is considered finite if it is neither
03050         infinite nor a NaN.
03051         """
03052         return not self._is_special
03053 
03054     def is_infinite(self):
03055         """Return True if self is infinite; otherwise return False."""
03056         return self._exp == 'F'
03057 
03058     def is_nan(self):
03059         """Return True if self is a qNaN or sNaN; otherwise return False."""
03060         return self._exp in ('n', 'N')
03061 
03062     def is_normal(self, context=None):
03063         """Return True if self is a normal number; otherwise return False."""
03064         if self._is_special or not self:
03065             return False
03066         if context is None:
03067             context = getcontext()
03068         return context.Emin <= self.adjusted()
03069 
03070     def is_qnan(self):
03071         """Return True if self is a quiet NaN; otherwise return False."""
03072         return self._exp == 'n'
03073 
03074     def is_signed(self):
03075         """Return True if self is negative; otherwise return False."""
03076         return self._sign == 1
03077 
03078     def is_snan(self):
03079         """Return True if self is a signaling NaN; otherwise return False."""
03080         return self._exp == 'N'
03081 
03082     def is_subnormal(self, context=None):
03083         """Return True if self is subnormal; otherwise return False."""
03084         if self._is_special or not self:
03085             return False
03086         if context is None:
03087             context = getcontext()
03088         return self.adjusted() < context.Emin
03089 
03090     def is_zero(self):
03091         """Return True if self is a zero; otherwise return False."""
03092         return not self._is_special and self._int == '0'
03093 
03094     def _ln_exp_bound(self):
03095         """Compute a lower bound for the adjusted exponent of self.ln().
03096         In other words, compute r such that self.ln() >= 10**r.  Assumes
03097         that self is finite and positive and that self != 1.
03098         """
03099 
03100         # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
03101         adj = self._exp + len(self._int) - 1
03102         if adj >= 1:
03103             # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
03104             return len(str(adj*23//10)) - 1
03105         if adj <= -2:
03106             # argument <= 0.1
03107             return len(str((-1-adj)*23//10)) - 1
03108         op = _WorkRep(self)
03109         c, e = op.int, op.exp
03110         if adj == 0:
03111             # 1 < self < 10
03112             num = str(c-10**-e)
03113             den = str(c)
03114             return len(num) - len(den) - (num < den)
03115         # adj == -1, 0.1 <= self < 1
03116         return e + len(str(10**-e - c)) - 1
03117 
03118 
03119     def ln(self, context=None):
03120         """Returns the natural (base e) logarithm of self."""
03121 
03122         if context is None:
03123             context = getcontext()
03124 
03125         # ln(NaN) = NaN
03126         ans = self._check_nans(context=context)
03127         if ans:
03128             return ans
03129 
03130         # ln(0.0) == -Infinity
03131         if not self:
03132             return _NegativeInfinity
03133 
03134         # ln(Infinity) = Infinity
03135         if self._isinfinity() == 1:
03136             return _Infinity
03137 
03138         # ln(1.0) == 0.0
03139         if self == _One:
03140             return _Zero
03141 
03142         # ln(negative) raises InvalidOperation
03143         if self._sign == 1:
03144             return context._raise_error(InvalidOperation,
03145                                         'ln of a negative value')
03146 
03147         # result is irrational, so necessarily inexact
03148         op = _WorkRep(self)
03149         c, e = op.int, op.exp
03150         p = context.prec
03151 
03152         # correctly rounded result: repeatedly increase precision by 3
03153         # until we get an unambiguously roundable result
03154         places = p - self._ln_exp_bound() + 2 # at least p+3 places
03155         while True:
03156             coeff = _dlog(c, e, places)
03157             # assert len(str(abs(coeff)))-p >= 1
03158             if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
03159                 break
03160             places += 3
03161         ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
03162 
03163         context = context._shallow_copy()
03164         rounding = context._set_rounding(ROUND_HALF_EVEN)
03165         ans = ans._fix(context)
03166         context.rounding = rounding
03167         return ans
03168 
03169     def _log10_exp_bound(self):
03170         """Compute a lower bound for the adjusted exponent of self.log10().
03171         In other words, find r such that self.log10() >= 10**r.
03172         Assumes that self is finite and positive and that self != 1.
03173         """
03174 
03175         # For x >= 10 or x < 0.1 we only need a bound on the integer
03176         # part of log10(self), and this comes directly from the
03177         # exponent of x.  For 0.1 <= x <= 10 we use the inequalities
03178         # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
03179         # (1-1/x)/2.31 > 0.  If x < 1 then |log10(x)| > (1-x)/2.31 > 0
03180 
03181         adj = self._exp + len(self._int) - 1
03182         if adj >= 1:
03183             # self >= 10
03184             return len(str(adj))-1
03185         if adj <= -2:
03186             # self < 0.1
03187             return len(str(-1-adj))-1
03188         op = _WorkRep(self)
03189         c, e = op.int, op.exp
03190         if adj == 0:
03191             # 1 < self < 10
03192             num = str(c-10**-e)
03193             den = str(231*c)
03194             return len(num) - len(den) - (num < den) + 2
03195         # adj == -1, 0.1 <= self < 1
03196         num = str(10**-e-c)
03197         return len(num) + e - (num < "231") - 1
03198 
03199     def log10(self, context=None):
03200         """Returns the base 10 logarithm of self."""
03201 
03202         if context is None:
03203             context = getcontext()
03204 
03205         # log10(NaN) = NaN
03206         ans = self._check_nans(context=context)
03207         if ans:
03208             return ans
03209 
03210         # log10(0.0) == -Infinity
03211         if not self:
03212             return _NegativeInfinity
03213 
03214         # log10(Infinity) = Infinity
03215         if self._isinfinity() == 1:
03216             return _Infinity
03217 
03218         # log10(negative or -Infinity) raises InvalidOperation
03219         if self._sign == 1:
03220             return context._raise_error(InvalidOperation,
03221                                         'log10 of a negative value')
03222 
03223         # log10(10**n) = n
03224         if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
03225             # answer may need rounding
03226             ans = Decimal(self._exp + len(self._int) - 1)
03227         else:
03228             # result is irrational, so necessarily inexact
03229             op = _WorkRep(self)
03230             c, e = op.int, op.exp
03231             p = context.prec
03232 
03233             # correctly rounded result: repeatedly increase precision
03234             # until result is unambiguously roundable
03235             places = p-self._log10_exp_bound()+2
03236             while True:
03237                 coeff = _dlog10(c, e, places)
03238                 # assert len(str(abs(coeff)))-p >= 1
03239                 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
03240                     break
03241                 places += 3
03242             ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
03243 
03244         context = context._shallow_copy()
03245         rounding = context._set_rounding(ROUND_HALF_EVEN)
03246         ans = ans._fix(context)
03247         context.rounding = rounding
03248         return ans
03249 
03250     def logb(self, context=None):
03251         """ Returns the exponent of the magnitude of self's MSD.
03252 
03253         The result is the integer which is the exponent of the magnitude
03254         of the most significant digit of self (as though it were truncated
03255         to a single digit while maintaining the value of that digit and
03256         without limiting the resulting exponent).
03257         """
03258         # logb(NaN) = NaN
03259         ans = self._check_nans(context=context)
03260         if ans:
03261             return ans
03262 
03263         if context is None:
03264             context = getcontext()
03265 
03266         # logb(+/-Inf) = +Inf
03267         if self._isinfinity():
03268             return _Infinity
03269 
03270         # logb(0) = -Inf, DivisionByZero
03271         if not self:
03272             return context._raise_error(DivisionByZero, 'logb(0)', 1)
03273 
03274         # otherwise, simply return the adjusted exponent of self, as a
03275         # Decimal.  Note that no attempt is made to fit the result
03276         # into the current context.
03277         ans = Decimal(self.adjusted())
03278         return ans._fix(context)
03279 
03280     def _islogical(self):
03281         """Return True if self is a logical operand.
03282 
03283         For being logical, it must be a finite number with a sign of 0,
03284         an exponent of 0, and a coefficient whose digits must all be
03285         either 0 or 1.
03286         """
03287         if self._sign != 0 or self._exp != 0:
03288             return False
03289         for dig in self._int:
03290             if dig not in '01':
03291                 return False
03292         return True
03293 
03294     def _fill_logical(self, context, opa, opb):
03295         dif = context.prec - len(opa)
03296         if dif > 0:
03297             opa = '0'*dif + opa
03298         elif dif < 0:
03299             opa = opa[-context.prec:]
03300         dif = context.prec - len(opb)
03301         if dif > 0:
03302             opb = '0'*dif + opb
03303         elif dif < 0:
03304             opb = opb[-context.prec:]
03305         return opa, opb
03306 
03307     def logical_and(self, other, context=None):
03308         """Applies an 'and' operation between self and other's digits."""
03309         if context is None:
03310             context = getcontext()
03311 
03312         other = _convert_other(other, raiseit=True)
03313 
03314         if not self._islogical() or not other._islogical():
03315             return context._raise_error(InvalidOperation)
03316 
03317         # fill to context.prec
03318         (opa, opb) = self._fill_logical(context, self._int, other._int)
03319 
03320         # make the operation, and clean starting zeroes
03321         result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
03322         return _dec_from_triple(0, result.lstrip('0') or '0', 0)
03323 
03324     def logical_invert(self, context=None):
03325         """Invert all its digits."""
03326         if context is None:
03327             context = getcontext()
03328         return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
03329                                 context)
03330 
03331     def logical_or(self, other, context=None):
03332         """Applies an 'or' operation between self and other's digits."""
03333         if context is None:
03334             context = getcontext()
03335 
03336         other = _convert_other(other, raiseit=True)
03337 
03338         if not self._islogical() or not other._islogical():
03339             return context._raise_error(InvalidOperation)
03340 
03341         # fill to context.prec
03342         (opa, opb) = self._fill_logical(context, self._int, other._int)
03343 
03344         # make the operation, and clean starting zeroes
03345         result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
03346         return _dec_from_triple(0, result.lstrip('0') or '0', 0)
03347 
03348     def logical_xor(self, other, context=None):
03349         """Applies an 'xor' operation between self and other's digits."""
03350         if context is None:
03351             context = getcontext()
03352 
03353         other = _convert_other(other, raiseit=True)
03354 
03355         if not self._islogical() or not other._islogical():
03356             return context._raise_error(InvalidOperation)
03357 
03358         # fill to context.prec
03359         (opa, opb) = self._fill_logical(context, self._int, other._int)
03360 
03361         # make the operation, and clean starting zeroes
03362         result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
03363         return _dec_from_triple(0, result.lstrip('0') or '0', 0)
03364 
03365     def max_mag(self, other, context=None):
03366         """Compares the values numerically with their sign ignored."""
03367         other = _convert_other(other, raiseit=True)
03368 
03369         if context is None:
03370             context = getcontext()
03371 
03372         if self._is_special or other._is_special:
03373             # If one operand is a quiet NaN and the other is number, then the
03374             # number is always returned
03375             sn = self._isnan()
03376             on = other._isnan()
03377             if sn or on:
03378                 if on == 1 and sn == 0:
03379                     return self._fix(context)
03380                 if sn == 1 and on == 0:
03381                     return other._fix(context)
03382                 return self._check_nans(other, context)
03383 
03384         c = self.copy_abs()._cmp(other.copy_abs())
03385         if c == 0:
03386             c = self.compare_total(other)
03387 
03388         if c == -1:
03389             ans = other
03390         else:
03391             ans = self
03392 
03393         return ans._fix(context)
03394 
03395     def min_mag(self, other, context=None):
03396         """Compares the values numerically with their sign ignored."""
03397         other = _convert_other(other, raiseit=True)
03398 
03399         if context is None:
03400             context = getcontext()
03401 
03402         if self._is_special or other._is_special:
03403             # If one operand is a quiet NaN and the other is number, then the
03404             # number is always returned
03405             sn = self._isnan()
03406             on = other._isnan()
03407             if sn or on:
03408                 if on == 1 and sn == 0:
03409                     return self._fix(context)
03410                 if sn == 1 and on == 0:
03411                     return other._fix(context)
03412                 return self._check_nans(other, context)
03413 
03414         c = self.copy_abs()._cmp(other.copy_abs())
03415         if c == 0:
03416             c = self.compare_total(other)
03417 
03418         if c == -1:
03419             ans = self
03420         else:
03421             ans = other
03422 
03423         return ans._fix(context)
03424 
03425     def next_minus(self, context=None):
03426         """Returns the largest representable number smaller than itself."""
03427         if context is None:
03428             context = getcontext()
03429 
03430         ans = self._check_nans(context=context)
03431         if ans:
03432             return ans
03433 
03434         if self._isinfinity() == -1:
03435             return _NegativeInfinity
03436         if self._isinfinity() == 1:
03437             return _dec_from_triple(0, '9'*context.prec, context.Etop())
03438 
03439         context = context.copy()
03440         context._set_rounding(ROUND_FLOOR)
03441         context._ignore_all_flags()
03442         new_self = self._fix(context)
03443         if new_self != self:
03444             return new_self
03445         return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
03446                             context)
03447 
03448     def next_plus(self, context=None):
03449         """Returns the smallest representable number larger than itself."""
03450         if context is None:
03451             context = getcontext()
03452 
03453         ans = self._check_nans(context=context)
03454         if ans:
03455             return ans
03456 
03457         if self._isinfinity() == 1:
03458             return _Infinity
03459         if self._isinfinity() == -1:
03460             return _dec_from_triple(1, '9'*context.prec, context.Etop())
03461 
03462         context = context.copy()
03463         context._set_rounding(ROUND_CEILING)
03464         context._ignore_all_flags()
03465         new_self = self._fix(context)
03466         if new_self != self:
03467             return new_self
03468         return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
03469                             context)
03470 
03471     def next_toward(self, other, context=None):
03472         """Returns the number closest to self, in the direction towards other.
03473 
03474         The result is the closest representable number to self
03475         (excluding self) that is in the direction towards other,
03476         unless both have the same value.  If the two operands are
03477         numerically equal, then the result is a copy of self with the
03478         sign set to be the same as the sign of other.
03479         """
03480         other = _convert_other(other, raiseit=True)
03481 
03482         if context is None:
03483             context = getcontext()
03484 
03485         ans = self._check_nans(other, context)
03486         if ans:
03487             return ans
03488 
03489         comparison = self._cmp(other)
03490         if comparison == 0:
03491             return self.copy_sign(other)
03492 
03493         if comparison == -1:
03494             ans = self.next_plus(context)
03495         else: # comparison == 1
03496             ans = self.next_minus(context)
03497 
03498         # decide which flags to raise using value of ans
03499         if ans._isinfinity():
03500             context._raise_error(Overflow,
03501                                  'Infinite result from next_toward',
03502                                  ans._sign)
03503             context._raise_error(Inexact)
03504             context._raise_error(Rounded)
03505         elif ans.adjusted() < context.Emin:
03506             context._raise_error(Underflow)
03507             context._raise_error(Subnormal)
03508             context._raise_error(Inexact)
03509             context._raise_error(Rounded)
03510             # if precision == 1 then we don't raise Clamped for a
03511             # result 0E-Etiny.
03512             if not ans:
03513                 context._raise_error(Clamped)
03514 
03515         return ans
03516 
03517     def number_class(self, context=None):
03518         """Returns an indication of the class of self.
03519 
03520         The class is one of the following strings:
03521           sNaN
03522           NaN
03523           -Infinity
03524           -Normal
03525           -Subnormal
03526           -Zero
03527           +Zero
03528           +Subnormal
03529           +Normal
03530           +Infinity
03531         """
03532         if self.is_snan():
03533             return "sNaN"
03534         if self.is_qnan():
03535             return "NaN"
03536         inf = self._isinfinity()
03537         if inf == 1:
03538             return "+Infinity"
03539         if inf == -1:
03540             return "-Infinity"
03541         if self.is_zero():
03542             if self._sign:
03543                 return "-Zero"
03544             else:
03545                 return "+Zero"
03546         if context is None:
03547             context = getcontext()
03548         if self.is_subnormal(context=context):
03549             if self._sign:
03550                 return "-Subnormal"
03551             else:
03552                 return "+Subnormal"
03553         # just a normal, regular, boring number, :)
03554         if self._sign:
03555             return "-Normal"
03556         else:
03557             return "+Normal"
03558 
03559     def radix(self):
03560         """Just returns 10, as this is Decimal, :)"""
03561         return Decimal(10)
03562 
03563     def rotate(self, other, context=None):
03564         """Returns a rotated copy of self, value-of-other times."""
03565         if context is None:
03566             context = getcontext()
03567 
03568         other = _convert_other(other, raiseit=True)
03569 
03570         ans = self._check_nans(other, context)
03571         if ans:
03572             return ans
03573 
03574         if other._exp != 0:
03575             return context._raise_error(InvalidOperation)
03576         if not (-context.prec <= int(other) <= context.prec):
03577             return context._raise_error(InvalidOperation)
03578 
03579         if self._isinfinity():
03580             return Decimal(self)
03581 
03582         # get values, pad if necessary
03583         torot = int(other)
03584         rotdig = self._int
03585         topad = context.prec - len(rotdig)
03586         if topad > 0:
03587             rotdig = '0'*topad + rotdig
03588         elif topad < 0:
03589             rotdig = rotdig[-topad:]
03590 
03591         # let's rotate!
03592         rotated = rotdig[torot:] + rotdig[:torot]
03593         return _dec_from_triple(self._sign,
03594                                 rotated.lstrip('0') or '0', self._exp)
03595 
03596     def scaleb(self, other, context=None):
03597         """Returns self operand after adding the second value to its exp."""
03598         if context is None:
03599             context = getcontext()
03600 
03601         other = _convert_other(other, raiseit=True)
03602 
03603         ans = self._check_nans(other, context)
03604         if ans:
03605             return ans
03606 
03607         if other._exp != 0:
03608             return context._raise_error(InvalidOperation)
03609         liminf = -2 * (context.Emax + context.prec)
03610         limsup =  2 * (context.Emax + context.prec)
03611         if not (liminf <= int(other) <= limsup):
03612             return context._raise_error(InvalidOperation)
03613 
03614         if self._isinfinity():
03615             return Decimal(self)
03616 
03617         d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
03618         d = d._fix(context)
03619         return d
03620 
03621     def shift(self, other, context=None):
03622         """Returns a shifted copy of self, value-of-other times."""
03623         if context is None:
03624             context = getcontext()
03625 
03626         other = _convert_other(other, raiseit=True)
03627 
03628         ans = self._check_nans(other, context)
03629         if ans:
03630             return ans
03631 
03632         if other._exp != 0:
03633             return context._raise_error(InvalidOperation)
03634         if not (-context.prec <= int(other) <= context.prec):
03635             return context._raise_error(InvalidOperation)
03636 
03637         if self._isinfinity():
03638             return Decimal(self)
03639 
03640         # get values, pad if necessary
03641         torot = int(other)
03642         rotdig = self._int
03643         topad = context.prec - len(rotdig)
03644         if topad > 0:
03645             rotdig = '0'*topad + rotdig
03646         elif topad < 0:
03647             rotdig = rotdig[-topad:]
03648 
03649         # let's shift!
03650         if torot < 0:
03651             shifted = rotdig[:torot]
03652         else:
03653             shifted = rotdig + '0'*torot
03654             shifted = shifted[-context.prec:]
03655 
03656         return _dec_from_triple(self._sign,
03657                                     shifted.lstrip('0') or '0', self._exp)
03658 
03659     # Support for pickling, copy, and deepcopy
03660     def __reduce__(self):
03661         return (self.__class__, (str(self),))
03662 
03663     def __copy__(self):
03664         if type(self) is Decimal:
03665             return self     # I'm immutable; therefore I am my own clone
03666         return self.__class__(str(self))
03667 
03668     def __deepcopy__(self, memo):
03669         if type(self) is Decimal:
03670             return self     # My components are also immutable
03671         return self.__class__(str(self))
03672 
03673     # PEP 3101 support.  the _localeconv keyword argument should be
03674     # considered private: it's provided for ease of testing only.
03675     def __format__(self, specifier, context=None, _localeconv=None):
03676         """Format a Decimal instance according to the given specifier.
03677 
03678         The specifier should be a standard format specifier, with the
03679         form described in PEP 3101.  Formatting types 'e', 'E', 'f',
03680         'F', 'g', 'G', 'n' and '%' are supported.  If the formatting
03681         type is omitted it defaults to 'g' or 'G', depending on the
03682         value of context.capitals.
03683         """
03684 
03685         # Note: PEP 3101 says that if the type is not present then
03686         # there should be at least one digit after the decimal point.
03687         # We take the liberty of ignoring this requirement for
03688         # Decimal---it's presumably there to make sure that
03689         # format(float, '') behaves similarly to str(float).
03690         if context is None:
03691             context = getcontext()
03692 
03693         spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
03694 
03695         # special values don't care about the type or precision
03696         if self._is_special:
03697             sign = _format_sign(self._sign, spec)
03698             body = str(self.copy_abs())
03699             return _format_align(sign, body, spec)
03700 
03701         # a type of None defaults to 'g' or 'G', depending on context
03702         if spec['type'] is None:
03703             spec['type'] = ['g', 'G'][context.capitals]
03704 
03705         # if type is '%', adjust exponent of self accordingly
03706         if spec['type'] == '%':
03707             self = _dec_from_triple(self._sign, self._int, self._exp+2)
03708 
03709         # round if necessary, taking rounding mode from the context
03710         rounding = context.rounding
03711         precision = spec['precision']
03712         if precision is not None:
03713             if spec['type'] in 'eE':
03714                 self = self._round(precision+1, rounding)
03715             elif spec['type'] in 'fF%':
03716                 self = self._rescale(-precision, rounding)
03717             elif spec['type'] in 'gG' and len(self._int) > precision:
03718                 self = self._round(precision, rounding)
03719         # special case: zeros with a positive exponent can't be
03720         # represented in fixed point; rescale them to 0e0.
03721         if not self and self._exp > 0 and spec['type'] in 'fF%':
03722             self = self._rescale(0, rounding)
03723 
03724         # figure out placement of the decimal point
03725         leftdigits = self._exp + len(self._int)
03726         if spec['type'] in 'eE':
03727             if not self and precision is not None:
03728                 dotplace = 1 - precision
03729             else:
03730                 dotplace = 1
03731         elif spec['type'] in 'fF%':
03732             dotplace = leftdigits
03733         elif spec['type'] in 'gG':
03734             if self._exp <= 0 and leftdigits > -6:
03735                 dotplace = leftdigits
03736             else:
03737                 dotplace = 1
03738 
03739         # find digits before and after decimal point, and get exponent
03740         if dotplace < 0:
03741             intpart = '0'
03742             fracpart = '0'*(-dotplace) + self._int
03743         elif dotplace > len(self._int):
03744             intpart = self._int + '0'*(dotplace-len(self._int))
03745             fracpart = ''
03746         else:
03747             intpart = self._int[:dotplace] or '0'
03748             fracpart = self._int[dotplace:]
03749         exp = leftdigits-dotplace
03750 
03751         # done with the decimal-specific stuff;  hand over the rest
03752         # of the formatting to the _format_number function
03753         return _format_number(self._sign, intpart, fracpart, exp, spec)
03754 
03755 def _dec_from_triple(sign, coefficient, exponent, special=False):
03756     """Create a decimal instance directly, without any validation,
03757     normalization (e.g. removal of leading zeros) or argument
03758     conversion.
03759 
03760     This function is for *internal use only*.
03761     """
03762 
03763     self = object.__new__(Decimal)
03764     self._sign = sign
03765     self._int = coefficient
03766     self._exp = exponent
03767     self._is_special = special
03768 
03769     return self
03770 
03771 # Register Decimal as a kind of Number (an abstract base class).
03772 # However, do not register it as Real (because Decimals are not
03773 # interoperable with floats).
03774 _numbers.Number.register(Decimal)
03775 
03776 
03777 ##### Context class #######################################################
03778 
03779 class _ContextManager(object):
03780     """Context manager class to support localcontext().
03781 
03782       Sets a copy of the supplied context in __enter__() and restores
03783       the previous decimal context in __exit__()
03784     """
03785     def __init__(self, new_context):
03786         self.new_context = new_context.copy()
03787     def __enter__(self):
03788         self.saved_context = getcontext()
03789         setcontext(self.new_context)
03790         return self.new_context
03791     def __exit__(self, t, v, tb):
03792         setcontext(self.saved_context)
03793 
03794 class Context(object):
03795     """Contains the context for a Decimal instance.
03796 
03797     Contains:
03798     prec - precision (for use in rounding, division, square roots..)
03799     rounding - rounding type (how you round)
03800     traps - If traps[exception] = 1, then the exception is
03801                     raised when it is caused.  Otherwise, a value is
03802                     substituted in.
03803     flags  - When an exception is caused, flags[exception] is set.
03804              (Whether or not the trap_enabler is set)
03805              Should be reset by user of Decimal instance.
03806     Emin -   Minimum exponent
03807     Emax -   Maximum exponent
03808     capitals -      If 1, 1*10^1 is printed as 1E+1.
03809                     If 0, printed as 1e1
03810     clamp -  If 1, change exponents if too high (Default 0)
03811     """
03812 
03813     def __init__(self, prec=None, rounding=None,
03814                  traps=None, flags=None,
03815                  Emin=None, Emax=None,
03816                  capitals=None, clamp=None,
03817                  _ignored_flags=None):
03818         # Set defaults; for everything except flags and _ignored_flags,
03819         # inherit from DefaultContext.
03820         try:
03821             dc = DefaultContext
03822         except NameError:
03823             pass
03824 
03825         self.prec = prec if prec is not None else dc.prec
03826         self.rounding = rounding if rounding is not None else dc.rounding
03827         self.Emin = Emin if Emin is not None else dc.Emin
03828         self.Emax = Emax if Emax is not None else dc.Emax
03829         self.capitals = capitals if capitals is not None else dc.capitals
03830         self.clamp = clamp if clamp is not None else dc.clamp
03831 
03832         if _ignored_flags is None:
03833             self._ignored_flags = []
03834         else:
03835             self._ignored_flags = _ignored_flags
03836 
03837         if traps is None:
03838             self.traps = dc.traps.copy()
03839         elif not isinstance(traps, dict):
03840             self.traps = dict((s, int(s in traps)) for s in _signals)
03841         else:
03842             self.traps = traps
03843 
03844         if flags is None:
03845             self.flags = dict.fromkeys(_signals, 0)
03846         elif not isinstance(flags, dict):
03847             self.flags = dict((s, int(s in flags)) for s in _signals)
03848         else:
03849             self.flags = flags
03850 
03851     def __repr__(self):
03852         """Show the current context."""
03853         s = []
03854         s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
03855                  'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d, '
03856                  'clamp=%(clamp)d'
03857                  % vars(self))
03858         names = [f.__name__ for f, v in self.flags.items() if v]
03859         s.append('flags=[' + ', '.join(names) + ']')
03860         names = [t.__name__ for t, v in self.traps.items() if v]
03861         s.append('traps=[' + ', '.join(names) + ']')
03862         return ', '.join(s) + ')'
03863 
03864     def clear_flags(self):
03865         """Reset all flags to zero"""
03866         for flag in self.flags:
03867             self.flags[flag] = 0
03868 
03869     def _shallow_copy(self):
03870         """Returns a shallow copy from self."""
03871         nc = Context(self.prec, self.rounding, self.traps,
03872                      self.flags, self.Emin, self.Emax,
03873                      self.capitals, self.clamp, self._ignored_flags)
03874         return nc
03875 
03876     def copy(self):
03877         """Returns a deep copy from self."""
03878         nc = Context(self.prec, self.rounding, self.traps.copy(),
03879                      self.flags.copy(), self.Emin, self.Emax,
03880                      self.capitals, self.clamp, self._ignored_flags)
03881         return nc
03882     __copy__ = copy
03883 
03884     # _clamp is provided for backwards compatibility with third-party
03885     # code.  May be removed in Python >= 3.3.
03886     def _get_clamp(self):
03887         "_clamp mirrors the clamp attribute.  Its use is deprecated."
03888         import warnings
03889         warnings.warn('Use of the _clamp attribute is deprecated. '
03890                       'Please use clamp instead.',
03891                       DeprecationWarning)
03892         return self.clamp
03893 
03894     def _set_clamp(self, clamp):
03895         "_clamp mirrors the clamp attribute.  Its use is deprecated."
03896         import warnings
03897         warnings.warn('Use of the _clamp attribute is deprecated. '
03898                       'Please use clamp instead.',
03899                       DeprecationWarning)
03900         self.clamp = clamp
03901 
03902     # don't bother with _del_clamp;  no sane 3rd party code should
03903     # be deleting the _clamp attribute
03904     _clamp = property(_get_clamp, _set_clamp)
03905 
03906     def _raise_error(self, condition, explanation = None, *args):
03907         """Handles an error
03908 
03909         If the flag is in _ignored_flags, returns the default response.
03910         Otherwise, it sets the flag, then, if the corresponding
03911         trap_enabler is set, it reraises the exception.  Otherwise, it returns
03912         the default value after setting the flag.
03913         """
03914         error = _condition_map.get(condition, condition)
03915         if error in self._ignored_flags:
03916             # Don't touch the flag
03917             return error().handle(self, *args)
03918 
03919         self.flags[error] = 1
03920         if not self.traps[error]:
03921             # The errors define how to handle themselves.
03922             return condition().handle(self, *args)
03923 
03924         # Errors should only be risked on copies of the context
03925         # self._ignored_flags = []
03926         raise error(explanation)
03927 
03928     def _ignore_all_flags(self):
03929         """Ignore all flags, if they are raised"""
03930         return self._ignore_flags(*_signals)
03931 
03932     def _ignore_flags(self, *flags):
03933         """Ignore the flags, if they are raised"""
03934         # Do not mutate-- This way, copies of a context leave the original
03935         # alone.
03936         self._ignored_flags = (self._ignored_flags + list(flags))
03937         return list(flags)
03938 
03939     def _regard_flags(self, *flags):
03940         """Stop ignoring the flags, if they are raised"""
03941         if flags and isinstance(flags[0], (tuple,list)):
03942             flags = flags[0]
03943         for flag in flags:
03944             self._ignored_flags.remove(flag)
03945 
03946     # We inherit object.__hash__, so we must deny this explicitly
03947     __hash__ = None
03948 
03949     def Etiny(self):
03950         """Returns Etiny (= Emin - prec + 1)"""
03951         return int(self.Emin - self.prec + 1)
03952 
03953     def Etop(self):
03954         """Returns maximum exponent (= Emax - prec + 1)"""
03955         return int(self.Emax - self.prec + 1)
03956 
03957     def _set_rounding(self, type):
03958         """Sets the rounding type.
03959 
03960         Sets the rounding type, and returns the current (previous)
03961         rounding type.  Often used like:
03962 
03963         context = context.copy()
03964         # so you don't change the calling context
03965         # if an error occurs in the middle.
03966         rounding = context._set_rounding(ROUND_UP)
03967         val = self.__sub__(other, context=context)
03968         context._set_rounding(rounding)
03969 
03970         This will make it round up for that operation.
03971         """
03972         rounding = self.rounding
03973         self.rounding= type
03974         return rounding
03975 
03976     def create_decimal(self, num='0'):
03977         """Creates a new Decimal instance but using self as context.
03978 
03979         This method implements the to-number operation of the
03980         IBM Decimal specification."""
03981 
03982         if isinstance(num, str) and num != num.strip():
03983             return self._raise_error(ConversionSyntax,
03984                                      "no trailing or leading whitespace is "
03985                                      "permitted.")
03986 
03987         d = Decimal(num, context=self)
03988         if d._isnan() and len(d._int) > self.prec - self.clamp:
03989             return self._raise_error(ConversionSyntax,
03990                                      "diagnostic info too long in NaN")
03991         return d._fix(self)
03992 
03993     def create_decimal_from_float(self, f):
03994         """Creates a new Decimal instance from a float but rounding using self
03995         as the context.
03996 
03997         >>> context = Context(prec=5, rounding=ROUND_DOWN)
03998         >>> context.create_decimal_from_float(3.1415926535897932)
03999         Decimal('3.1415')
04000         >>> context = Context(prec=5, traps=[Inexact])
04001         >>> context.create_decimal_from_float(3.1415926535897932)
04002         Traceback (most recent call last):
04003             ...
04004         decimal.Inexact: None
04005 
04006         """
04007         d = Decimal.from_float(f)       # An exact conversion
04008         return d._fix(self)             # Apply the context rounding
04009 
04010     # Methods
04011     def abs(self, a):
04012         """Returns the absolute value of the operand.
04013 
04014         If the operand is negative, the result is the same as using the minus
04015         operation on the operand.  Otherwise, the result is the same as using
04016         the plus operation on the operand.
04017 
04018         >>> ExtendedContext.abs(Decimal('2.1'))
04019         Decimal('2.1')
04020         >>> ExtendedContext.abs(Decimal('-100'))
04021         Decimal('100')
04022         >>> ExtendedContext.abs(Decimal('101.5'))
04023         Decimal('101.5')
04024         >>> ExtendedContext.abs(Decimal('-101.5'))
04025         Decimal('101.5')
04026         >>> ExtendedContext.abs(-1)
04027         Decimal('1')
04028         """
04029         a = _convert_other(a, raiseit=True)
04030         return a.__abs__(context=self)
04031 
04032     def add(self, a, b):
04033         """Return the sum of the two operands.
04034 
04035         >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
04036         Decimal('19.00')
04037         >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
04038         Decimal('1.02E+4')
04039         >>> ExtendedContext.add(1, Decimal(2))
04040         Decimal('3')
04041         >>> ExtendedContext.add(Decimal(8), 5)
04042         Decimal('13')
04043         >>> ExtendedContext.add(5, 5)
04044         Decimal('10')
04045         """
04046         a = _convert_other(a, raiseit=True)
04047         r = a.__add__(b, context=self)
04048         if r is NotImplemented:
04049             raise TypeError("Unable to convert %s to Decimal" % b)
04050         else:
04051             return r
04052 
04053     def _apply(self, a):
04054         return str(a._fix(self))
04055 
04056     def canonical(self, a):
04057         """Returns the same Decimal object.
04058 
04059         As we do not have different encodings for the same number, the
04060         received object already is in its canonical form.
04061 
04062         >>> ExtendedContext.canonical(Decimal('2.50'))
04063         Decimal('2.50')
04064         """
04065         return a.canonical(context=self)
04066 
04067     def compare(self, a, b):
04068         """Compares values numerically.
04069 
04070         If the signs of the operands differ, a value representing each operand
04071         ('-1' if the operand is less than zero, '0' if the operand is zero or
04072         negative zero, or '1' if the operand is greater than zero) is used in
04073         place of that operand for the comparison instead of the actual
04074         operand.
04075 
04076         The comparison is then effected by subtracting the second operand from
04077         the first and then returning a value according to the result of the
04078         subtraction: '-1' if the result is less than zero, '0' if the result is
04079         zero or negative zero, or '1' if the result is greater than zero.
04080 
04081         >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
04082         Decimal('-1')
04083         >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
04084         Decimal('0')
04085         >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
04086         Decimal('0')
04087         >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
04088         Decimal('1')
04089         >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
04090         Decimal('1')
04091         >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
04092         Decimal('-1')
04093         >>> ExtendedContext.compare(1, 2)
04094         Decimal('-1')
04095         >>> ExtendedContext.compare(Decimal(1), 2)
04096         Decimal('-1')
04097         >>> ExtendedContext.compare(1, Decimal(2))
04098         Decimal('-1')
04099         """
04100         a = _convert_other(a, raiseit=True)
04101         return a.compare(b, context=self)
04102 
04103     def compare_signal(self, a, b):
04104         """Compares the values of the two operands numerically.
04105 
04106         It's pretty much like compare(), but all NaNs signal, with signaling
04107         NaNs taking precedence over quiet NaNs.
04108 
04109         >>> c = ExtendedContext
04110         >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
04111         Decimal('-1')
04112         >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
04113         Decimal('0')
04114         >>> c.flags[InvalidOperation] = 0
04115         >>> print(c.flags[InvalidOperation])
04116         0
04117         >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
04118         Decimal('NaN')
04119         >>> print(c.flags[InvalidOperation])
04120         1
04121         >>> c.flags[InvalidOperation] = 0
04122         >>> print(c.flags[InvalidOperation])
04123         0
04124         >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
04125         Decimal('NaN')
04126         >>> print(c.flags[InvalidOperation])
04127         1
04128         >>> c.compare_signal(-1, 2)
04129         Decimal('-1')
04130         >>> c.compare_signal(Decimal(-1), 2)
04131         Decimal('-1')
04132         >>> c.compare_signal(-1, Decimal(2))
04133         Decimal('-1')
04134         """
04135         a = _convert_other(a, raiseit=True)
04136         return a.compare_signal(b, context=self)
04137 
04138     def compare_total(self, a, b):
04139         """Compares two operands using their abstract representation.
04140 
04141         This is not like the standard compare, which use their numerical
04142         value. Note that a total ordering is defined for all possible abstract
04143         representations.
04144 
04145         >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
04146         Decimal('-1')
04147         >>> ExtendedContext.compare_total(Decimal('-127'),  Decimal('12'))
04148         Decimal('-1')
04149         >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
04150         Decimal('-1')
04151         >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
04152         Decimal('0')
04153         >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('12.300'))
04154         Decimal('1')
04155         >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('NaN'))
04156         Decimal('-1')
04157         >>> ExtendedContext.compare_total(1, 2)
04158         Decimal('-1')
04159         >>> ExtendedContext.compare_total(Decimal(1), 2)
04160         Decimal('-1')
04161         >>> ExtendedContext.compare_total(1, Decimal(2))
04162         Decimal('-1')
04163         """
04164         a = _convert_other(a, raiseit=True)
04165         return a.compare_total(b)
04166 
04167     def compare_total_mag(self, a, b):
04168         """Compares two operands using their abstract representation ignoring sign.
04169 
04170         Like compare_total, but with operand's sign ignored and assumed to be 0.
04171         """
04172         a = _convert_other(a, raiseit=True)
04173         return a.compare_total_mag(b)
04174 
04175     def copy_abs(self, a):
04176         """Returns a copy of the operand with the sign set to 0.
04177 
04178         >>> ExtendedContext.copy_abs(Decimal('2.1'))
04179         Decimal('2.1')
04180         >>> ExtendedContext.copy_abs(Decimal('-100'))
04181         Decimal('100')
04182         >>> ExtendedContext.copy_abs(-1)
04183         Decimal('1')
04184         """
04185         a = _convert_other(a, raiseit=True)
04186         return a.copy_abs()
04187 
04188     def copy_decimal(self, a):
04189         """Returns a copy of the decimal object.
04190 
04191         >>> ExtendedContext.copy_decimal(Decimal('2.1'))
04192         Decimal('2.1')
04193         >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
04194         Decimal('-1.00')
04195         >>> ExtendedContext.copy_decimal(1)
04196         Decimal('1')
04197         """
04198         a = _convert_other(a, raiseit=True)
04199         return Decimal(a)
04200 
04201     def copy_negate(self, a):
04202         """Returns a copy of the operand with the sign inverted.
04203 
04204         >>> ExtendedContext.copy_negate(Decimal('101.5'))
04205         Decimal('-101.5')
04206         >>> ExtendedContext.copy_negate(Decimal('-101.5'))
04207         Decimal('101.5')
04208         >>> ExtendedContext.copy_negate(1)
04209         Decimal('-1')
04210         """
04211         a = _convert_other(a, raiseit=True)
04212         return a.copy_negate()
04213 
04214     def copy_sign(self, a, b):
04215         """Copies the second operand's sign to the first one.
04216 
04217         In detail, it returns a copy of the first operand with the sign
04218         equal to the sign of the second operand.
04219 
04220         >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
04221         Decimal('1.50')
04222         >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
04223         Decimal('1.50')
04224         >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
04225         Decimal('-1.50')
04226         >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
04227         Decimal('-1.50')
04228         >>> ExtendedContext.copy_sign(1, -2)
04229         Decimal('-1')
04230         >>> ExtendedContext.copy_sign(Decimal(1), -2)
04231         Decimal('-1')
04232         >>> ExtendedContext.copy_sign(1, Decimal(-2))
04233         Decimal('-1')
04234         """
04235         a = _convert_other(a, raiseit=True)
04236         return a.copy_sign(b)
04237 
04238     def divide(self, a, b):
04239         """Decimal division in a specified context.
04240 
04241         >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
04242         Decimal('0.333333333')
04243         >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
04244         Decimal('0.666666667')
04245         >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
04246         Decimal('2.5')
04247         >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
04248         Decimal('0.1')
04249         >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
04250         Decimal('1')
04251         >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
04252         Decimal('4.00')
04253         >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
04254         Decimal('1.20')
04255         >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
04256         Decimal('10')
04257         >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
04258         Decimal('1000')
04259         >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
04260         Decimal('1.20E+6')
04261         >>> ExtendedContext.divide(5, 5)
04262         Decimal('1')
04263         >>> ExtendedContext.divide(Decimal(5), 5)
04264         Decimal('1')
04265         >>> ExtendedContext.divide(5, Decimal(5))
04266         Decimal('1')
04267         """
04268         a = _convert_other(a, raiseit=True)
04269         r = a.__truediv__(b, context=self)
04270         if r is NotImplemented:
04271             raise TypeError("Unable to convert %s to Decimal" % b)
04272         else:
04273             return r
04274 
04275     def divide_int(self, a, b):
04276         """Divides two numbers and returns the integer part of the result.
04277 
04278         >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
04279         Decimal('0')
04280         >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
04281         Decimal('3')
04282         >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
04283         Decimal('3')
04284         >>> ExtendedContext.divide_int(10, 3)
04285         Decimal('3')
04286         >>> ExtendedContext.divide_int(Decimal(10), 3)
04287         Decimal('3')
04288         >>> ExtendedContext.divide_int(10, Decimal(3))
04289         Decimal('3')
04290         """
04291         a = _convert_other(a, raiseit=True)
04292         r = a.__floordiv__(b, context=self)
04293         if r is NotImplemented:
04294             raise TypeError("Unable to convert %s to Decimal" % b)
04295         else:
04296             return r
04297 
04298     def divmod(self, a, b):
04299         """Return (a // b, a % b).
04300 
04301         >>> ExtendedContext.divmod(Decimal(8), Decimal(3))
04302         (Decimal('2'), Decimal('2'))
04303         >>> ExtendedContext.divmod(Decimal(8), Decimal(4))
04304         (Decimal('2'), Decimal('0'))
04305         >>> ExtendedContext.divmod(8, 4)
04306         (Decimal('2'), Decimal('0'))
04307         >>> ExtendedContext.divmod(Decimal(8), 4)
04308         (Decimal('2'), Decimal('0'))
04309         >>> ExtendedContext.divmod(8, Decimal(4))
04310         (Decimal('2'), Decimal('0'))
04311         """
04312         a = _convert_other(a, raiseit=True)
04313         r = a.__divmod__(b, context=self)
04314         if r is NotImplemented:
04315             raise TypeError("Unable to convert %s to Decimal" % b)
04316         else:
04317             return r
04318 
04319     def exp(self, a):
04320         """Returns e ** a.
04321 
04322         >>> c = ExtendedContext.copy()
04323         >>> c.Emin = -999
04324         >>> c.Emax = 999
04325         >>> c.exp(Decimal('-Infinity'))
04326         Decimal('0')
04327         >>> c.exp(Decimal('-1'))
04328         Decimal('0.367879441')
04329         >>> c.exp(Decimal('0'))
04330         Decimal('1')
04331         >>> c.exp(Decimal('1'))
04332         Decimal('2.71828183')
04333         >>> c.exp(Decimal('0.693147181'))
04334         Decimal('2.00000000')
04335         >>> c.exp(Decimal('+Infinity'))
04336         Decimal('Infinity')
04337         >>> c.exp(10)
04338         Decimal('22026.4658')
04339         """
04340         a =_convert_other(a, raiseit=True)
04341         return a.exp(context=self)
04342 
04343     def fma(self, a, b, c):
04344         """Returns a multiplied by b, plus c.
04345 
04346         The first two operands are multiplied together, using multiply,
04347         the third operand is then added to the result of that
04348         multiplication, using add, all with only one final rounding.
04349 
04350         >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
04351         Decimal('22')
04352         >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
04353         Decimal('-8')
04354         >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
04355         Decimal('1.38435736E+12')
04356         >>> ExtendedContext.fma(1, 3, 4)
04357         Decimal('7')
04358         >>> ExtendedContext.fma(1, Decimal(3), 4)
04359         Decimal('7')
04360         >>> ExtendedContext.fma(1, 3, Decimal(4))
04361         Decimal('7')
04362         """
04363         a = _convert_other(a, raiseit=True)
04364         return a.fma(b, c, context=self)
04365 
04366     def is_canonical(self, a):
04367         """Return True if the operand is canonical; otherwise return False.
04368 
04369         Currently, the encoding of a Decimal instance is always
04370         canonical, so this method returns True for any Decimal.
04371 
04372         >>> ExtendedContext.is_canonical(Decimal('2.50'))
04373         True
04374         """
04375         return a.is_canonical()
04376 
04377     def is_finite(self, a):
04378         """Return True if the operand is finite; otherwise return False.
04379 
04380         A Decimal instance is considered finite if it is neither
04381         infinite nor a NaN.
04382 
04383         >>> ExtendedContext.is_finite(Decimal('2.50'))
04384         True
04385         >>> ExtendedContext.is_finite(Decimal('-0.3'))
04386         True
04387         >>> ExtendedContext.is_finite(Decimal('0'))
04388         True
04389         >>> ExtendedContext.is_finite(Decimal('Inf'))
04390         False
04391         >>> ExtendedContext.is_finite(Decimal('NaN'))
04392         False
04393         >>> ExtendedContext.is_finite(1)
04394         True
04395         """
04396         a = _convert_other(a, raiseit=True)
04397         return a.is_finite()
04398 
04399     def is_infinite(self, a):
04400         """Return True if the operand is infinite; otherwise return False.
04401 
04402         >>> ExtendedContext.is_infinite(Decimal('2.50'))
04403         False
04404         >>> ExtendedContext.is_infinite(Decimal('-Inf'))
04405         True
04406         >>> ExtendedContext.is_infinite(Decimal('NaN'))
04407         False
04408         >>> ExtendedContext.is_infinite(1)
04409         False
04410         """
04411         a = _convert_other(a, raiseit=True)
04412         return a.is_infinite()
04413 
04414     def is_nan(self, a):
04415         """Return True if the operand is a qNaN or sNaN;
04416         otherwise return False.
04417 
04418         >>> ExtendedContext.is_nan(Decimal('2.50'))
04419         False
04420         >>> ExtendedContext.is_nan(Decimal('NaN'))
04421         True
04422         >>> ExtendedContext.is_nan(Decimal('-sNaN'))
04423         True
04424         >>> ExtendedContext.is_nan(1)
04425         False
04426         """
04427         a = _convert_other(a, raiseit=True)
04428         return a.is_nan()
04429 
04430     def is_normal(self, a):
04431         """Return True if the operand is a normal number;
04432         otherwise return False.
04433 
04434         >>> c = ExtendedContext.copy()
04435         >>> c.Emin = -999
04436         >>> c.Emax = 999
04437         >>> c.is_normal(Decimal('2.50'))
04438         True
04439         >>> c.is_normal(Decimal('0.1E-999'))
04440         False
04441         >>> c.is_normal(Decimal('0.00'))
04442         False
04443         >>> c.is_normal(Decimal('-Inf'))
04444         False
04445         >>> c.is_normal(Decimal('NaN'))
04446         False
04447         >>> c.is_normal(1)
04448         True
04449         """
04450         a = _convert_other(a, raiseit=True)
04451         return a.is_normal(context=self)
04452 
04453     def is_qnan(self, a):
04454         """Return True if the operand is a quiet NaN; otherwise return False.
04455 
04456         >>> ExtendedContext.is_qnan(Decimal('2.50'))
04457         False
04458         >>> ExtendedContext.is_qnan(Decimal('NaN'))
04459         True
04460         >>> ExtendedContext.is_qnan(Decimal('sNaN'))
04461         False
04462         >>> ExtendedContext.is_qnan(1)
04463         False
04464         """
04465         a = _convert_other(a, raiseit=True)
04466         return a.is_qnan()
04467 
04468     def is_signed(self, a):
04469         """Return True if the operand is negative; otherwise return False.
04470 
04471         >>> ExtendedContext.is_signed(Decimal('2.50'))
04472         False
04473         >>> ExtendedContext.is_signed(Decimal('-12'))
04474         True
04475         >>> ExtendedContext.is_signed(Decimal('-0'))
04476         True
04477         >>> ExtendedContext.is_signed(8)
04478         False
04479         >>> ExtendedContext.is_signed(-8)
04480         True
04481         """
04482         a = _convert_other(a, raiseit=True)
04483         return a.is_signed()
04484 
04485     def is_snan(self, a):
04486         """Return True if the operand is a signaling NaN;
04487         otherwise return False.
04488 
04489         >>> ExtendedContext.is_snan(Decimal('2.50'))
04490         False
04491         >>> ExtendedContext.is_snan(Decimal('NaN'))
04492         False
04493         >>> ExtendedContext.is_snan(Decimal('sNaN'))
04494         True
04495         >>> ExtendedContext.is_snan(1)
04496         False
04497         """
04498         a = _convert_other(a, raiseit=True)
04499         return a.is_snan()
04500 
04501     def is_subnormal(self, a):
04502         """Return True if the operand is subnormal; otherwise return False.
04503 
04504         >>> c = ExtendedContext.copy()
04505         >>> c.Emin = -999
04506         >>> c.Emax = 999
04507         >>> c.is_subnormal(Decimal('2.50'))
04508         False
04509         >>> c.is_subnormal(Decimal('0.1E-999'))
04510         True
04511         >>> c.is_subnormal(Decimal('0.00'))
04512         False
04513         >>> c.is_subnormal(Decimal('-Inf'))
04514         False
04515         >>> c.is_subnormal(Decimal('NaN'))
04516         False
04517         >>> c.is_subnormal(1)
04518         False
04519         """
04520         a = _convert_other(a, raiseit=True)
04521         return a.is_subnormal(context=self)
04522 
04523     def is_zero(self, a):
04524         """Return True if the operand is a zero; otherwise return False.
04525 
04526         >>> ExtendedContext.is_zero(Decimal('0'))
04527         True
04528         >>> ExtendedContext.is_zero(Decimal('2.50'))
04529         False
04530         >>> ExtendedContext.is_zero(Decimal('-0E+2'))
04531         True
04532         >>> ExtendedContext.is_zero(1)
04533         False
04534         >>> ExtendedContext.is_zero(0)
04535         True
04536         """
04537         a = _convert_other(a, raiseit=True)
04538         return a.is_zero()
04539 
04540     def ln(self, a):
04541         """Returns the natural (base e) logarithm of the operand.
04542 
04543         >>> c = ExtendedContext.copy()
04544         >>> c.Emin = -999
04545         >>> c.Emax = 999
04546         >>> c.ln(Decimal('0'))
04547         Decimal('-Infinity')
04548         >>> c.ln(Decimal('1.000'))
04549         Decimal('0')
04550         >>> c.ln(Decimal('2.71828183'))
04551         Decimal('1.00000000')
04552         >>> c.ln(Decimal('10'))
04553         Decimal('2.30258509')
04554         >>> c.ln(Decimal('+Infinity'))
04555         Decimal('Infinity')
04556         >>> c.ln(1)
04557         Decimal('0')
04558         """
04559         a = _convert_other(a, raiseit=True)
04560         return a.ln(context=self)
04561 
04562     def log10(self, a):
04563         """Returns the base 10 logarithm of the operand.
04564 
04565         >>> c = ExtendedContext.copy()
04566         >>> c.Emin = -999
04567         >>> c.Emax = 999
04568         >>> c.log10(Decimal('0'))
04569         Decimal('-Infinity')
04570         >>> c.log10(Decimal('0.001'))
04571         Decimal('-3')
04572         >>> c.log10(Decimal('1.000'))
04573         Decimal('0')
04574         >>> c.log10(Decimal('2'))
04575         Decimal('0.301029996')
04576         >>> c.log10(Decimal('10'))
04577         Decimal('1')
04578         >>> c.log10(Decimal('70'))
04579         Decimal('1.84509804')
04580         >>> c.log10(Decimal('+Infinity'))
04581         Decimal('Infinity')
04582         >>> c.log10(0)
04583         Decimal('-Infinity')
04584         >>> c.log10(1)
04585         Decimal('0')
04586         """
04587         a = _convert_other(a, raiseit=True)
04588         return a.log10(context=self)
04589 
04590     def logb(self, a):
04591         """ Returns the exponent of the magnitude of the operand's MSD.
04592 
04593         The result is the integer which is the exponent of the magnitude
04594         of the most significant digit of the operand (as though the
04595         operand were truncated to a single digit while maintaining the
04596         value of that digit and without limiting the resulting exponent).
04597 
04598         >>> ExtendedContext.logb(Decimal('250'))
04599         Decimal('2')
04600         >>> ExtendedContext.logb(Decimal('2.50'))
04601         Decimal('0')
04602         >>> ExtendedContext.logb(Decimal('0.03'))
04603         Decimal('-2')
04604         >>> ExtendedContext.logb(Decimal('0'))
04605         Decimal('-Infinity')
04606         >>> ExtendedContext.logb(1)
04607         Decimal('0')
04608         >>> ExtendedContext.logb(10)
04609         Decimal('1')
04610         >>> ExtendedContext.logb(100)
04611         Decimal('2')
04612         """
04613         a = _convert_other(a, raiseit=True)
04614         return a.logb(context=self)
04615 
04616     def logical_and(self, a, b):
04617         """Applies the logical operation 'and' between each operand's digits.
04618 
04619         The operands must be both logical numbers.
04620 
04621         >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
04622         Decimal('0')
04623         >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
04624         Decimal('0')
04625         >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
04626         Decimal('0')
04627         >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
04628         Decimal('1')
04629         >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
04630         Decimal('1000')
04631         >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
04632         Decimal('10')
04633         >>> ExtendedContext.logical_and(110, 1101)
04634         Decimal('100')
04635         >>> ExtendedContext.logical_and(Decimal(110), 1101)
04636         Decimal('100')
04637         >>> ExtendedContext.logical_and(110, Decimal(1101))
04638         Decimal('100')
04639         """
04640         a = _convert_other(a, raiseit=True)
04641         return a.logical_and(b, context=self)
04642 
04643     def logical_invert(self, a):
04644         """Invert all the digits in the operand.
04645 
04646         The operand must be a logical number.
04647 
04648         >>> ExtendedContext.logical_invert(Decimal('0'))
04649         Decimal('111111111')
04650         >>> ExtendedContext.logical_invert(Decimal('1'))
04651         Decimal('111111110')
04652         >>> ExtendedContext.logical_invert(Decimal('111111111'))
04653         Decimal('0')
04654         >>> ExtendedContext.logical_invert(Decimal('101010101'))
04655         Decimal('10101010')
04656         >>> ExtendedContext.logical_invert(1101)
04657         Decimal('111110010')
04658         """
04659         a = _convert_other(a, raiseit=True)
04660         return a.logical_invert(context=self)
04661 
04662     def logical_or(self, a, b):
04663         """Applies the logical operation 'or' between each operand's digits.
04664 
04665         The operands must be both logical numbers.
04666 
04667         >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
04668         Decimal('0')
04669         >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
04670         Decimal('1')
04671         >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
04672         Decimal('1')
04673         >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
04674         Decimal('1')
04675         >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
04676         Decimal('1110')
04677         >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
04678         Decimal('1110')
04679         >>> ExtendedContext.logical_or(110, 1101)
04680         Decimal('1111')
04681         >>> ExtendedContext.logical_or(Decimal(110), 1101)
04682         Decimal('1111')
04683         >>> ExtendedContext.logical_or(110, Decimal(1101))
04684         Decimal('1111')
04685         """
04686         a = _convert_other(a, raiseit=True)
04687         return a.logical_or(b, context=self)
04688 
04689     def logical_xor(self, a, b):
04690         """Applies the logical operation 'xor' between each operand's digits.
04691 
04692         The operands must be both logical numbers.
04693 
04694         >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
04695         Decimal('0')
04696         >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
04697         Decimal('1')
04698         >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
04699         Decimal('1')
04700         >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
04701         Decimal('0')
04702         >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
04703         Decimal('110')
04704         >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
04705         Decimal('1101')
04706         >>> ExtendedContext.logical_xor(110, 1101)
04707         Decimal('1011')
04708         >>> ExtendedContext.logical_xor(Decimal(110), 1101)
04709         Decimal('1011')
04710         >>> ExtendedContext.logical_xor(110, Decimal(1101))
04711         Decimal('1011')
04712         """
04713         a = _convert_other(a, raiseit=True)
04714         return a.logical_xor(b, context=self)
04715 
04716     def max(self, a, b):
04717         """max compares two values numerically and returns the maximum.
04718 
04719         If either operand is a NaN then the general rules apply.
04720         Otherwise, the operands are compared as though by the compare
04721         operation.  If they are numerically equal then the left-hand operand
04722         is chosen as the result.  Otherwise the maximum (closer to positive
04723         infinity) of the two operands is chosen as the result.
04724 
04725         >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
04726         Decimal('3')
04727         >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
04728         Decimal('3')
04729         >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
04730         Decimal('1')
04731         >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
04732         Decimal('7')
04733         >>> ExtendedContext.max(1, 2)
04734         Decimal('2')
04735         >>> ExtendedContext.max(Decimal(1), 2)
04736         Decimal('2')
04737         >>> ExtendedContext.max(1, Decimal(2))
04738         Decimal('2')
04739         """
04740         a = _convert_other(a, raiseit=True)
04741         return a.max(b, context=self)
04742 
04743     def max_mag(self, a, b):
04744         """Compares the values numerically with their sign ignored.
04745 
04746         >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
04747         Decimal('7')
04748         >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
04749         Decimal('-10')
04750         >>> ExtendedContext.max_mag(1, -2)
04751         Decimal('-2')
04752         >>> ExtendedContext.max_mag(Decimal(1), -2)
04753         Decimal('-2')
04754         >>> ExtendedContext.max_mag(1, Decimal(-2))
04755         Decimal('-2')
04756         """
04757         a = _convert_other(a, raiseit=True)
04758         return a.max_mag(b, context=self)
04759 
04760     def min(self, a, b):
04761         """min compares two values numerically and returns the minimum.
04762 
04763         If either operand is a NaN then the general rules apply.
04764         Otherwise, the operands are compared as though by the compare
04765         operation.  If they are numerically equal then the left-hand operand
04766         is chosen as the result.  Otherwise the minimum (closer to negative
04767         infinity) of the two operands is chosen as the result.
04768 
04769         >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
04770         Decimal('2')
04771         >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
04772         Decimal('-10')
04773         >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
04774         Decimal('1.0')
04775         >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
04776         Decimal('7')
04777         >>> ExtendedContext.min(1, 2)
04778         Decimal('1')
04779         >>> ExtendedContext.min(Decimal(1), 2)
04780         Decimal('1')
04781         >>> ExtendedContext.min(1, Decimal(29))
04782         Decimal('1')
04783         """
04784         a = _convert_other(a, raiseit=True)
04785         return a.min(b, context=self)
04786 
04787     def min_mag(self, a, b):
04788         """Compares the values numerically with their sign ignored.
04789 
04790         >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2'))
04791         Decimal('-2')
04792         >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN'))
04793         Decimal('-3')
04794         >>> ExtendedContext.min_mag(1, -2)
04795         Decimal('1')
04796         >>> ExtendedContext.min_mag(Decimal(1), -2)
04797         Decimal('1')
04798         >>> ExtendedContext.min_mag(1, Decimal(-2))
04799         Decimal('1')
04800         """
04801         a = _convert_other(a, raiseit=True)
04802         return a.min_mag(b, context=self)
04803 
04804     def minus(self, a):
04805         """Minus corresponds to unary prefix minus in Python.
04806 
04807         The operation is evaluated using the same rules as subtract; the
04808         operation minus(a) is calculated as subtract('0', a) where the '0'
04809         has the same exponent as the operand.
04810 
04811         >>> ExtendedContext.minus(Decimal('1.3'))
04812         Decimal('-1.3')
04813         >>> ExtendedContext.minus(Decimal('-1.3'))
04814         Decimal('1.3')
04815         >>> ExtendedContext.minus(1)
04816         Decimal('-1')
04817         """
04818         a = _convert_other(a, raiseit=True)
04819         return a.__neg__(context=self)
04820 
04821     def multiply(self, a, b):
04822         """multiply multiplies two operands.
04823 
04824         If either operand is a special value then the general rules apply.
04825         Otherwise, the operands are multiplied together
04826         ('long multiplication'), resulting in a number which may be as long as
04827         the sum of the lengths of the two operands.
04828 
04829         >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
04830         Decimal('3.60')
04831         >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
04832         Decimal('21')
04833         >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
04834         Decimal('0.72')
04835         >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
04836         Decimal('-0.0')
04837         >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
04838         Decimal('4.28135971E+11')
04839         >>> ExtendedContext.multiply(7, 7)
04840         Decimal('49')
04841         >>> ExtendedContext.multiply(Decimal(7), 7)
04842         Decimal('49')
04843         >>> ExtendedContext.multiply(7, Decimal(7))
04844         Decimal('49')
04845         """
04846         a = _convert_other(a, raiseit=True)
04847         r = a.__mul__(b, context=self)
04848         if r is NotImplemented:
04849             raise TypeError("Unable to convert %s to Decimal" % b)
04850         else:
04851             return r
04852 
04853     def next_minus(self, a):
04854         """Returns the largest representable number smaller than a.
04855 
04856         >>> c = ExtendedContext.copy()
04857         >>> c.Emin = -999
04858         >>> c.Emax = 999
04859         >>> ExtendedContext.next_minus(Decimal('1'))
04860         Decimal('0.999999999')
04861         >>> c.next_minus(Decimal('1E-1007'))
04862         Decimal('0E-1007')
04863         >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
04864         Decimal('-1.00000004')
04865         >>> c.next_minus(Decimal('Infinity'))
04866         Decimal('9.99999999E+999')
04867         >>> c.next_minus(1)
04868         Decimal('0.999999999')
04869         """
04870         a = _convert_other(a, raiseit=True)
04871         return a.next_minus(context=self)
04872 
04873     def next_plus(self, a):
04874         """Returns the smallest representable number larger than a.
04875 
04876         >>> c = ExtendedContext.copy()
04877         >>> c.Emin = -999
04878         >>> c.Emax = 999
04879         >>> ExtendedContext.next_plus(Decimal('1'))
04880         Decimal('1.00000001')
04881         >>> c.next_plus(Decimal('-1E-1007'))
04882         Decimal('-0E-1007')
04883         >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
04884         Decimal('-1.00000002')
04885         >>> c.next_plus(Decimal('-Infinity'))
04886         Decimal('-9.99999999E+999')
04887         >>> c.next_plus(1)
04888         Decimal('1.00000001')
04889         """
04890         a = _convert_other(a, raiseit=True)
04891         return a.next_plus(context=self)
04892 
04893     def next_toward(self, a, b):
04894         """Returns the number closest to a, in direction towards b.
04895 
04896         The result is the closest representable number from the first
04897         operand (but not the first operand) that is in the direction
04898         towards the second operand, unless the operands have the same
04899         value.
04900 
04901         >>> c = ExtendedContext.copy()
04902         >>> c.Emin = -999
04903         >>> c.Emax = 999
04904         >>> c.next_toward(Decimal('1'), Decimal('2'))
04905         Decimal('1.00000001')
04906         >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
04907         Decimal('-0E-1007')
04908         >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
04909         Decimal('-1.00000002')
04910         >>> c.next_toward(Decimal('1'), Decimal('0'))
04911         Decimal('0.999999999')
04912         >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
04913         Decimal('0E-1007')
04914         >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
04915         Decimal('-1.00000004')
04916         >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
04917         Decimal('-0.00')
04918         >>> c.next_toward(0, 1)
04919         Decimal('1E-1007')
04920         >>> c.next_toward(Decimal(0), 1)
04921         Decimal('1E-1007')
04922         >>> c.next_toward(0, Decimal(1))
04923         Decimal('1E-1007')
04924         """
04925         a = _convert_other(a, raiseit=True)
04926         return a.next_toward(b, context=self)
04927 
04928     def normalize(self, a):
04929         """normalize reduces an operand to its simplest form.
04930 
04931         Essentially a plus operation with all trailing zeros removed from the
04932         result.
04933 
04934         >>> ExtendedContext.normalize(Decimal('2.1'))
04935         Decimal('2.1')
04936         >>> ExtendedContext.normalize(Decimal('-2.0'))
04937         Decimal('-2')
04938         >>> ExtendedContext.normalize(Decimal('1.200'))
04939         Decimal('1.2')
04940         >>> ExtendedContext.normalize(Decimal('-120'))
04941         Decimal('-1.2E+2')
04942         >>> ExtendedContext.normalize(Decimal('120.00'))
04943         Decimal('1.2E+2')
04944         >>> ExtendedContext.normalize(Decimal('0.00'))
04945         Decimal('0')
04946         >>> ExtendedContext.normalize(6)
04947         Decimal('6')
04948         """
04949         a = _convert_other(a, raiseit=True)
04950         return a.normalize(context=self)
04951 
04952     def number_class(self, a):
04953         """Returns an indication of the class of the operand.
04954 
04955         The class is one of the following strings:
04956           -sNaN
04957           -NaN
04958           -Infinity
04959           -Normal
04960           -Subnormal
04961           -Zero
04962           +Zero
04963           +Subnormal
04964           +Normal
04965           +Infinity
04966 
04967         >>> c = Context(ExtendedContext)
04968         >>> c.Emin = -999
04969         >>> c.Emax = 999
04970         >>> c.number_class(Decimal('Infinity'))
04971         '+Infinity'
04972         >>> c.number_class(Decimal('1E-10'))
04973         '+Normal'
04974         >>> c.number_class(Decimal('2.50'))
04975         '+Normal'
04976         >>> c.number_class(Decimal('0.1E-999'))
04977         '+Subnormal'
04978         >>> c.number_class(Decimal('0'))
04979         '+Zero'
04980         >>> c.number_class(Decimal('-0'))
04981         '-Zero'
04982         >>> c.number_class(Decimal('-0.1E-999'))
04983         '-Subnormal'
04984         >>> c.number_class(Decimal('-1E-10'))
04985         '-Normal'
04986         >>> c.number_class(Decimal('-2.50'))
04987         '-Normal'
04988         >>> c.number_class(Decimal('-Infinity'))
04989         '-Infinity'
04990         >>> c.number_class(Decimal('NaN'))
04991         'NaN'
04992         >>> c.number_class(Decimal('-NaN'))
04993         'NaN'
04994         >>> c.number_class(Decimal('sNaN'))
04995         'sNaN'
04996         >>> c.number_class(123)
04997         '+Normal'
04998         """
04999         a = _convert_other(a, raiseit=True)
05000         return a.number_class(context=self)
05001 
05002     def plus(self, a):
05003         """Plus corresponds to unary prefix plus in Python.
05004 
05005         The operation is evaluated using the same rules as add; the
05006         operation plus(a) is calculated as add('0', a) where the '0'
05007         has the same exponent as the operand.
05008 
05009         >>> ExtendedContext.plus(Decimal('1.3'))
05010         Decimal('1.3')
05011         >>> ExtendedContext.plus(Decimal('-1.3'))
05012         Decimal('-1.3')
05013         >>> ExtendedContext.plus(-1)
05014         Decimal('-1')
05015         """
05016         a = _convert_other(a, raiseit=True)
05017         return a.__pos__(context=self)
05018 
05019     def power(self, a, b, modulo=None):
05020         """Raises a to the power of b, to modulo if given.
05021 
05022         With two arguments, compute a**b.  If a is negative then b
05023         must be integral.  The result will be inexact unless b is
05024         integral and the result is finite and can be expressed exactly
05025         in 'precision' digits.
05026 
05027         With three arguments, compute (a**b) % modulo.  For the
05028         three argument form, the following restrictions on the
05029         arguments hold:
05030 
05031          - all three arguments must be integral
05032          - b must be nonnegative
05033          - at least one of a or b must be nonzero
05034          - modulo must be nonzero and have at most 'precision' digits
05035 
05036         The result of pow(a, b, modulo) is identical to the result
05037         that would be obtained by computing (a**b) % modulo with
05038         unbounded precision, but is computed more efficiently.  It is
05039         always exact.
05040 
05041         >>> c = ExtendedContext.copy()
05042         >>> c.Emin = -999
05043         >>> c.Emax = 999
05044         >>> c.power(Decimal('2'), Decimal('3'))
05045         Decimal('8')
05046         >>> c.power(Decimal('-2'), Decimal('3'))
05047         Decimal('-8')
05048         >>> c.power(Decimal('2'), Decimal('-3'))
05049         Decimal('0.125')
05050         >>> c.power(Decimal('1.7'), Decimal('8'))
05051         Decimal('69.7575744')
05052         >>> c.power(Decimal('10'), Decimal('0.301029996'))
05053         Decimal('2.00000000')
05054         >>> c.power(Decimal('Infinity'), Decimal('-1'))
05055         Decimal('0')
05056         >>> c.power(Decimal('Infinity'), Decimal('0'))
05057         Decimal('1')
05058         >>> c.power(Decimal('Infinity'), Decimal('1'))
05059         Decimal('Infinity')
05060         >>> c.power(Decimal('-Infinity'), Decimal('-1'))
05061         Decimal('-0')
05062         >>> c.power(Decimal('-Infinity'), Decimal('0'))
05063         Decimal('1')
05064         >>> c.power(Decimal('-Infinity'), Decimal('1'))
05065         Decimal('-Infinity')
05066         >>> c.power(Decimal('-Infinity'), Decimal('2'))
05067         Decimal('Infinity')
05068         >>> c.power(Decimal('0'), Decimal('0'))
05069         Decimal('NaN')
05070 
05071         >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
05072         Decimal('11')
05073         >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
05074         Decimal('-11')
05075         >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
05076         Decimal('1')
05077         >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
05078         Decimal('11')
05079         >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
05080         Decimal('11729830')
05081         >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
05082         Decimal('-0')
05083         >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
05084         Decimal('1')
05085         >>> ExtendedContext.power(7, 7)
05086         Decimal('823543')
05087         >>> ExtendedContext.power(Decimal(7), 7)
05088         Decimal('823543')
05089         >>> ExtendedContext.power(7, Decimal(7), 2)
05090         Decimal('1')
05091         """
05092         a = _convert_other(a, raiseit=True)
05093         r = a.__pow__(b, modulo, context=self)
05094         if r is NotImplemented:
05095             raise TypeError("Unable to convert %s to Decimal" % b)
05096         else:
05097             return r
05098 
05099     def quantize(self, a, b):
05100         """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
05101 
05102         The coefficient of the result is derived from that of the left-hand
05103         operand.  It may be rounded using the current rounding setting (if the
05104         exponent is being increased), multiplied by a positive power of ten (if
05105         the exponent is being decreased), or is unchanged (if the exponent is
05106         already equal to that of the right-hand operand).
05107 
05108         Unlike other operations, if the length of the coefficient after the
05109         quantize operation would be greater than precision then an Invalid
05110         operation condition is raised.  This guarantees that, unless there is
05111         an error condition, the exponent of the result of a quantize is always
05112         equal to that of the right-hand operand.
05113 
05114         Also unlike other operations, quantize will never raise Underflow, even
05115         if the result is subnormal and inexact.
05116 
05117         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
05118         Decimal('2.170')
05119         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
05120         Decimal('2.17')
05121         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
05122         Decimal('2.2')
05123         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
05124         Decimal('2')
05125         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
05126         Decimal('0E+1')
05127         >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
05128         Decimal('-Infinity')
05129         >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
05130         Decimal('NaN')
05131         >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
05132         Decimal('-0')
05133         >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
05134         Decimal('-0E+5')
05135         >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
05136         Decimal('NaN')
05137         >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
05138         Decimal('NaN')
05139         >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
05140         Decimal('217.0')
05141         >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
05142         Decimal('217')
05143         >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
05144         Decimal('2.2E+2')
05145         >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
05146         Decimal('2E+2')
05147         >>> ExtendedContext.quantize(1, 2)
05148         Decimal('1')
05149         >>> ExtendedContext.quantize(Decimal(1), 2)
05150         Decimal('1')
05151         >>> ExtendedContext.quantize(1, Decimal(2))
05152         Decimal('1')
05153         """
05154         a = _convert_other(a, raiseit=True)
05155         return a.quantize(b, context=self)
05156 
05157     def radix(self):
05158         """Just returns 10, as this is Decimal, :)
05159 
05160         >>> ExtendedContext.radix()
05161         Decimal('10')
05162         """
05163         return Decimal(10)
05164 
05165     def remainder(self, a, b):
05166         """Returns the remainder from integer division.
05167 
05168         The result is the residue of the dividend after the operation of
05169         calculating integer division as described for divide-integer, rounded
05170         to precision digits if necessary.  The sign of the result, if
05171         non-zero, is the same as that of the original dividend.
05172 
05173         This operation will fail under the same conditions as integer division
05174         (that is, if integer division on the same two operands would fail, the
05175         remainder cannot be calculated).
05176 
05177         >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
05178         Decimal('2.1')
05179         >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
05180         Decimal('1')
05181         >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
05182         Decimal('-1')
05183         >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
05184         Decimal('0.2')
05185         >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
05186         Decimal('0.1')
05187         >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
05188         Decimal('1.0')
05189         >>> ExtendedContext.remainder(22, 6)
05190         Decimal('4')
05191         >>> ExtendedContext.remainder(Decimal(22), 6)
05192         Decimal('4')
05193         >>> ExtendedContext.remainder(22, Decimal(6))
05194         Decimal('4')
05195         """
05196         a = _convert_other(a, raiseit=True)
05197         r = a.__mod__(b, context=self)
05198         if r is NotImplemented:
05199             raise TypeError("Unable to convert %s to Decimal" % b)
05200         else:
05201             return r
05202 
05203     def remainder_near(self, a, b):
05204         """Returns to be "a - b * n", where n is the integer nearest the exact
05205         value of "x / b" (if two integers are equally near then the even one
05206         is chosen).  If the result is equal to 0 then its sign will be the
05207         sign of a.
05208 
05209         This operation will fail under the same conditions as integer division
05210         (that is, if integer division on the same two operands would fail, the
05211         remainder cannot be calculated).
05212 
05213         >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
05214         Decimal('-0.9')
05215         >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
05216         Decimal('-2')
05217         >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
05218         Decimal('1')
05219         >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
05220         Decimal('-1')
05221         >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
05222         Decimal('0.2')
05223         >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
05224         Decimal('0.1')
05225         >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
05226         Decimal('-0.3')
05227         >>> ExtendedContext.remainder_near(3, 11)
05228         Decimal('3')
05229         >>> ExtendedContext.remainder_near(Decimal(3), 11)
05230         Decimal('3')
05231         >>> ExtendedContext.remainder_near(3, Decimal(11))
05232         Decimal('3')
05233         """
05234         a = _convert_other(a, raiseit=True)
05235         return a.remainder_near(b, context=self)
05236 
05237     def rotate(self, a, b):
05238         """Returns a rotated copy of a, b times.
05239 
05240         The coefficient of the result is a rotated copy of the digits in
05241         the coefficient of the first operand.  The number of places of
05242         rotation is taken from the absolute value of the second operand,
05243         with the rotation being to the left if the second operand is
05244         positive or to the right otherwise.
05245 
05246         >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
05247         Decimal('400000003')
05248         >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
05249         Decimal('12')
05250         >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
05251         Decimal('891234567')
05252         >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
05253         Decimal('123456789')
05254         >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
05255         Decimal('345678912')
05256         >>> ExtendedContext.rotate(1333333, 1)
05257         Decimal('13333330')
05258         >>> ExtendedContext.rotate(Decimal(1333333), 1)
05259         Decimal('13333330')
05260         >>> ExtendedContext.rotate(1333333, Decimal(1))
05261         Decimal('13333330')
05262         """
05263         a = _convert_other(a, raiseit=True)
05264         return a.rotate(b, context=self)
05265 
05266     def same_quantum(self, a, b):
05267         """Returns True if the two operands have the same exponent.
05268 
05269         The result is never affected by either the sign or the coefficient of
05270         either operand.
05271 
05272         >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
05273         False
05274         >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
05275         True
05276         >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
05277         False
05278         >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
05279         True
05280         >>> ExtendedContext.same_quantum(10000, -1)
05281         True
05282         >>> ExtendedContext.same_quantum(Decimal(10000), -1)
05283         True
05284         >>> ExtendedContext.same_quantum(10000, Decimal(-1))
05285         True
05286         """
05287         a = _convert_other(a, raiseit=True)
05288         return a.same_quantum(b)
05289 
05290     def scaleb (self, a, b):
05291         """Returns the first operand after adding the second value its exp.
05292 
05293         >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
05294         Decimal('0.0750')
05295         >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
05296         Decimal('7.50')
05297         >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
05298         Decimal('7.50E+3')
05299         >>> ExtendedContext.scaleb(1, 4)
05300         Decimal('1E+4')
05301         >>> ExtendedContext.scaleb(Decimal(1), 4)
05302         Decimal('1E+4')
05303         >>> ExtendedContext.scaleb(1, Decimal(4))
05304         Decimal('1E+4')
05305         """
05306         a = _convert_other(a, raiseit=True)
05307         return a.scaleb(b, context=self)
05308 
05309     def shift(self, a, b):
05310         """Returns a shifted copy of a, b times.
05311 
05312         The coefficient of the result is a shifted copy of the digits
05313         in the coefficient of the first operand.  The number of places
05314         to shift is taken from the absolute value of the second operand,
05315         with the shift being to the left if the second operand is
05316         positive or to the right otherwise.  Digits shifted into the
05317         coefficient are zeros.
05318 
05319         >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
05320         Decimal('400000000')
05321         >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
05322         Decimal('0')
05323         >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
05324         Decimal('1234567')
05325         >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
05326         Decimal('123456789')
05327         >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
05328         Decimal('345678900')
05329         >>> ExtendedContext.shift(88888888, 2)
05330         Decimal('888888800')
05331         >>> ExtendedContext.shift(Decimal(88888888), 2)
05332         Decimal('888888800')
05333         >>> ExtendedContext.shift(88888888, Decimal(2))
05334         Decimal('888888800')
05335         """
05336         a = _convert_other(a, raiseit=True)
05337         return a.shift(b, context=self)
05338 
05339     def sqrt(self, a):
05340         """Square root of a non-negative number to context precision.
05341 
05342         If the result must be inexact, it is rounded using the round-half-even
05343         algorithm.
05344 
05345         >>> ExtendedContext.sqrt(Decimal('0'))
05346         Decimal('0')
05347         >>> ExtendedContext.sqrt(Decimal('-0'))
05348         Decimal('-0')
05349         >>> ExtendedContext.sqrt(Decimal('0.39'))
05350         Decimal('0.624499800')
05351         >>> ExtendedContext.sqrt(Decimal('100'))
05352         Decimal('10')
05353         >>> ExtendedContext.sqrt(Decimal('1'))
05354         Decimal('1')
05355         >>> ExtendedContext.sqrt(Decimal('1.0'))
05356         Decimal('1.0')
05357         >>> ExtendedContext.sqrt(Decimal('1.00'))
05358         Decimal('1.0')
05359         >>> ExtendedContext.sqrt(Decimal('7'))
05360         Decimal('2.64575131')
05361         >>> ExtendedContext.sqrt(Decimal('10'))
05362         Decimal('3.16227766')
05363         >>> ExtendedContext.sqrt(2)
05364         Decimal('1.41421356')
05365         >>> ExtendedContext.prec
05366         9
05367         """
05368         a = _convert_other(a, raiseit=True)
05369         return a.sqrt(context=self)
05370 
05371     def subtract(self, a, b):
05372         """Return the difference between the two operands.
05373 
05374         >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
05375         Decimal('0.23')
05376         >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
05377         Decimal('0.00')
05378         >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
05379         Decimal('-0.77')
05380         >>> ExtendedContext.subtract(8, 5)
05381         Decimal('3')
05382         >>> ExtendedContext.subtract(Decimal(8), 5)
05383         Decimal('3')
05384         >>> ExtendedContext.subtract(8, Decimal(5))
05385         Decimal('3')
05386         """
05387         a = _convert_other(a, raiseit=True)
05388         r = a.__sub__(b, context=self)
05389         if r is NotImplemented:
05390             raise TypeError("Unable to convert %s to Decimal" % b)
05391         else:
05392             return r
05393 
05394     def to_eng_string(self, a):
05395         """Converts a number to a string, using scientific notation.
05396 
05397         The operation is not affected by the context.
05398         """
05399         a = _convert_other(a, raiseit=True)
05400         return a.to_eng_string(context=self)
05401 
05402     def to_sci_string(self, a):
05403         """Converts a number to a string, using scientific notation.
05404 
05405         The operation is not affected by the context.
05406         """
05407         a = _convert_other(a, raiseit=True)
05408         return a.__str__(context=self)
05409 
05410     def to_integral_exact(self, a):
05411         """Rounds to an integer.
05412 
05413         When the operand has a negative exponent, the result is the same
05414         as using the quantize() operation using the given operand as the
05415         left-hand-operand, 1E+0 as the right-hand-operand, and the precision
05416         of the operand as the precision setting; Inexact and Rounded flags
05417         are allowed in this operation.  The rounding mode is taken from the
05418         context.
05419 
05420         >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
05421         Decimal('2')
05422         >>> ExtendedContext.to_integral_exact(Decimal('100'))
05423         Decimal('100')
05424         >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
05425         Decimal('100')
05426         >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
05427         Decimal('102')
05428         >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
05429         Decimal('-102')
05430         >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
05431         Decimal('1.0E+6')
05432         >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
05433         Decimal('7.89E+77')
05434         >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
05435         Decimal('-Infinity')
05436         """
05437         a = _convert_other(a, raiseit=True)
05438         return a.to_integral_exact(context=self)
05439 
05440     def to_integral_value(self, a):
05441         """Rounds to an integer.
05442 
05443         When the operand has a negative exponent, the result is the same
05444         as using the quantize() operation using the given operand as the
05445         left-hand-operand, 1E+0 as the right-hand-operand, and the precision
05446         of the operand as the precision setting, except that no flags will
05447         be set.  The rounding mode is taken from the context.
05448 
05449         >>> ExtendedContext.to_integral_value(Decimal('2.1'))
05450         Decimal('2')
05451         >>> ExtendedContext.to_integral_value(Decimal('100'))
05452         Decimal('100')
05453         >>> ExtendedContext.to_integral_value(Decimal('100.0'))
05454         Decimal('100')
05455         >>> ExtendedContext.to_integral_value(Decimal('101.5'))
05456         Decimal('102')
05457         >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
05458         Decimal('-102')
05459         >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
05460         Decimal('1.0E+6')
05461         >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
05462         Decimal('7.89E+77')
05463         >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
05464         Decimal('-Infinity')
05465         """
05466         a = _convert_other(a, raiseit=True)
05467         return a.to_integral_value(context=self)
05468 
05469     # the method name changed, but we provide also the old one, for compatibility
05470     to_integral = to_integral_value
05471 
05472 class _WorkRep(object):
05473     __slots__ = ('sign','int','exp')
05474     # sign: 0 or 1
05475     # int:  int
05476     # exp:  None, int, or string
05477 
05478     def __init__(self, value=None):
05479         if value is None:
05480             self.sign = None
05481             self.int = 0
05482             self.exp = None
05483         elif isinstance(value, Decimal):
05484             self.sign = value._sign
05485             self.int = int(value._int)
05486             self.exp = value._exp
05487         else:
05488             # assert isinstance(value, tuple)
05489             self.sign = value[0]
05490             self.int = value[1]
05491             self.exp = value[2]
05492 
05493     def __repr__(self):
05494         return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
05495 
05496     __str__ = __repr__
05497 
05498 
05499 
05500 def _normalize(op1, op2, prec = 0):
05501     """Normalizes op1, op2 to have the same exp and length of coefficient.
05502 
05503     Done during addition.
05504     """
05505     if op1.exp < op2.exp:
05506         tmp = op2
05507         other = op1
05508     else:
05509         tmp = op1
05510         other = op2
05511 
05512     # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
05513     # Then adding 10**exp to tmp has the same effect (after rounding)
05514     # as adding any positive quantity smaller than 10**exp; similarly
05515     # for subtraction.  So if other is smaller than 10**exp we replace
05516     # it with 10**exp.  This avoids tmp.exp - other.exp getting too large.
05517     tmp_len = len(str(tmp.int))
05518     other_len = len(str(other.int))
05519     exp = tmp.exp + min(-1, tmp_len - prec - 2)
05520     if other_len + other.exp - 1 < exp:
05521         other.int = 1
05522         other.exp = exp
05523 
05524     tmp.int *= 10 ** (tmp.exp - other.exp)
05525     tmp.exp = other.exp
05526     return op1, op2
05527 
05528 ##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
05529 
05530 _nbits = int.bit_length
05531 
05532 def _sqrt_nearest(n, a):
05533     """Closest integer to the square root of the positive integer n.  a is
05534     an initial approximation to the square root.  Any positive integer
05535     will do for a, but the closer a is to the square root of n the
05536     faster convergence will be.
05537 
05538     """
05539     if n <= 0 or a <= 0:
05540         raise ValueError("Both arguments to _sqrt_nearest should be positive.")
05541 
05542     b=0
05543     while a != b:
05544         b, a = a, a--n//a>>1
05545     return a
05546 
05547 def _rshift_nearest(x, shift):
05548     """Given an integer x and a nonnegative integer shift, return closest
05549     integer to x / 2**shift; use round-to-even in case of a tie.
05550 
05551     """
05552     b, q = 1 << shift, x >> shift
05553     return q + (2*(x & (b-1)) + (q&1) > b)
05554 
05555 def _div_nearest(a, b):
05556     """Closest integer to a/b, a and b positive integers; rounds to even
05557     in the case of a tie.
05558 
05559     """
05560     q, r = divmod(a, b)
05561     return q + (2*r + (q&1) > b)
05562 
05563 def _ilog(x, M, L = 8):
05564     """Integer approximation to M*log(x/M), with absolute error boundable
05565     in terms only of x/M.
05566 
05567     Given positive integers x and M, return an integer approximation to
05568     M * log(x/M).  For L = 8 and 0.1 <= x/M <= 10 the difference
05569     between the approximation and the exact result is at most 22.  For
05570     L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15.  In
05571     both cases these are upper bounds on the error; it will usually be
05572     much smaller."""
05573 
05574     # The basic algorithm is the following: let log1p be the function
05575     # log1p(x) = log(1+x).  Then log(x/M) = log1p((x-M)/M).  We use
05576     # the reduction
05577     #
05578     #    log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
05579     #
05580     # repeatedly until the argument to log1p is small (< 2**-L in
05581     # absolute value).  For small y we can use the Taylor series
05582     # expansion
05583     #
05584     #    log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
05585     #
05586     # truncating at T such that y**T is small enough.  The whole
05587     # computation is carried out in a form of fixed-point arithmetic,
05588     # with a real number z being represented by an integer
05589     # approximation to z*M.  To avoid loss of precision, the y below
05590     # is actually an integer approximation to 2**R*y*M, where R is the
05591     # number of reductions performed so far.
05592 
05593     y = x-M
05594     # argument reduction; R = number of reductions performed
05595     R = 0
05596     while (R <= L and abs(y) << L-R >= M or
05597            R > L and abs(y) >> R-L >= M):
05598         y = _div_nearest((M*y) << 1,
05599                          M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
05600         R += 1
05601 
05602     # Taylor series with T terms
05603     T = -int(-10*len(str(M))//(3*L))
05604     yshift = _rshift_nearest(y, R)
05605     w = _div_nearest(M, T)
05606     for k in range(T-1, 0, -1):
05607         w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
05608 
05609     return _div_nearest(w*y, M)
05610 
05611 def _dlog10(c, e, p):
05612     """Given integers c, e and p with c > 0, p >= 0, compute an integer
05613     approximation to 10**p * log10(c*10**e), with an absolute error of
05614     at most 1.  Assumes that c*10**e is not exactly 1."""
05615 
05616     # increase precision by 2; compensate for this by dividing
05617     # final result by 100
05618     p += 2
05619 
05620     # write c*10**e as d*10**f with either:
05621     #   f >= 0 and 1 <= d <= 10, or
05622     #   f <= 0 and 0.1 <= d <= 1.
05623     # Thus for c*10**e close to 1, f = 0
05624     l = len(str(c))
05625     f = e+l - (e+l >= 1)
05626 
05627     if p > 0:
05628         M = 10**p
05629         k = e+p-f
05630         if k >= 0:
05631             c *= 10**k
05632         else:
05633             c = _div_nearest(c, 10**-k)
05634 
05635         log_d = _ilog(c, M) # error < 5 + 22 = 27
05636         log_10 = _log10_digits(p) # error < 1
05637         log_d = _div_nearest(log_d*M, log_10)
05638         log_tenpower = f*M # exact
05639     else:
05640         log_d = 0  # error < 2.31
05641         log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
05642 
05643     return _div_nearest(log_tenpower+log_d, 100)
05644 
05645 def _dlog(c, e, p):
05646     """Given integers c, e and p with c > 0, compute an integer
05647     approximation to 10**p * log(c*10**e), with an absolute error of
05648     at most 1.  Assumes that c*10**e is not exactly 1."""
05649 
05650     # Increase precision by 2. The precision increase is compensated
05651     # for at the end with a division by 100.
05652     p += 2
05653 
05654     # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
05655     # or f <= 0 and 0.1 <= d <= 1.  Then we can compute 10**p * log(c*10**e)
05656     # as 10**p * log(d) + 10**p*f * log(10).
05657     l = len(str(c))
05658     f = e+l - (e+l >= 1)
05659 
05660     # compute approximation to 10**p*log(d), with error < 27
05661     if p > 0:
05662         k = e+p-f
05663         if k >= 0:
05664             c *= 10**k
05665         else:
05666             c = _div_nearest(c, 10**-k)  # error of <= 0.5 in c
05667 
05668         # _ilog magnifies existing error in c by a factor of at most 10
05669         log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
05670     else:
05671         # p <= 0: just approximate the whole thing by 0; error < 2.31
05672         log_d = 0
05673 
05674     # compute approximation to f*10**p*log(10), with error < 11.
05675     if f:
05676         extra = len(str(abs(f)))-1
05677         if p + extra >= 0:
05678             # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
05679             # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
05680             f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
05681         else:
05682             f_log_ten = 0
05683     else:
05684         f_log_ten = 0
05685 
05686     # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
05687     return _div_nearest(f_log_ten + log_d, 100)
05688 
05689 class _Log10Memoize(object):
05690     """Class to compute, store, and allow retrieval of, digits of the
05691     constant log(10) = 2.302585....  This constant is needed by
05692     Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
05693     def __init__(self):
05694         self.digits = "23025850929940456840179914546843642076011014886"
05695 
05696     def getdigits(self, p):
05697         """Given an integer p >= 0, return floor(10**p)*log(10).
05698 
05699         For example, self.getdigits(3) returns 2302.
05700         """
05701         # digits are stored as a string, for quick conversion to
05702         # integer in the case that we've already computed enough
05703         # digits; the stored digits should always be correct
05704         # (truncated, not rounded to nearest).
05705         if p < 0:
05706             raise ValueError("p should be nonnegative")
05707 
05708         if p >= len(self.digits):
05709             # compute p+3, p+6, p+9, ... digits; continue until at
05710             # least one of the extra digits is nonzero
05711             extra = 3
05712             while True:
05713                 # compute p+extra digits, correct to within 1ulp
05714                 M = 10**(p+extra+2)
05715                 digits = str(_div_nearest(_ilog(10*M, M), 100))
05716                 if digits[-extra:] != '0'*extra:
05717                     break
05718                 extra += 3
05719             # keep all reliable digits so far; remove trailing zeros
05720             # and next nonzero digit
05721             self.digits = digits.rstrip('0')[:-1]
05722         return int(self.digits[:p+1])
05723 
05724 _log10_digits = _Log10Memoize().getdigits
05725 
05726 def _iexp(x, M, L=8):
05727     """Given integers x and M, M > 0, such that x/M is small in absolute
05728     value, compute an integer approximation to M*exp(x/M).  For 0 <=
05729     x/M <= 2.4, the absolute error in the result is bounded by 60 (and
05730     is usually much smaller)."""
05731 
05732     # Algorithm: to compute exp(z) for a real number z, first divide z
05733     # by a suitable power R of 2 so that |z/2**R| < 2**-L.  Then
05734     # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
05735     # series
05736     #
05737     #     expm1(x) = x + x**2/2! + x**3/3! + ...
05738     #
05739     # Now use the identity
05740     #
05741     #     expm1(2x) = expm1(x)*(expm1(x)+2)
05742     #
05743     # R times to compute the sequence expm1(z/2**R),
05744     # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
05745 
05746     # Find R such that x/2**R/M <= 2**-L
05747     R = _nbits((x<<L)//M)
05748 
05749     # Taylor series.  (2**L)**T > M
05750     T = -int(-10*len(str(M))//(3*L))
05751     y = _div_nearest(x, T)
05752     Mshift = M<<R
05753     for i in range(T-1, 0, -1):
05754         y = _div_nearest(x*(Mshift + y), Mshift * i)
05755 
05756     # Expansion
05757     for k in range(R-1, -1, -1):
05758         Mshift = M<<(k+2)
05759         y = _div_nearest(y*(y+Mshift), Mshift)
05760 
05761     return M+y
05762 
05763 def _dexp(c, e, p):
05764     """Compute an approximation to exp(c*10**e), with p decimal places of
05765     precision.
05766 
05767     Returns integers d, f such that:
05768 
05769       10**(p-1) <= d <= 10**p, and
05770       (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
05771 
05772     In other words, d*10**f is an approximation to exp(c*10**e) with p
05773     digits of precision, and with an error in d of at most 1.  This is
05774     almost, but not quite, the same as the error being < 1ulp: when d
05775     = 10**(p-1) the error could be up to 10 ulp."""
05776 
05777     # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
05778     p += 2
05779 
05780     # compute log(10) with extra precision = adjusted exponent of c*10**e
05781     extra = max(0, e + len(str(c)) - 1)
05782     q = p + extra
05783 
05784     # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
05785     # rounding down
05786     shift = e+q
05787     if shift >= 0:
05788         cshift = c*10**shift
05789     else:
05790         cshift = c//10**-shift
05791     quot, rem = divmod(cshift, _log10_digits(q))
05792 
05793     # reduce remainder back to original precision
05794     rem = _div_nearest(rem, 10**extra)
05795 
05796     # error in result of _iexp < 120;  error after division < 0.62
05797     return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
05798 
05799 def _dpower(xc, xe, yc, ye, p):
05800     """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
05801     y = yc*10**ye, compute x**y.  Returns a pair of integers (c, e) such that:
05802 
05803       10**(p-1) <= c <= 10**p, and
05804       (c-1)*10**e < x**y < (c+1)*10**e
05805 
05806     in other words, c*10**e is an approximation to x**y with p digits
05807     of precision, and with an error in c of at most 1.  (This is
05808     almost, but not quite, the same as the error being < 1ulp: when c
05809     == 10**(p-1) we can only guarantee error < 10ulp.)
05810 
05811     We assume that: x is positive and not equal to 1, and y is nonzero.
05812     """
05813 
05814     # Find b such that 10**(b-1) <= |y| <= 10**b
05815     b = len(str(abs(yc))) + ye
05816 
05817     # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
05818     lxc = _dlog(xc, xe, p+b+1)
05819 
05820     # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
05821     shift = ye-b
05822     if shift >= 0:
05823         pc = lxc*yc*10**shift
05824     else:
05825         pc = _div_nearest(lxc*yc, 10**-shift)
05826 
05827     if pc == 0:
05828         # we prefer a result that isn't exactly 1; this makes it
05829         # easier to compute a correctly rounded result in __pow__
05830         if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
05831             coeff, exp = 10**(p-1)+1, 1-p
05832         else:
05833             coeff, exp = 10**p-1, -p
05834     else:
05835         coeff, exp = _dexp(pc, -(p+1), p+1)
05836         coeff = _div_nearest(coeff, 10)
05837         exp += 1
05838 
05839     return coeff, exp
05840 
05841 def _log10_lb(c, correction = {
05842         '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
05843         '6': 23, '7': 16, '8': 10, '9': 5}):
05844     """Compute a lower bound for 100*log10(c) for a positive integer c."""
05845     if c <= 0:
05846         raise ValueError("The argument to _log10_lb should be nonnegative.")
05847     str_c = str(c)
05848     return 100*len(str_c) - correction[str_c[0]]
05849 
05850 ##### Helper Functions ####################################################
05851 
05852 def _convert_other(other, raiseit=False, allow_float=False):
05853     """Convert other to Decimal.
05854 
05855     Verifies that it's ok to use in an implicit construction.
05856     If allow_float is true, allow conversion from float;  this
05857     is used in the comparison methods (__eq__ and friends).
05858 
05859     """
05860     if isinstance(other, Decimal):
05861         return other
05862     if isinstance(other, int):
05863         return Decimal(other)
05864     if allow_float and isinstance(other, float):
05865         return Decimal.from_float(other)
05866 
05867     if raiseit:
05868         raise TypeError("Unable to convert %s to Decimal" % other)
05869     return NotImplemented
05870 
05871 def _convert_for_comparison(self, other, equality_op=False):
05872     """Given a Decimal instance self and a Python object other, return
05873     a pair (s, o) of Decimal instances such that "s op o" is
05874     equivalent to "self op other" for any of the 6 comparison
05875     operators "op".
05876 
05877     """
05878     if isinstance(other, Decimal):
05879         return self, other
05880 
05881     # Comparison with a Rational instance (also includes integers):
05882     # self op n/d <=> self*d op n (for n and d integers, d positive).
05883     # A NaN or infinity can be left unchanged without affecting the
05884     # comparison result.
05885     if isinstance(other, _numbers.Rational):
05886         if not self._is_special:
05887             self = _dec_from_triple(self._sign,
05888                                     str(int(self._int) * other.denominator),
05889                                     self._exp)
05890         return self, Decimal(other.numerator)
05891 
05892     # Comparisons with float and complex types.  == and != comparisons
05893     # with complex numbers should succeed, returning either True or False
05894     # as appropriate.  Other comparisons return NotImplemented.
05895     if equality_op and isinstance(other, _numbers.Complex) and other.imag == 0:
05896         other = other.real
05897     if isinstance(other, float):
05898         return self, Decimal.from_float(other)
05899     return NotImplemented, NotImplemented
05900 
05901 
05902 ##### Setup Specific Contexts ############################################
05903 
05904 # The default context prototype used by Context()
05905 # Is mutable, so that new contexts can have different default values
05906 
05907 DefaultContext = Context(
05908         prec=28, rounding=ROUND_HALF_EVEN,
05909         traps=[DivisionByZero, Overflow, InvalidOperation],
05910         flags=[],
05911         Emax=999999999,
05912         Emin=-999999999,
05913         capitals=1,
05914         clamp=0
05915 )
05916 
05917 # Pre-made alternate contexts offered by the specification
05918 # Don't change these; the user should be able to select these
05919 # contexts and be able to reproduce results from other implementations
05920 # of the spec.
05921 
05922 BasicContext = Context(
05923         prec=9, rounding=ROUND_HALF_UP,
05924         traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
05925         flags=[],
05926 )
05927 
05928 ExtendedContext = Context(
05929         prec=9, rounding=ROUND_HALF_EVEN,
05930         traps=[],
05931         flags=[],
05932 )
05933 
05934 
05935 ##### crud for parsing strings #############################################
05936 #
05937 # Regular expression used for parsing numeric strings.  Additional
05938 # comments:
05939 #
05940 # 1. Uncomment the two '\s*' lines to allow leading and/or trailing
05941 # whitespace.  But note that the specification disallows whitespace in
05942 # a numeric string.
05943 #
05944 # 2. For finite numbers (not infinities and NaNs) the body of the
05945 # number between the optional sign and the optional exponent must have
05946 # at least one decimal digit, possibly after the decimal point.  The
05947 # lookahead expression '(?=\d|\.\d)' checks this.
05948 
05949 import re
05950 _parser = re.compile(r"""        # A numeric string consists of:
05951 #    \s*
05952     (?P<sign>[-+])?              # an optional sign, followed by either...
05953     (
05954         (?=\d|\.\d)              # ...a number (with at least one digit)
05955         (?P<int>\d*)             # having a (possibly empty) integer part
05956         (\.(?P<frac>\d*))?       # followed by an optional fractional part
05957         (E(?P<exp>[-+]?\d+))?    # followed by an optional exponent, or...
05958     |
05959         Inf(inity)?              # ...an infinity, or...
05960     |
05961         (?P<signal>s)?           # ...an (optionally signaling)
05962         NaN                      # NaN
05963         (?P<diag>\d*)            # with (possibly empty) diagnostic info.
05964     )
05965 #    \s*
05966     \Z
05967 """, re.VERBOSE | re.IGNORECASE).match
05968 
05969 _all_zeros = re.compile('0*$').match
05970 _exact_half = re.compile('50*$').match
05971 
05972 ##### PEP3101 support functions ##############################################
05973 # The functions in this section have little to do with the Decimal
05974 # class, and could potentially be reused or adapted for other pure
05975 # Python numeric classes that want to implement __format__
05976 #
05977 # A format specifier for Decimal looks like:
05978 #
05979 #   [[fill]align][sign][#][0][minimumwidth][,][.precision][type]
05980 
05981 _parse_format_specifier_regex = re.compile(r"""\A
05982 (?:
05983    (?P<fill>.)?
05984    (?P<align>[<>=^])
05985 )?
05986 (?P<sign>[-+ ])?
05987 (?P<alt>\#)?
05988 (?P<zeropad>0)?
05989 (?P<minimumwidth>(?!0)\d+)?
05990 (?P<thousands_sep>,)?
05991 (?:\.(?P<precision>0|(?!0)\d+))?
05992 (?P<type>[eEfFgGn%])?
05993 \Z
05994 """, re.VERBOSE)
05995 
05996 del re
05997 
05998 # The locale module is only needed for the 'n' format specifier.  The
05999 # rest of the PEP 3101 code functions quite happily without it, so we
06000 # don't care too much if locale isn't present.
06001 try:
06002     import locale as _locale
06003 except ImportError:
06004     pass
06005 
06006 def _parse_format_specifier(format_spec, _localeconv=None):
06007     """Parse and validate a format specifier.
06008 
06009     Turns a standard numeric format specifier into a dict, with the
06010     following entries:
06011 
06012       fill: fill character to pad field to minimum width
06013       align: alignment type, either '<', '>', '=' or '^'
06014       sign: either '+', '-' or ' '
06015       minimumwidth: nonnegative integer giving minimum width
06016       zeropad: boolean, indicating whether to pad with zeros
06017       thousands_sep: string to use as thousands separator, or ''
06018       grouping: grouping for thousands separators, in format
06019         used by localeconv
06020       decimal_point: string to use for decimal point
06021       precision: nonnegative integer giving precision, or None
06022       type: one of the characters 'eEfFgG%', or None
06023 
06024     """
06025     m = _parse_format_specifier_regex.match(format_spec)
06026     if m is None:
06027         raise ValueError("Invalid format specifier: " + format_spec)
06028 
06029     # get the dictionary
06030     format_dict = m.groupdict()
06031 
06032     # zeropad; defaults for fill and alignment.  If zero padding
06033     # is requested, the fill and align fields should be absent.
06034     fill = format_dict['fill']
06035     align = format_dict['align']
06036     format_dict['zeropad'] = (format_dict['zeropad'] is not None)
06037     if format_dict['zeropad']:
06038         if fill is not None:
06039             raise ValueError("Fill character conflicts with '0'"
06040                              " in format specifier: " + format_spec)
06041         if align is not None:
06042             raise ValueError("Alignment conflicts with '0' in "
06043                              "format specifier: " + format_spec)
06044     format_dict['fill'] = fill or ' '
06045     # PEP 3101 originally specified that the default alignment should
06046     # be left;  it was later agreed that right-aligned makes more sense
06047     # for numeric types.  See http://bugs.python.org/issue6857.
06048     format_dict['align'] = align or '>'
06049 
06050     # default sign handling: '-' for negative, '' for positive
06051     if format_dict['sign'] is None:
06052         format_dict['sign'] = '-'
06053 
06054     # minimumwidth defaults to 0; precision remains None if not given
06055     format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
06056     if format_dict['precision'] is not None:
06057         format_dict['precision'] = int(format_dict['precision'])
06058 
06059     # if format type is 'g' or 'G' then a precision of 0 makes little
06060     # sense; convert it to 1.  Same if format type is unspecified.
06061     if format_dict['precision'] == 0:
06062         if format_dict['type'] is None or format_dict['type'] in 'gG':
06063             format_dict['precision'] = 1
06064 
06065     # determine thousands separator, grouping, and decimal separator, and
06066     # add appropriate entries to format_dict
06067     if format_dict['type'] == 'n':
06068         # apart from separators, 'n' behaves just like 'g'
06069         format_dict['type'] = 'g'
06070         if _localeconv is None:
06071             _localeconv = _locale.localeconv()
06072         if format_dict['thousands_sep'] is not None:
06073             raise ValueError("Explicit thousands separator conflicts with "
06074                              "'n' type in format specifier: " + format_spec)
06075         format_dict['thousands_sep'] = _localeconv['thousands_sep']
06076         format_dict['grouping'] = _localeconv['grouping']
06077         format_dict['decimal_point'] = _localeconv['decimal_point']
06078     else:
06079         if format_dict['thousands_sep'] is None:
06080             format_dict['thousands_sep'] = ''
06081         format_dict['grouping'] = [3, 0]
06082         format_dict['decimal_point'] = '.'
06083 
06084     return format_dict
06085 
06086 def _format_align(sign, body, spec):
06087     """Given an unpadded, non-aligned numeric string 'body' and sign
06088     string 'sign', add padding and alignment conforming to the given
06089     format specifier dictionary 'spec' (as produced by
06090     parse_format_specifier).
06091 
06092     """
06093     # how much extra space do we have to play with?
06094     minimumwidth = spec['minimumwidth']
06095     fill = spec['fill']
06096     padding = fill*(minimumwidth - len(sign) - len(body))
06097 
06098     align = spec['align']
06099     if align == '<':
06100         result = sign + body + padding
06101     elif align == '>':
06102         result = padding + sign + body
06103     elif align == '=':
06104         result = sign + padding + body
06105     elif align == '^':
06106         half = len(padding)//2
06107         result = padding[:half] + sign + body + padding[half:]
06108     else:
06109         raise ValueError('Unrecognised alignment field')
06110 
06111     return result
06112 
06113 def _group_lengths(grouping):
06114     """Convert a localeconv-style grouping into a (possibly infinite)
06115     iterable of integers representing group lengths.
06116 
06117     """
06118     # The result from localeconv()['grouping'], and the input to this
06119     # function, should be a list of integers in one of the
06120     # following three forms:
06121     #
06122     #   (1) an empty list, or
06123     #   (2) nonempty list of positive integers + [0]
06124     #   (3) list of positive integers + [locale.CHAR_MAX], or
06125 
06126     from itertools import chain, repeat
06127     if not grouping:
06128         return []
06129     elif grouping[-1] == 0 and len(grouping) >= 2:
06130         return chain(grouping[:-1], repeat(grouping[-2]))
06131     elif grouping[-1] == _locale.CHAR_MAX:
06132         return grouping[:-1]
06133     else:
06134         raise ValueError('unrecognised format for grouping')
06135 
06136 def _insert_thousands_sep(digits, spec, min_width=1):
06137     """Insert thousands separators into a digit string.
06138 
06139     spec is a dictionary whose keys should include 'thousands_sep' and
06140     'grouping'; typically it's the result of parsing the format
06141     specifier using _parse_format_specifier.
06142 
06143     The min_width keyword argument gives the minimum length of the
06144     result, which will be padded on the left with zeros if necessary.
06145 
06146     If necessary, the zero padding adds an extra '0' on the left to
06147     avoid a leading thousands separator.  For example, inserting
06148     commas every three digits in '123456', with min_width=8, gives
06149     '0,123,456', even though that has length 9.
06150 
06151     """
06152 
06153     sep = spec['thousands_sep']
06154     grouping = spec['grouping']
06155 
06156     groups = []
06157     for l in _group_lengths(grouping):
06158         if l <= 0:
06159             raise ValueError("group length should be positive")
06160         # max(..., 1) forces at least 1 digit to the left of a separator
06161         l = min(max(len(digits), min_width, 1), l)
06162         groups.append('0'*(l - len(digits)) + digits[-l:])
06163         digits = digits[:-l]
06164         min_width -= l
06165         if not digits and min_width <= 0:
06166             break
06167         min_width -= len(sep)
06168     else:
06169         l = max(len(digits), min_width, 1)
06170         groups.append('0'*(l - len(digits)) + digits[-l:])
06171     return sep.join(reversed(groups))
06172 
06173 def _format_sign(is_negative, spec):
06174     """Determine sign character."""
06175 
06176     if is_negative:
06177         return '-'
06178     elif spec['sign'] in ' +':
06179         return spec['sign']
06180     else:
06181         return ''
06182 
06183 def _format_number(is_negative, intpart, fracpart, exp, spec):
06184     """Format a number, given the following data:
06185 
06186     is_negative: true if the number is negative, else false
06187     intpart: string of digits that must appear before the decimal point
06188     fracpart: string of digits that must come after the point
06189     exp: exponent, as an integer
06190     spec: dictionary resulting from parsing the format specifier
06191 
06192     This function uses the information in spec to:
06193       insert separators (decimal separator and thousands separators)
06194       format the sign
06195       format the exponent
06196       add trailing '%' for the '%' type
06197       zero-pad if necessary
06198       fill and align if necessary
06199     """
06200 
06201     sign = _format_sign(is_negative, spec)
06202 
06203     if fracpart or spec['alt']:
06204         fracpart = spec['decimal_point'] + fracpart
06205 
06206     if exp != 0 or spec['type'] in 'eE':
06207         echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
06208         fracpart += "{0}{1:+}".format(echar, exp)
06209     if spec['type'] == '%':
06210         fracpart += '%'
06211 
06212     if spec['zeropad']:
06213         min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
06214     else:
06215         min_width = 0
06216     intpart = _insert_thousands_sep(intpart, spec, min_width)
06217 
06218     return _format_align(sign, intpart+fracpart, spec)
06219 
06220 
06221 ##### Useful Constants (internal use only) ################################
06222 
06223 # Reusable defaults
06224 _Infinity = Decimal('Inf')
06225 _NegativeInfinity = Decimal('-Inf')
06226 _NaN = Decimal('NaN')
06227 _Zero = Decimal(0)
06228 _One = Decimal(1)
06229 _NegativeOne = Decimal(-1)
06230 
06231 # _SignedInfinity[sign] is infinity w/ that sign
06232 _SignedInfinity = (_Infinity, _NegativeInfinity)
06233 
06234 # Constants related to the hash implementation;  hash(x) is based
06235 # on the reduction of x modulo _PyHASH_MODULUS
06236 import sys
06237 _PyHASH_MODULUS = sys.hash_info.modulus
06238 # hash values to use for positive and negative infinities, and nans
06239 _PyHASH_INF = sys.hash_info.inf
06240 _PyHASH_NAN = sys.hash_info.nan
06241 del sys
06242 
06243 # _PyHASH_10INV is the inverse of 10 modulo the prime _PyHASH_MODULUS
06244 _PyHASH_10INV = pow(10, _PyHASH_MODULUS - 2, _PyHASH_MODULUS)
06245 
06246 
06247 if __name__ == '__main__':
06248     import doctest, decimal
06249     doctest.testmod(decimal)