symbian-qemu-0.9.1-12/python-win32-2.6.1/lib/decimal.py
changeset 1 2fb8b9db1c86
equal deleted inserted replaced
0:ffa851df0825 1:2fb8b9db1c86
       
     1 # Copyright (c) 2004 Python Software Foundation.
       
     2 # All rights reserved.
       
     3 
       
     4 # Written by Eric Price <eprice at tjhsst.edu>
       
     5 #    and Facundo Batista <facundo at taniquetil.com.ar>
       
     6 #    and Raymond Hettinger <python at rcn.com>
       
     7 #    and Aahz <aahz at pobox.com>
       
     8 #    and Tim Peters
       
     9 
       
    10 # This module is currently Py2.3 compatible and should be kept that way
       
    11 # unless a major compelling advantage arises.  IOW, 2.3 compatibility is
       
    12 # strongly preferred, but not guaranteed.
       
    13 
       
    14 # Also, this module should be kept in sync with the latest updates of
       
    15 # the IBM specification as it evolves.  Those updates will be treated
       
    16 # as bug fixes (deviation from the spec is a compatibility, usability
       
    17 # bug) and will be backported.  At this point the spec is stabilizing
       
    18 # and the updates are becoming fewer, smaller, and less significant.
       
    19 
       
    20 """
       
    21 This is a Py2.3 implementation of decimal floating point arithmetic based on
       
    22 the General Decimal Arithmetic Specification:
       
    23 
       
    24     www2.hursley.ibm.com/decimal/decarith.html
       
    25 
       
    26 and IEEE standard 854-1987:
       
    27 
       
    28     www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
       
    29 
       
    30 Decimal floating point has finite precision with arbitrarily large bounds.
       
    31 
       
    32 The purpose of this module is to support arithmetic using familiar
       
    33 "schoolhouse" rules and to avoid some of the tricky representation
       
    34 issues associated with binary floating point.  The package is especially
       
    35 useful for financial applications or for contexts where users have
       
    36 expectations that are at odds with binary floating point (for instance,
       
    37 in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
       
    38 of the expected Decimal('0.00') returned by decimal floating point).
       
    39 
       
    40 Here are some examples of using the decimal module:
       
    41 
       
    42 >>> from decimal import *
       
    43 >>> setcontext(ExtendedContext)
       
    44 >>> Decimal(0)
       
    45 Decimal('0')
       
    46 >>> Decimal('1')
       
    47 Decimal('1')
       
    48 >>> Decimal('-.0123')
       
    49 Decimal('-0.0123')
       
    50 >>> Decimal(123456)
       
    51 Decimal('123456')
       
    52 >>> Decimal('123.45e12345678901234567890')
       
    53 Decimal('1.2345E+12345678901234567892')
       
    54 >>> Decimal('1.33') + Decimal('1.27')
       
    55 Decimal('2.60')
       
    56 >>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
       
    57 Decimal('-2.20')
       
    58 >>> dig = Decimal(1)
       
    59 >>> print dig / Decimal(3)
       
    60 0.333333333
       
    61 >>> getcontext().prec = 18
       
    62 >>> print dig / Decimal(3)
       
    63 0.333333333333333333
       
    64 >>> print dig.sqrt()
       
    65 1
       
    66 >>> print Decimal(3).sqrt()
       
    67 1.73205080756887729
       
    68 >>> print Decimal(3) ** 123
       
    69 4.85192780976896427E+58
       
    70 >>> inf = Decimal(1) / Decimal(0)
       
    71 >>> print inf
       
    72 Infinity
       
    73 >>> neginf = Decimal(-1) / Decimal(0)
       
    74 >>> print neginf
       
    75 -Infinity
       
    76 >>> print neginf + inf
       
    77 NaN
       
    78 >>> print neginf * inf
       
    79 -Infinity
       
    80 >>> print dig / 0
       
    81 Infinity
       
    82 >>> getcontext().traps[DivisionByZero] = 1
       
    83 >>> print dig / 0
       
    84 Traceback (most recent call last):
       
    85   ...
       
    86   ...
       
    87   ...
       
    88 DivisionByZero: x / 0
       
    89 >>> c = Context()
       
    90 >>> c.traps[InvalidOperation] = 0
       
    91 >>> print c.flags[InvalidOperation]
       
    92 0
       
    93 >>> c.divide(Decimal(0), Decimal(0))
       
    94 Decimal('NaN')
       
    95 >>> c.traps[InvalidOperation] = 1
       
    96 >>> print c.flags[InvalidOperation]
       
    97 1
       
    98 >>> c.flags[InvalidOperation] = 0
       
    99 >>> print c.flags[InvalidOperation]
       
   100 0
       
   101 >>> print c.divide(Decimal(0), Decimal(0))
       
   102 Traceback (most recent call last):
       
   103   ...
       
   104   ...
       
   105   ...
       
   106 InvalidOperation: 0 / 0
       
   107 >>> print c.flags[InvalidOperation]
       
   108 1
       
   109 >>> c.flags[InvalidOperation] = 0
       
   110 >>> c.traps[InvalidOperation] = 0
       
   111 >>> print c.divide(Decimal(0), Decimal(0))
       
   112 NaN
       
   113 >>> print c.flags[InvalidOperation]
       
   114 1
       
   115 >>>
       
   116 """
       
   117 
       
   118 __all__ = [
       
   119     # Two major classes
       
   120     'Decimal', 'Context',
       
   121 
       
   122     # Contexts
       
   123     'DefaultContext', 'BasicContext', 'ExtendedContext',
       
   124 
       
   125     # Exceptions
       
   126     'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
       
   127     'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
       
   128 
       
   129     # Constants for use in setting up contexts
       
   130     'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
       
   131     'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
       
   132 
       
   133     # Functions for manipulating contexts
       
   134     'setcontext', 'getcontext', 'localcontext'
       
   135 ]
       
   136 
       
   137 import copy as _copy
       
   138 
       
   139 try:
       
   140     from collections import namedtuple as _namedtuple
       
   141     DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
       
   142 except ImportError:
       
   143     DecimalTuple = lambda *args: args
       
   144 
       
   145 # Rounding
       
   146 ROUND_DOWN = 'ROUND_DOWN'
       
   147 ROUND_HALF_UP = 'ROUND_HALF_UP'
       
   148 ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
       
   149 ROUND_CEILING = 'ROUND_CEILING'
       
   150 ROUND_FLOOR = 'ROUND_FLOOR'
       
   151 ROUND_UP = 'ROUND_UP'
       
   152 ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
       
   153 ROUND_05UP = 'ROUND_05UP'
       
   154 
       
   155 # Errors
       
   156 
       
   157 class DecimalException(ArithmeticError):
       
   158     """Base exception class.
       
   159 
       
   160     Used exceptions derive from this.
       
   161     If an exception derives from another exception besides this (such as
       
   162     Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
       
   163     called if the others are present.  This isn't actually used for
       
   164     anything, though.
       
   165 
       
   166     handle  -- Called when context._raise_error is called and the
       
   167                trap_enabler is set.  First argument is self, second is the
       
   168                context.  More arguments can be given, those being after
       
   169                the explanation in _raise_error (For example,
       
   170                context._raise_error(NewError, '(-x)!', self._sign) would
       
   171                call NewError().handle(context, self._sign).)
       
   172 
       
   173     To define a new exception, it should be sufficient to have it derive
       
   174     from DecimalException.
       
   175     """
       
   176     def handle(self, context, *args):
       
   177         pass
       
   178 
       
   179 
       
   180 class Clamped(DecimalException):
       
   181     """Exponent of a 0 changed to fit bounds.
       
   182 
       
   183     This occurs and signals clamped if the exponent of a result has been
       
   184     altered in order to fit the constraints of a specific concrete
       
   185     representation.  This may occur when the exponent of a zero result would
       
   186     be outside the bounds of a representation, or when a large normal
       
   187     number would have an encoded exponent that cannot be represented.  In
       
   188     this latter case, the exponent is reduced to fit and the corresponding
       
   189     number of zero digits are appended to the coefficient ("fold-down").
       
   190     """
       
   191 
       
   192 class InvalidOperation(DecimalException):
       
   193     """An invalid operation was performed.
       
   194 
       
   195     Various bad things cause this:
       
   196 
       
   197     Something creates a signaling NaN
       
   198     -INF + INF
       
   199     0 * (+-)INF
       
   200     (+-)INF / (+-)INF
       
   201     x % 0
       
   202     (+-)INF % x
       
   203     x._rescale( non-integer )
       
   204     sqrt(-x) , x > 0
       
   205     0 ** 0
       
   206     x ** (non-integer)
       
   207     x ** (+-)INF
       
   208     An operand is invalid
       
   209 
       
   210     The result of the operation after these is a quiet positive NaN,
       
   211     except when the cause is a signaling NaN, in which case the result is
       
   212     also a quiet NaN, but with the original sign, and an optional
       
   213     diagnostic information.
       
   214     """
       
   215     def handle(self, context, *args):
       
   216         if args:
       
   217             ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
       
   218             return ans._fix_nan(context)
       
   219         return NaN
       
   220 
       
   221 class ConversionSyntax(InvalidOperation):
       
   222     """Trying to convert badly formed string.
       
   223 
       
   224     This occurs and signals invalid-operation if an string is being
       
   225     converted to a number and it does not conform to the numeric string
       
   226     syntax.  The result is [0,qNaN].
       
   227     """
       
   228     def handle(self, context, *args):
       
   229         return NaN
       
   230 
       
   231 class DivisionByZero(DecimalException, ZeroDivisionError):
       
   232     """Division by 0.
       
   233 
       
   234     This occurs and signals division-by-zero if division of a finite number
       
   235     by zero was attempted (during a divide-integer or divide operation, or a
       
   236     power operation with negative right-hand operand), and the dividend was
       
   237     not zero.
       
   238 
       
   239     The result of the operation is [sign,inf], where sign is the exclusive
       
   240     or of the signs of the operands for divide, or is 1 for an odd power of
       
   241     -0, for power.
       
   242     """
       
   243 
       
   244     def handle(self, context, sign, *args):
       
   245         return Infsign[sign]
       
   246 
       
   247 class DivisionImpossible(InvalidOperation):
       
   248     """Cannot perform the division adequately.
       
   249 
       
   250     This occurs and signals invalid-operation if the integer result of a
       
   251     divide-integer or remainder operation had too many digits (would be
       
   252     longer than precision).  The result is [0,qNaN].
       
   253     """
       
   254 
       
   255     def handle(self, context, *args):
       
   256         return NaN
       
   257 
       
   258 class DivisionUndefined(InvalidOperation, ZeroDivisionError):
       
   259     """Undefined result of division.
       
   260 
       
   261     This occurs and signals invalid-operation if division by zero was
       
   262     attempted (during a divide-integer, divide, or remainder operation), and
       
   263     the dividend is also zero.  The result is [0,qNaN].
       
   264     """
       
   265 
       
   266     def handle(self, context, *args):
       
   267         return NaN
       
   268 
       
   269 class Inexact(DecimalException):
       
   270     """Had to round, losing information.
       
   271 
       
   272     This occurs and signals inexact whenever the result of an operation is
       
   273     not exact (that is, it needed to be rounded and any discarded digits
       
   274     were non-zero), or if an overflow or underflow condition occurs.  The
       
   275     result in all cases is unchanged.
       
   276 
       
   277     The inexact signal may be tested (or trapped) to determine if a given
       
   278     operation (or sequence of operations) was inexact.
       
   279     """
       
   280 
       
   281 class InvalidContext(InvalidOperation):
       
   282     """Invalid context.  Unknown rounding, for example.
       
   283 
       
   284     This occurs and signals invalid-operation if an invalid context was
       
   285     detected during an operation.  This can occur if contexts are not checked
       
   286     on creation and either the precision exceeds the capability of the
       
   287     underlying concrete representation or an unknown or unsupported rounding
       
   288     was specified.  These aspects of the context need only be checked when
       
   289     the values are required to be used.  The result is [0,qNaN].
       
   290     """
       
   291 
       
   292     def handle(self, context, *args):
       
   293         return NaN
       
   294 
       
   295 class Rounded(DecimalException):
       
   296     """Number got rounded (not  necessarily changed during rounding).
       
   297 
       
   298     This occurs and signals rounded whenever the result of an operation is
       
   299     rounded (that is, some zero or non-zero digits were discarded from the
       
   300     coefficient), or if an overflow or underflow condition occurs.  The
       
   301     result in all cases is unchanged.
       
   302 
       
   303     The rounded signal may be tested (or trapped) to determine if a given
       
   304     operation (or sequence of operations) caused a loss of precision.
       
   305     """
       
   306 
       
   307 class Subnormal(DecimalException):
       
   308     """Exponent < Emin before rounding.
       
   309 
       
   310     This occurs and signals subnormal whenever the result of a conversion or
       
   311     operation is subnormal (that is, its adjusted exponent is less than
       
   312     Emin, before any rounding).  The result in all cases is unchanged.
       
   313 
       
   314     The subnormal signal may be tested (or trapped) to determine if a given
       
   315     or operation (or sequence of operations) yielded a subnormal result.
       
   316     """
       
   317 
       
   318 class Overflow(Inexact, Rounded):
       
   319     """Numerical overflow.
       
   320 
       
   321     This occurs and signals overflow if the adjusted exponent of a result
       
   322     (from a conversion or from an operation that is not an attempt to divide
       
   323     by zero), after rounding, would be greater than the largest value that
       
   324     can be handled by the implementation (the value Emax).
       
   325 
       
   326     The result depends on the rounding mode:
       
   327 
       
   328     For round-half-up and round-half-even (and for round-half-down and
       
   329     round-up, if implemented), the result of the operation is [sign,inf],
       
   330     where sign is the sign of the intermediate result.  For round-down, the
       
   331     result is the largest finite number that can be represented in the
       
   332     current precision, with the sign of the intermediate result.  For
       
   333     round-ceiling, the result is the same as for round-down if the sign of
       
   334     the intermediate result is 1, or is [0,inf] otherwise.  For round-floor,
       
   335     the result is the same as for round-down if the sign of the intermediate
       
   336     result is 0, or is [1,inf] otherwise.  In all cases, Inexact and Rounded
       
   337     will also be raised.
       
   338     """
       
   339 
       
   340     def handle(self, context, sign, *args):
       
   341         if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
       
   342                                 ROUND_HALF_DOWN, ROUND_UP):
       
   343             return Infsign[sign]
       
   344         if sign == 0:
       
   345             if context.rounding == ROUND_CEILING:
       
   346                 return Infsign[sign]
       
   347             return _dec_from_triple(sign, '9'*context.prec,
       
   348                             context.Emax-context.prec+1)
       
   349         if sign == 1:
       
   350             if context.rounding == ROUND_FLOOR:
       
   351                 return Infsign[sign]
       
   352             return _dec_from_triple(sign, '9'*context.prec,
       
   353                              context.Emax-context.prec+1)
       
   354 
       
   355 
       
   356 class Underflow(Inexact, Rounded, Subnormal):
       
   357     """Numerical underflow with result rounded to 0.
       
   358 
       
   359     This occurs and signals underflow if a result is inexact and the
       
   360     adjusted exponent of the result would be smaller (more negative) than
       
   361     the smallest value that can be handled by the implementation (the value
       
   362     Emin).  That is, the result is both inexact and subnormal.
       
   363 
       
   364     The result after an underflow will be a subnormal number rounded, if
       
   365     necessary, so that its exponent is not less than Etiny.  This may result
       
   366     in 0 with the sign of the intermediate result and an exponent of Etiny.
       
   367 
       
   368     In all cases, Inexact, Rounded, and Subnormal will also be raised.
       
   369     """
       
   370 
       
   371 # List of public traps and flags
       
   372 _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
       
   373            Underflow, InvalidOperation, Subnormal]
       
   374 
       
   375 # Map conditions (per the spec) to signals
       
   376 _condition_map = {ConversionSyntax:InvalidOperation,
       
   377                   DivisionImpossible:InvalidOperation,
       
   378                   DivisionUndefined:InvalidOperation,
       
   379                   InvalidContext:InvalidOperation}
       
   380 
       
   381 ##### Context Functions ##################################################
       
   382 
       
   383 # The getcontext() and setcontext() function manage access to a thread-local
       
   384 # current context.  Py2.4 offers direct support for thread locals.  If that
       
   385 # is not available, use threading.currentThread() which is slower but will
       
   386 # work for older Pythons.  If threads are not part of the build, create a
       
   387 # mock threading object with threading.local() returning the module namespace.
       
   388 
       
   389 try:
       
   390     import threading
       
   391 except ImportError:
       
   392     # Python was compiled without threads; create a mock object instead
       
   393     import sys
       
   394     class MockThreading(object):
       
   395         def local(self, sys=sys):
       
   396             return sys.modules[__name__]
       
   397     threading = MockThreading()
       
   398     del sys, MockThreading
       
   399 
       
   400 try:
       
   401     threading.local
       
   402 
       
   403 except AttributeError:
       
   404 
       
   405     # To fix reloading, force it to create a new context
       
   406     # Old contexts have different exceptions in their dicts, making problems.
       
   407     if hasattr(threading.currentThread(), '__decimal_context__'):
       
   408         del threading.currentThread().__decimal_context__
       
   409 
       
   410     def setcontext(context):
       
   411         """Set this thread's context to context."""
       
   412         if context in (DefaultContext, BasicContext, ExtendedContext):
       
   413             context = context.copy()
       
   414             context.clear_flags()
       
   415         threading.currentThread().__decimal_context__ = context
       
   416 
       
   417     def getcontext():
       
   418         """Returns this thread's context.
       
   419 
       
   420         If this thread does not yet have a context, returns
       
   421         a new context and sets this thread's context.
       
   422         New contexts are copies of DefaultContext.
       
   423         """
       
   424         try:
       
   425             return threading.currentThread().__decimal_context__
       
   426         except AttributeError:
       
   427             context = Context()
       
   428             threading.currentThread().__decimal_context__ = context
       
   429             return context
       
   430 
       
   431 else:
       
   432 
       
   433     local = threading.local()
       
   434     if hasattr(local, '__decimal_context__'):
       
   435         del local.__decimal_context__
       
   436 
       
   437     def getcontext(_local=local):
       
   438         """Returns this thread's context.
       
   439 
       
   440         If this thread does not yet have a context, returns
       
   441         a new context and sets this thread's context.
       
   442         New contexts are copies of DefaultContext.
       
   443         """
       
   444         try:
       
   445             return _local.__decimal_context__
       
   446         except AttributeError:
       
   447             context = Context()
       
   448             _local.__decimal_context__ = context
       
   449             return context
       
   450 
       
   451     def setcontext(context, _local=local):
       
   452         """Set this thread's context to context."""
       
   453         if context in (DefaultContext, BasicContext, ExtendedContext):
       
   454             context = context.copy()
       
   455             context.clear_flags()
       
   456         _local.__decimal_context__ = context
       
   457 
       
   458     del threading, local        # Don't contaminate the namespace
       
   459 
       
   460 def localcontext(ctx=None):
       
   461     """Return a context manager for a copy of the supplied context
       
   462 
       
   463     Uses a copy of the current context if no context is specified
       
   464     The returned context manager creates a local decimal context
       
   465     in a with statement:
       
   466         def sin(x):
       
   467              with localcontext() as ctx:
       
   468                  ctx.prec += 2
       
   469                  # Rest of sin calculation algorithm
       
   470                  # uses a precision 2 greater than normal
       
   471              return +s  # Convert result to normal precision
       
   472 
       
   473          def sin(x):
       
   474              with localcontext(ExtendedContext):
       
   475                  # Rest of sin calculation algorithm
       
   476                  # uses the Extended Context from the
       
   477                  # General Decimal Arithmetic Specification
       
   478              return +s  # Convert result to normal context
       
   479 
       
   480     >>> setcontext(DefaultContext)
       
   481     >>> print getcontext().prec
       
   482     28
       
   483     >>> with localcontext():
       
   484     ...     ctx = getcontext()
       
   485     ...     ctx.prec += 2
       
   486     ...     print ctx.prec
       
   487     ...
       
   488     30
       
   489     >>> with localcontext(ExtendedContext):
       
   490     ...     print getcontext().prec
       
   491     ...
       
   492     9
       
   493     >>> print getcontext().prec
       
   494     28
       
   495     """
       
   496     if ctx is None: ctx = getcontext()
       
   497     return _ContextManager(ctx)
       
   498 
       
   499 
       
   500 ##### Decimal class #######################################################
       
   501 
       
   502 class Decimal(object):
       
   503     """Floating point class for decimal arithmetic."""
       
   504 
       
   505     __slots__ = ('_exp','_int','_sign', '_is_special')
       
   506     # Generally, the value of the Decimal instance is given by
       
   507     #  (-1)**_sign * _int * 10**_exp
       
   508     # Special values are signified by _is_special == True
       
   509 
       
   510     # We're immutable, so use __new__ not __init__
       
   511     def __new__(cls, value="0", context=None):
       
   512         """Create a decimal point instance.
       
   513 
       
   514         >>> Decimal('3.14')              # string input
       
   515         Decimal('3.14')
       
   516         >>> Decimal((0, (3, 1, 4), -2))  # tuple (sign, digit_tuple, exponent)
       
   517         Decimal('3.14')
       
   518         >>> Decimal(314)                 # int or long
       
   519         Decimal('314')
       
   520         >>> Decimal(Decimal(314))        # another decimal instance
       
   521         Decimal('314')
       
   522         >>> Decimal('  3.14  \\n')        # leading and trailing whitespace okay
       
   523         Decimal('3.14')
       
   524         """
       
   525 
       
   526         # Note that the coefficient, self._int, is actually stored as
       
   527         # a string rather than as a tuple of digits.  This speeds up
       
   528         # the "digits to integer" and "integer to digits" conversions
       
   529         # that are used in almost every arithmetic operation on
       
   530         # Decimals.  This is an internal detail: the as_tuple function
       
   531         # and the Decimal constructor still deal with tuples of
       
   532         # digits.
       
   533 
       
   534         self = object.__new__(cls)
       
   535 
       
   536         # From a string
       
   537         # REs insist on real strings, so we can too.
       
   538         if isinstance(value, basestring):
       
   539             m = _parser(value.strip())
       
   540             if m is None:
       
   541                 if context is None:
       
   542                     context = getcontext()
       
   543                 return context._raise_error(ConversionSyntax,
       
   544                                 "Invalid literal for Decimal: %r" % value)
       
   545 
       
   546             if m.group('sign') == "-":
       
   547                 self._sign = 1
       
   548             else:
       
   549                 self._sign = 0
       
   550             intpart = m.group('int')
       
   551             if intpart is not None:
       
   552                 # finite number
       
   553                 fracpart = m.group('frac')
       
   554                 exp = int(m.group('exp') or '0')
       
   555                 if fracpart is not None:
       
   556                     self._int = str((intpart+fracpart).lstrip('0') or '0')
       
   557                     self._exp = exp - len(fracpart)
       
   558                 else:
       
   559                     self._int = str(intpart.lstrip('0') or '0')
       
   560                     self._exp = exp
       
   561                 self._is_special = False
       
   562             else:
       
   563                 diag = m.group('diag')
       
   564                 if diag is not None:
       
   565                     # NaN
       
   566                     self._int = str(diag.lstrip('0'))
       
   567                     if m.group('signal'):
       
   568                         self._exp = 'N'
       
   569                     else:
       
   570                         self._exp = 'n'
       
   571                 else:
       
   572                     # infinity
       
   573                     self._int = '0'
       
   574                     self._exp = 'F'
       
   575                 self._is_special = True
       
   576             return self
       
   577 
       
   578         # From an integer
       
   579         if isinstance(value, (int,long)):
       
   580             if value >= 0:
       
   581                 self._sign = 0
       
   582             else:
       
   583                 self._sign = 1
       
   584             self._exp = 0
       
   585             self._int = str(abs(value))
       
   586             self._is_special = False
       
   587             return self
       
   588 
       
   589         # From another decimal
       
   590         if isinstance(value, Decimal):
       
   591             self._exp  = value._exp
       
   592             self._sign = value._sign
       
   593             self._int  = value._int
       
   594             self._is_special  = value._is_special
       
   595             return self
       
   596 
       
   597         # From an internal working value
       
   598         if isinstance(value, _WorkRep):
       
   599             self._sign = value.sign
       
   600             self._int = str(value.int)
       
   601             self._exp = int(value.exp)
       
   602             self._is_special = False
       
   603             return self
       
   604 
       
   605         # tuple/list conversion (possibly from as_tuple())
       
   606         if isinstance(value, (list,tuple)):
       
   607             if len(value) != 3:
       
   608                 raise ValueError('Invalid tuple size in creation of Decimal '
       
   609                                  'from list or tuple.  The list or tuple '
       
   610                                  'should have exactly three elements.')
       
   611             # process sign.  The isinstance test rejects floats
       
   612             if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
       
   613                 raise ValueError("Invalid sign.  The first value in the tuple "
       
   614                                  "should be an integer; either 0 for a "
       
   615                                  "positive number or 1 for a negative number.")
       
   616             self._sign = value[0]
       
   617             if value[2] == 'F':
       
   618                 # infinity: value[1] is ignored
       
   619                 self._int = '0'
       
   620                 self._exp = value[2]
       
   621                 self._is_special = True
       
   622             else:
       
   623                 # process and validate the digits in value[1]
       
   624                 digits = []
       
   625                 for digit in value[1]:
       
   626                     if isinstance(digit, (int, long)) and 0 <= digit <= 9:
       
   627                         # skip leading zeros
       
   628                         if digits or digit != 0:
       
   629                             digits.append(digit)
       
   630                     else:
       
   631                         raise ValueError("The second value in the tuple must "
       
   632                                          "be composed of integers in the range "
       
   633                                          "0 through 9.")
       
   634                 if value[2] in ('n', 'N'):
       
   635                     # NaN: digits form the diagnostic
       
   636                     self._int = ''.join(map(str, digits))
       
   637                     self._exp = value[2]
       
   638                     self._is_special = True
       
   639                 elif isinstance(value[2], (int, long)):
       
   640                     # finite number: digits give the coefficient
       
   641                     self._int = ''.join(map(str, digits or [0]))
       
   642                     self._exp = value[2]
       
   643                     self._is_special = False
       
   644                 else:
       
   645                     raise ValueError("The third value in the tuple must "
       
   646                                      "be an integer, or one of the "
       
   647                                      "strings 'F', 'n', 'N'.")
       
   648             return self
       
   649 
       
   650         if isinstance(value, float):
       
   651             raise TypeError("Cannot convert float to Decimal.  " +
       
   652                             "First convert the float to a string")
       
   653 
       
   654         raise TypeError("Cannot convert %r to Decimal" % value)
       
   655 
       
   656     def _isnan(self):
       
   657         """Returns whether the number is not actually one.
       
   658 
       
   659         0 if a number
       
   660         1 if NaN
       
   661         2 if sNaN
       
   662         """
       
   663         if self._is_special:
       
   664             exp = self._exp
       
   665             if exp == 'n':
       
   666                 return 1
       
   667             elif exp == 'N':
       
   668                 return 2
       
   669         return 0
       
   670 
       
   671     def _isinfinity(self):
       
   672         """Returns whether the number is infinite
       
   673 
       
   674         0 if finite or not a number
       
   675         1 if +INF
       
   676         -1 if -INF
       
   677         """
       
   678         if self._exp == 'F':
       
   679             if self._sign:
       
   680                 return -1
       
   681             return 1
       
   682         return 0
       
   683 
       
   684     def _check_nans(self, other=None, context=None):
       
   685         """Returns whether the number is not actually one.
       
   686 
       
   687         if self, other are sNaN, signal
       
   688         if self, other are NaN return nan
       
   689         return 0
       
   690 
       
   691         Done before operations.
       
   692         """
       
   693 
       
   694         self_is_nan = self._isnan()
       
   695         if other is None:
       
   696             other_is_nan = False
       
   697         else:
       
   698             other_is_nan = other._isnan()
       
   699 
       
   700         if self_is_nan or other_is_nan:
       
   701             if context is None:
       
   702                 context = getcontext()
       
   703 
       
   704             if self_is_nan == 2:
       
   705                 return context._raise_error(InvalidOperation, 'sNaN',
       
   706                                         self)
       
   707             if other_is_nan == 2:
       
   708                 return context._raise_error(InvalidOperation, 'sNaN',
       
   709                                         other)
       
   710             if self_is_nan:
       
   711                 return self._fix_nan(context)
       
   712 
       
   713             return other._fix_nan(context)
       
   714         return 0
       
   715 
       
   716     def _compare_check_nans(self, other, context):
       
   717         """Version of _check_nans used for the signaling comparisons
       
   718         compare_signal, __le__, __lt__, __ge__, __gt__.
       
   719 
       
   720         Signal InvalidOperation if either self or other is a (quiet
       
   721         or signaling) NaN.  Signaling NaNs take precedence over quiet
       
   722         NaNs.
       
   723 
       
   724         Return 0 if neither operand is a NaN.
       
   725 
       
   726         """
       
   727         if context is None:
       
   728             context = getcontext()
       
   729 
       
   730         if self._is_special or other._is_special:
       
   731             if self.is_snan():
       
   732                 return context._raise_error(InvalidOperation,
       
   733                                             'comparison involving sNaN',
       
   734                                             self)
       
   735             elif other.is_snan():
       
   736                 return context._raise_error(InvalidOperation,
       
   737                                             'comparison involving sNaN',
       
   738                                             other)
       
   739             elif self.is_qnan():
       
   740                 return context._raise_error(InvalidOperation,
       
   741                                             'comparison involving NaN',
       
   742                                             self)
       
   743             elif other.is_qnan():
       
   744                 return context._raise_error(InvalidOperation,
       
   745                                             'comparison involving NaN',
       
   746                                             other)
       
   747         return 0
       
   748 
       
   749     def __nonzero__(self):
       
   750         """Return True if self is nonzero; otherwise return False.
       
   751 
       
   752         NaNs and infinities are considered nonzero.
       
   753         """
       
   754         return self._is_special or self._int != '0'
       
   755 
       
   756     def _cmp(self, other):
       
   757         """Compare the two non-NaN decimal instances self and other.
       
   758 
       
   759         Returns -1 if self < other, 0 if self == other and 1
       
   760         if self > other.  This routine is for internal use only."""
       
   761 
       
   762         if self._is_special or other._is_special:
       
   763             return cmp(self._isinfinity(), other._isinfinity())
       
   764 
       
   765         # check for zeros;  note that cmp(0, -0) should return 0
       
   766         if not self:
       
   767             if not other:
       
   768                 return 0
       
   769             else:
       
   770                 return -((-1)**other._sign)
       
   771         if not other:
       
   772             return (-1)**self._sign
       
   773 
       
   774         # If different signs, neg one is less
       
   775         if other._sign < self._sign:
       
   776             return -1
       
   777         if self._sign < other._sign:
       
   778             return 1
       
   779 
       
   780         self_adjusted = self.adjusted()
       
   781         other_adjusted = other.adjusted()
       
   782         if self_adjusted == other_adjusted:
       
   783             self_padded = self._int + '0'*(self._exp - other._exp)
       
   784             other_padded = other._int + '0'*(other._exp - self._exp)
       
   785             return cmp(self_padded, other_padded) * (-1)**self._sign
       
   786         elif self_adjusted > other_adjusted:
       
   787             return (-1)**self._sign
       
   788         else: # self_adjusted < other_adjusted
       
   789             return -((-1)**self._sign)
       
   790 
       
   791     # Note: The Decimal standard doesn't cover rich comparisons for
       
   792     # Decimals.  In particular, the specification is silent on the
       
   793     # subject of what should happen for a comparison involving a NaN.
       
   794     # We take the following approach:
       
   795     #
       
   796     #   == comparisons involving a NaN always return False
       
   797     #   != comparisons involving a NaN always return True
       
   798     #   <, >, <= and >= comparisons involving a (quiet or signaling)
       
   799     #      NaN signal InvalidOperation, and return False if the
       
   800     #      InvalidOperation is not trapped.
       
   801     #
       
   802     # This behavior is designed to conform as closely as possible to
       
   803     # that specified by IEEE 754.
       
   804 
       
   805     def __eq__(self, other):
       
   806         other = _convert_other(other)
       
   807         if other is NotImplemented:
       
   808             return other
       
   809         if self.is_nan() or other.is_nan():
       
   810             return False
       
   811         return self._cmp(other) == 0
       
   812 
       
   813     def __ne__(self, other):
       
   814         other = _convert_other(other)
       
   815         if other is NotImplemented:
       
   816             return other
       
   817         if self.is_nan() or other.is_nan():
       
   818             return True
       
   819         return self._cmp(other) != 0
       
   820 
       
   821     def __lt__(self, other, context=None):
       
   822         other = _convert_other(other)
       
   823         if other is NotImplemented:
       
   824             return other
       
   825         ans = self._compare_check_nans(other, context)
       
   826         if ans:
       
   827             return False
       
   828         return self._cmp(other) < 0
       
   829 
       
   830     def __le__(self, other, context=None):
       
   831         other = _convert_other(other)
       
   832         if other is NotImplemented:
       
   833             return other
       
   834         ans = self._compare_check_nans(other, context)
       
   835         if ans:
       
   836             return False
       
   837         return self._cmp(other) <= 0
       
   838 
       
   839     def __gt__(self, other, context=None):
       
   840         other = _convert_other(other)
       
   841         if other is NotImplemented:
       
   842             return other
       
   843         ans = self._compare_check_nans(other, context)
       
   844         if ans:
       
   845             return False
       
   846         return self._cmp(other) > 0
       
   847 
       
   848     def __ge__(self, other, context=None):
       
   849         other = _convert_other(other)
       
   850         if other is NotImplemented:
       
   851             return other
       
   852         ans = self._compare_check_nans(other, context)
       
   853         if ans:
       
   854             return False
       
   855         return self._cmp(other) >= 0
       
   856 
       
   857     def compare(self, other, context=None):
       
   858         """Compares one to another.
       
   859 
       
   860         -1 => a < b
       
   861         0  => a = b
       
   862         1  => a > b
       
   863         NaN => one is NaN
       
   864         Like __cmp__, but returns Decimal instances.
       
   865         """
       
   866         other = _convert_other(other, raiseit=True)
       
   867 
       
   868         # Compare(NaN, NaN) = NaN
       
   869         if (self._is_special or other and other._is_special):
       
   870             ans = self._check_nans(other, context)
       
   871             if ans:
       
   872                 return ans
       
   873 
       
   874         return Decimal(self._cmp(other))
       
   875 
       
   876     def __hash__(self):
       
   877         """x.__hash__() <==> hash(x)"""
       
   878         # Decimal integers must hash the same as the ints
       
   879         #
       
   880         # The hash of a nonspecial noninteger Decimal must depend only
       
   881         # on the value of that Decimal, and not on its representation.
       
   882         # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
       
   883         if self._is_special:
       
   884             if self._isnan():
       
   885                 raise TypeError('Cannot hash a NaN value.')
       
   886             return hash(str(self))
       
   887         if not self:
       
   888             return 0
       
   889         if self._isinteger():
       
   890             op = _WorkRep(self.to_integral_value())
       
   891             # to make computation feasible for Decimals with large
       
   892             # exponent, we use the fact that hash(n) == hash(m) for
       
   893             # any two nonzero integers n and m such that (i) n and m
       
   894             # have the same sign, and (ii) n is congruent to m modulo
       
   895             # 2**64-1.  So we can replace hash((-1)**s*c*10**e) with
       
   896             # hash((-1)**s*c*pow(10, e, 2**64-1).
       
   897             return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
       
   898         # The value of a nonzero nonspecial Decimal instance is
       
   899         # faithfully represented by the triple consisting of its sign,
       
   900         # its adjusted exponent, and its coefficient with trailing
       
   901         # zeros removed.
       
   902         return hash((self._sign,
       
   903                      self._exp+len(self._int),
       
   904                      self._int.rstrip('0')))
       
   905 
       
   906     def as_tuple(self):
       
   907         """Represents the number as a triple tuple.
       
   908 
       
   909         To show the internals exactly as they are.
       
   910         """
       
   911         return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
       
   912 
       
   913     def __repr__(self):
       
   914         """Represents the number as an instance of Decimal."""
       
   915         # Invariant:  eval(repr(d)) == d
       
   916         return "Decimal('%s')" % str(self)
       
   917 
       
   918     def __str__(self, eng=False, context=None):
       
   919         """Return string representation of the number in scientific notation.
       
   920 
       
   921         Captures all of the information in the underlying representation.
       
   922         """
       
   923 
       
   924         sign = ['', '-'][self._sign]
       
   925         if self._is_special:
       
   926             if self._exp == 'F':
       
   927                 return sign + 'Infinity'
       
   928             elif self._exp == 'n':
       
   929                 return sign + 'NaN' + self._int
       
   930             else: # self._exp == 'N'
       
   931                 return sign + 'sNaN' + self._int
       
   932 
       
   933         # number of digits of self._int to left of decimal point
       
   934         leftdigits = self._exp + len(self._int)
       
   935 
       
   936         # dotplace is number of digits of self._int to the left of the
       
   937         # decimal point in the mantissa of the output string (that is,
       
   938         # after adjusting the exponent)
       
   939         if self._exp <= 0 and leftdigits > -6:
       
   940             # no exponent required
       
   941             dotplace = leftdigits
       
   942         elif not eng:
       
   943             # usual scientific notation: 1 digit on left of the point
       
   944             dotplace = 1
       
   945         elif self._int == '0':
       
   946             # engineering notation, zero
       
   947             dotplace = (leftdigits + 1) % 3 - 1
       
   948         else:
       
   949             # engineering notation, nonzero
       
   950             dotplace = (leftdigits - 1) % 3 + 1
       
   951 
       
   952         if dotplace <= 0:
       
   953             intpart = '0'
       
   954             fracpart = '.' + '0'*(-dotplace) + self._int
       
   955         elif dotplace >= len(self._int):
       
   956             intpart = self._int+'0'*(dotplace-len(self._int))
       
   957             fracpart = ''
       
   958         else:
       
   959             intpart = self._int[:dotplace]
       
   960             fracpart = '.' + self._int[dotplace:]
       
   961         if leftdigits == dotplace:
       
   962             exp = ''
       
   963         else:
       
   964             if context is None:
       
   965                 context = getcontext()
       
   966             exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
       
   967 
       
   968         return sign + intpart + fracpart + exp
       
   969 
       
   970     def to_eng_string(self, context=None):
       
   971         """Convert to engineering-type string.
       
   972 
       
   973         Engineering notation has an exponent which is a multiple of 3, so there
       
   974         are up to 3 digits left of the decimal place.
       
   975 
       
   976         Same rules for when in exponential and when as a value as in __str__.
       
   977         """
       
   978         return self.__str__(eng=True, context=context)
       
   979 
       
   980     def __neg__(self, context=None):
       
   981         """Returns a copy with the sign switched.
       
   982 
       
   983         Rounds, if it has reason.
       
   984         """
       
   985         if self._is_special:
       
   986             ans = self._check_nans(context=context)
       
   987             if ans:
       
   988                 return ans
       
   989 
       
   990         if not self:
       
   991             # -Decimal('0') is Decimal('0'), not Decimal('-0')
       
   992             ans = self.copy_abs()
       
   993         else:
       
   994             ans = self.copy_negate()
       
   995 
       
   996         if context is None:
       
   997             context = getcontext()
       
   998         return ans._fix(context)
       
   999 
       
  1000     def __pos__(self, context=None):
       
  1001         """Returns a copy, unless it is a sNaN.
       
  1002 
       
  1003         Rounds the number (if more then precision digits)
       
  1004         """
       
  1005         if self._is_special:
       
  1006             ans = self._check_nans(context=context)
       
  1007             if ans:
       
  1008                 return ans
       
  1009 
       
  1010         if not self:
       
  1011             # + (-0) = 0
       
  1012             ans = self.copy_abs()
       
  1013         else:
       
  1014             ans = Decimal(self)
       
  1015 
       
  1016         if context is None:
       
  1017             context = getcontext()
       
  1018         return ans._fix(context)
       
  1019 
       
  1020     def __abs__(self, round=True, context=None):
       
  1021         """Returns the absolute value of self.
       
  1022 
       
  1023         If the keyword argument 'round' is false, do not round.  The
       
  1024         expression self.__abs__(round=False) is equivalent to
       
  1025         self.copy_abs().
       
  1026         """
       
  1027         if not round:
       
  1028             return self.copy_abs()
       
  1029 
       
  1030         if self._is_special:
       
  1031             ans = self._check_nans(context=context)
       
  1032             if ans:
       
  1033                 return ans
       
  1034 
       
  1035         if self._sign:
       
  1036             ans = self.__neg__(context=context)
       
  1037         else:
       
  1038             ans = self.__pos__(context=context)
       
  1039 
       
  1040         return ans
       
  1041 
       
  1042     def __add__(self, other, context=None):
       
  1043         """Returns self + other.
       
  1044 
       
  1045         -INF + INF (or the reverse) cause InvalidOperation errors.
       
  1046         """
       
  1047         other = _convert_other(other)
       
  1048         if other is NotImplemented:
       
  1049             return other
       
  1050 
       
  1051         if context is None:
       
  1052             context = getcontext()
       
  1053 
       
  1054         if self._is_special or other._is_special:
       
  1055             ans = self._check_nans(other, context)
       
  1056             if ans:
       
  1057                 return ans
       
  1058 
       
  1059             if self._isinfinity():
       
  1060                 # If both INF, same sign => same as both, opposite => error.
       
  1061                 if self._sign != other._sign and other._isinfinity():
       
  1062                     return context._raise_error(InvalidOperation, '-INF + INF')
       
  1063                 return Decimal(self)
       
  1064             if other._isinfinity():
       
  1065                 return Decimal(other)  # Can't both be infinity here
       
  1066 
       
  1067         exp = min(self._exp, other._exp)
       
  1068         negativezero = 0
       
  1069         if context.rounding == ROUND_FLOOR and self._sign != other._sign:
       
  1070             # If the answer is 0, the sign should be negative, in this case.
       
  1071             negativezero = 1
       
  1072 
       
  1073         if not self and not other:
       
  1074             sign = min(self._sign, other._sign)
       
  1075             if negativezero:
       
  1076                 sign = 1
       
  1077             ans = _dec_from_triple(sign, '0', exp)
       
  1078             ans = ans._fix(context)
       
  1079             return ans
       
  1080         if not self:
       
  1081             exp = max(exp, other._exp - context.prec-1)
       
  1082             ans = other._rescale(exp, context.rounding)
       
  1083             ans = ans._fix(context)
       
  1084             return ans
       
  1085         if not other:
       
  1086             exp = max(exp, self._exp - context.prec-1)
       
  1087             ans = self._rescale(exp, context.rounding)
       
  1088             ans = ans._fix(context)
       
  1089             return ans
       
  1090 
       
  1091         op1 = _WorkRep(self)
       
  1092         op2 = _WorkRep(other)
       
  1093         op1, op2 = _normalize(op1, op2, context.prec)
       
  1094 
       
  1095         result = _WorkRep()
       
  1096         if op1.sign != op2.sign:
       
  1097             # Equal and opposite
       
  1098             if op1.int == op2.int:
       
  1099                 ans = _dec_from_triple(negativezero, '0', exp)
       
  1100                 ans = ans._fix(context)
       
  1101                 return ans
       
  1102             if op1.int < op2.int:
       
  1103                 op1, op2 = op2, op1
       
  1104                 # OK, now abs(op1) > abs(op2)
       
  1105             if op1.sign == 1:
       
  1106                 result.sign = 1
       
  1107                 op1.sign, op2.sign = op2.sign, op1.sign
       
  1108             else:
       
  1109                 result.sign = 0
       
  1110                 # So we know the sign, and op1 > 0.
       
  1111         elif op1.sign == 1:
       
  1112             result.sign = 1
       
  1113             op1.sign, op2.sign = (0, 0)
       
  1114         else:
       
  1115             result.sign = 0
       
  1116         # Now, op1 > abs(op2) > 0
       
  1117 
       
  1118         if op2.sign == 0:
       
  1119             result.int = op1.int + op2.int
       
  1120         else:
       
  1121             result.int = op1.int - op2.int
       
  1122 
       
  1123         result.exp = op1.exp
       
  1124         ans = Decimal(result)
       
  1125         ans = ans._fix(context)
       
  1126         return ans
       
  1127 
       
  1128     __radd__ = __add__
       
  1129 
       
  1130     def __sub__(self, other, context=None):
       
  1131         """Return self - other"""
       
  1132         other = _convert_other(other)
       
  1133         if other is NotImplemented:
       
  1134             return other
       
  1135 
       
  1136         if self._is_special or other._is_special:
       
  1137             ans = self._check_nans(other, context=context)
       
  1138             if ans:
       
  1139                 return ans
       
  1140 
       
  1141         # self - other is computed as self + other.copy_negate()
       
  1142         return self.__add__(other.copy_negate(), context=context)
       
  1143 
       
  1144     def __rsub__(self, other, context=None):
       
  1145         """Return other - self"""
       
  1146         other = _convert_other(other)
       
  1147         if other is NotImplemented:
       
  1148             return other
       
  1149 
       
  1150         return other.__sub__(self, context=context)
       
  1151 
       
  1152     def __mul__(self, other, context=None):
       
  1153         """Return self * other.
       
  1154 
       
  1155         (+-) INF * 0 (or its reverse) raise InvalidOperation.
       
  1156         """
       
  1157         other = _convert_other(other)
       
  1158         if other is NotImplemented:
       
  1159             return other
       
  1160 
       
  1161         if context is None:
       
  1162             context = getcontext()
       
  1163 
       
  1164         resultsign = self._sign ^ other._sign
       
  1165 
       
  1166         if self._is_special or other._is_special:
       
  1167             ans = self._check_nans(other, context)
       
  1168             if ans:
       
  1169                 return ans
       
  1170 
       
  1171             if self._isinfinity():
       
  1172                 if not other:
       
  1173                     return context._raise_error(InvalidOperation, '(+-)INF * 0')
       
  1174                 return Infsign[resultsign]
       
  1175 
       
  1176             if other._isinfinity():
       
  1177                 if not self:
       
  1178                     return context._raise_error(InvalidOperation, '0 * (+-)INF')
       
  1179                 return Infsign[resultsign]
       
  1180 
       
  1181         resultexp = self._exp + other._exp
       
  1182 
       
  1183         # Special case for multiplying by zero
       
  1184         if not self or not other:
       
  1185             ans = _dec_from_triple(resultsign, '0', resultexp)
       
  1186             # Fixing in case the exponent is out of bounds
       
  1187             ans = ans._fix(context)
       
  1188             return ans
       
  1189 
       
  1190         # Special case for multiplying by power of 10
       
  1191         if self._int == '1':
       
  1192             ans = _dec_from_triple(resultsign, other._int, resultexp)
       
  1193             ans = ans._fix(context)
       
  1194             return ans
       
  1195         if other._int == '1':
       
  1196             ans = _dec_from_triple(resultsign, self._int, resultexp)
       
  1197             ans = ans._fix(context)
       
  1198             return ans
       
  1199 
       
  1200         op1 = _WorkRep(self)
       
  1201         op2 = _WorkRep(other)
       
  1202 
       
  1203         ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
       
  1204         ans = ans._fix(context)
       
  1205 
       
  1206         return ans
       
  1207     __rmul__ = __mul__
       
  1208 
       
  1209     def __truediv__(self, other, context=None):
       
  1210         """Return self / other."""
       
  1211         other = _convert_other(other)
       
  1212         if other is NotImplemented:
       
  1213             return NotImplemented
       
  1214 
       
  1215         if context is None:
       
  1216             context = getcontext()
       
  1217 
       
  1218         sign = self._sign ^ other._sign
       
  1219 
       
  1220         if self._is_special or other._is_special:
       
  1221             ans = self._check_nans(other, context)
       
  1222             if ans:
       
  1223                 return ans
       
  1224 
       
  1225             if self._isinfinity() and other._isinfinity():
       
  1226                 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
       
  1227 
       
  1228             if self._isinfinity():
       
  1229                 return Infsign[sign]
       
  1230 
       
  1231             if other._isinfinity():
       
  1232                 context._raise_error(Clamped, 'Division by infinity')
       
  1233                 return _dec_from_triple(sign, '0', context.Etiny())
       
  1234 
       
  1235         # Special cases for zeroes
       
  1236         if not other:
       
  1237             if not self:
       
  1238                 return context._raise_error(DivisionUndefined, '0 / 0')
       
  1239             return context._raise_error(DivisionByZero, 'x / 0', sign)
       
  1240 
       
  1241         if not self:
       
  1242             exp = self._exp - other._exp
       
  1243             coeff = 0
       
  1244         else:
       
  1245             # OK, so neither = 0, INF or NaN
       
  1246             shift = len(other._int) - len(self._int) + context.prec + 1
       
  1247             exp = self._exp - other._exp - shift
       
  1248             op1 = _WorkRep(self)
       
  1249             op2 = _WorkRep(other)
       
  1250             if shift >= 0:
       
  1251                 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
       
  1252             else:
       
  1253                 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
       
  1254             if remainder:
       
  1255                 # result is not exact; adjust to ensure correct rounding
       
  1256                 if coeff % 5 == 0:
       
  1257                     coeff += 1
       
  1258             else:
       
  1259                 # result is exact; get as close to ideal exponent as possible
       
  1260                 ideal_exp = self._exp - other._exp
       
  1261                 while exp < ideal_exp and coeff % 10 == 0:
       
  1262                     coeff //= 10
       
  1263                     exp += 1
       
  1264 
       
  1265         ans = _dec_from_triple(sign, str(coeff), exp)
       
  1266         return ans._fix(context)
       
  1267 
       
  1268     def _divide(self, other, context):
       
  1269         """Return (self // other, self % other), to context.prec precision.
       
  1270 
       
  1271         Assumes that neither self nor other is a NaN, that self is not
       
  1272         infinite and that other is nonzero.
       
  1273         """
       
  1274         sign = self._sign ^ other._sign
       
  1275         if other._isinfinity():
       
  1276             ideal_exp = self._exp
       
  1277         else:
       
  1278             ideal_exp = min(self._exp, other._exp)
       
  1279 
       
  1280         expdiff = self.adjusted() - other.adjusted()
       
  1281         if not self or other._isinfinity() or expdiff <= -2:
       
  1282             return (_dec_from_triple(sign, '0', 0),
       
  1283                     self._rescale(ideal_exp, context.rounding))
       
  1284         if expdiff <= context.prec:
       
  1285             op1 = _WorkRep(self)
       
  1286             op2 = _WorkRep(other)
       
  1287             if op1.exp >= op2.exp:
       
  1288                 op1.int *= 10**(op1.exp - op2.exp)
       
  1289             else:
       
  1290                 op2.int *= 10**(op2.exp - op1.exp)
       
  1291             q, r = divmod(op1.int, op2.int)
       
  1292             if q < 10**context.prec:
       
  1293                 return (_dec_from_triple(sign, str(q), 0),
       
  1294                         _dec_from_triple(self._sign, str(r), ideal_exp))
       
  1295 
       
  1296         # Here the quotient is too large to be representable
       
  1297         ans = context._raise_error(DivisionImpossible,
       
  1298                                    'quotient too large in //, % or divmod')
       
  1299         return ans, ans
       
  1300 
       
  1301     def __rtruediv__(self, other, context=None):
       
  1302         """Swaps self/other and returns __truediv__."""
       
  1303         other = _convert_other(other)
       
  1304         if other is NotImplemented:
       
  1305             return other
       
  1306         return other.__truediv__(self, context=context)
       
  1307 
       
  1308     __div__ = __truediv__
       
  1309     __rdiv__ = __rtruediv__
       
  1310 
       
  1311     def __divmod__(self, other, context=None):
       
  1312         """
       
  1313         Return (self // other, self % other)
       
  1314         """
       
  1315         other = _convert_other(other)
       
  1316         if other is NotImplemented:
       
  1317             return other
       
  1318 
       
  1319         if context is None:
       
  1320             context = getcontext()
       
  1321 
       
  1322         ans = self._check_nans(other, context)
       
  1323         if ans:
       
  1324             return (ans, ans)
       
  1325 
       
  1326         sign = self._sign ^ other._sign
       
  1327         if self._isinfinity():
       
  1328             if other._isinfinity():
       
  1329                 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
       
  1330                 return ans, ans
       
  1331             else:
       
  1332                 return (Infsign[sign],
       
  1333                         context._raise_error(InvalidOperation, 'INF % x'))
       
  1334 
       
  1335         if not other:
       
  1336             if not self:
       
  1337                 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
       
  1338                 return ans, ans
       
  1339             else:
       
  1340                 return (context._raise_error(DivisionByZero, 'x // 0', sign),
       
  1341                         context._raise_error(InvalidOperation, 'x % 0'))
       
  1342 
       
  1343         quotient, remainder = self._divide(other, context)
       
  1344         remainder = remainder._fix(context)
       
  1345         return quotient, remainder
       
  1346 
       
  1347     def __rdivmod__(self, other, context=None):
       
  1348         """Swaps self/other and returns __divmod__."""
       
  1349         other = _convert_other(other)
       
  1350         if other is NotImplemented:
       
  1351             return other
       
  1352         return other.__divmod__(self, context=context)
       
  1353 
       
  1354     def __mod__(self, other, context=None):
       
  1355         """
       
  1356         self % other
       
  1357         """
       
  1358         other = _convert_other(other)
       
  1359         if other is NotImplemented:
       
  1360             return other
       
  1361 
       
  1362         if context is None:
       
  1363             context = getcontext()
       
  1364 
       
  1365         ans = self._check_nans(other, context)
       
  1366         if ans:
       
  1367             return ans
       
  1368 
       
  1369         if self._isinfinity():
       
  1370             return context._raise_error(InvalidOperation, 'INF % x')
       
  1371         elif not other:
       
  1372             if self:
       
  1373                 return context._raise_error(InvalidOperation, 'x % 0')
       
  1374             else:
       
  1375                 return context._raise_error(DivisionUndefined, '0 % 0')
       
  1376 
       
  1377         remainder = self._divide(other, context)[1]
       
  1378         remainder = remainder._fix(context)
       
  1379         return remainder
       
  1380 
       
  1381     def __rmod__(self, other, context=None):
       
  1382         """Swaps self/other and returns __mod__."""
       
  1383         other = _convert_other(other)
       
  1384         if other is NotImplemented:
       
  1385             return other
       
  1386         return other.__mod__(self, context=context)
       
  1387 
       
  1388     def remainder_near(self, other, context=None):
       
  1389         """
       
  1390         Remainder nearest to 0-  abs(remainder-near) <= other/2
       
  1391         """
       
  1392         if context is None:
       
  1393             context = getcontext()
       
  1394 
       
  1395         other = _convert_other(other, raiseit=True)
       
  1396 
       
  1397         ans = self._check_nans(other, context)
       
  1398         if ans:
       
  1399             return ans
       
  1400 
       
  1401         # self == +/-infinity -> InvalidOperation
       
  1402         if self._isinfinity():
       
  1403             return context._raise_error(InvalidOperation,
       
  1404                                         'remainder_near(infinity, x)')
       
  1405 
       
  1406         # other == 0 -> either InvalidOperation or DivisionUndefined
       
  1407         if not other:
       
  1408             if self:
       
  1409                 return context._raise_error(InvalidOperation,
       
  1410                                             'remainder_near(x, 0)')
       
  1411             else:
       
  1412                 return context._raise_error(DivisionUndefined,
       
  1413                                             'remainder_near(0, 0)')
       
  1414 
       
  1415         # other = +/-infinity -> remainder = self
       
  1416         if other._isinfinity():
       
  1417             ans = Decimal(self)
       
  1418             return ans._fix(context)
       
  1419 
       
  1420         # self = 0 -> remainder = self, with ideal exponent
       
  1421         ideal_exponent = min(self._exp, other._exp)
       
  1422         if not self:
       
  1423             ans = _dec_from_triple(self._sign, '0', ideal_exponent)
       
  1424             return ans._fix(context)
       
  1425 
       
  1426         # catch most cases of large or small quotient
       
  1427         expdiff = self.adjusted() - other.adjusted()
       
  1428         if expdiff >= context.prec + 1:
       
  1429             # expdiff >= prec+1 => abs(self/other) > 10**prec
       
  1430             return context._raise_error(DivisionImpossible)
       
  1431         if expdiff <= -2:
       
  1432             # expdiff <= -2 => abs(self/other) < 0.1
       
  1433             ans = self._rescale(ideal_exponent, context.rounding)
       
  1434             return ans._fix(context)
       
  1435 
       
  1436         # adjust both arguments to have the same exponent, then divide
       
  1437         op1 = _WorkRep(self)
       
  1438         op2 = _WorkRep(other)
       
  1439         if op1.exp >= op2.exp:
       
  1440             op1.int *= 10**(op1.exp - op2.exp)
       
  1441         else:
       
  1442             op2.int *= 10**(op2.exp - op1.exp)
       
  1443         q, r = divmod(op1.int, op2.int)
       
  1444         # remainder is r*10**ideal_exponent; other is +/-op2.int *
       
  1445         # 10**ideal_exponent.   Apply correction to ensure that
       
  1446         # abs(remainder) <= abs(other)/2
       
  1447         if 2*r + (q&1) > op2.int:
       
  1448             r -= op2.int
       
  1449             q += 1
       
  1450 
       
  1451         if q >= 10**context.prec:
       
  1452             return context._raise_error(DivisionImpossible)
       
  1453 
       
  1454         # result has same sign as self unless r is negative
       
  1455         sign = self._sign
       
  1456         if r < 0:
       
  1457             sign = 1-sign
       
  1458             r = -r
       
  1459 
       
  1460         ans = _dec_from_triple(sign, str(r), ideal_exponent)
       
  1461         return ans._fix(context)
       
  1462 
       
  1463     def __floordiv__(self, other, context=None):
       
  1464         """self // other"""
       
  1465         other = _convert_other(other)
       
  1466         if other is NotImplemented:
       
  1467             return other
       
  1468 
       
  1469         if context is None:
       
  1470             context = getcontext()
       
  1471 
       
  1472         ans = self._check_nans(other, context)
       
  1473         if ans:
       
  1474             return ans
       
  1475 
       
  1476         if self._isinfinity():
       
  1477             if other._isinfinity():
       
  1478                 return context._raise_error(InvalidOperation, 'INF // INF')
       
  1479             else:
       
  1480                 return Infsign[self._sign ^ other._sign]
       
  1481 
       
  1482         if not other:
       
  1483             if self:
       
  1484                 return context._raise_error(DivisionByZero, 'x // 0',
       
  1485                                             self._sign ^ other._sign)
       
  1486             else:
       
  1487                 return context._raise_error(DivisionUndefined, '0 // 0')
       
  1488 
       
  1489         return self._divide(other, context)[0]
       
  1490 
       
  1491     def __rfloordiv__(self, other, context=None):
       
  1492         """Swaps self/other and returns __floordiv__."""
       
  1493         other = _convert_other(other)
       
  1494         if other is NotImplemented:
       
  1495             return other
       
  1496         return other.__floordiv__(self, context=context)
       
  1497 
       
  1498     def __float__(self):
       
  1499         """Float representation."""
       
  1500         return float(str(self))
       
  1501 
       
  1502     def __int__(self):
       
  1503         """Converts self to an int, truncating if necessary."""
       
  1504         if self._is_special:
       
  1505             if self._isnan():
       
  1506                 context = getcontext()
       
  1507                 return context._raise_error(InvalidContext)
       
  1508             elif self._isinfinity():
       
  1509                 raise OverflowError("Cannot convert infinity to int")
       
  1510         s = (-1)**self._sign
       
  1511         if self._exp >= 0:
       
  1512             return s*int(self._int)*10**self._exp
       
  1513         else:
       
  1514             return s*int(self._int[:self._exp] or '0')
       
  1515 
       
  1516     __trunc__ = __int__
       
  1517 
       
  1518     @property
       
  1519     def real(self):
       
  1520         return self
       
  1521 
       
  1522     @property
       
  1523     def imag(self):
       
  1524         return Decimal(0)
       
  1525 
       
  1526     def conjugate(self):
       
  1527         return self
       
  1528 
       
  1529     def __complex__(self):
       
  1530         return complex(float(self))
       
  1531 
       
  1532     def __long__(self):
       
  1533         """Converts to a long.
       
  1534 
       
  1535         Equivalent to long(int(self))
       
  1536         """
       
  1537         return long(self.__int__())
       
  1538 
       
  1539     def _fix_nan(self, context):
       
  1540         """Decapitate the payload of a NaN to fit the context"""
       
  1541         payload = self._int
       
  1542 
       
  1543         # maximum length of payload is precision if _clamp=0,
       
  1544         # precision-1 if _clamp=1.
       
  1545         max_payload_len = context.prec - context._clamp
       
  1546         if len(payload) > max_payload_len:
       
  1547             payload = payload[len(payload)-max_payload_len:].lstrip('0')
       
  1548             return _dec_from_triple(self._sign, payload, self._exp, True)
       
  1549         return Decimal(self)
       
  1550 
       
  1551     def _fix(self, context):
       
  1552         """Round if it is necessary to keep self within prec precision.
       
  1553 
       
  1554         Rounds and fixes the exponent.  Does not raise on a sNaN.
       
  1555 
       
  1556         Arguments:
       
  1557         self - Decimal instance
       
  1558         context - context used.
       
  1559         """
       
  1560 
       
  1561         if self._is_special:
       
  1562             if self._isnan():
       
  1563                 # decapitate payload if necessary
       
  1564                 return self._fix_nan(context)
       
  1565             else:
       
  1566                 # self is +/-Infinity; return unaltered
       
  1567                 return Decimal(self)
       
  1568 
       
  1569         # if self is zero then exponent should be between Etiny and
       
  1570         # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
       
  1571         Etiny = context.Etiny()
       
  1572         Etop = context.Etop()
       
  1573         if not self:
       
  1574             exp_max = [context.Emax, Etop][context._clamp]
       
  1575             new_exp = min(max(self._exp, Etiny), exp_max)
       
  1576             if new_exp != self._exp:
       
  1577                 context._raise_error(Clamped)
       
  1578                 return _dec_from_triple(self._sign, '0', new_exp)
       
  1579             else:
       
  1580                 return Decimal(self)
       
  1581 
       
  1582         # exp_min is the smallest allowable exponent of the result,
       
  1583         # equal to max(self.adjusted()-context.prec+1, Etiny)
       
  1584         exp_min = len(self._int) + self._exp - context.prec
       
  1585         if exp_min > Etop:
       
  1586             # overflow: exp_min > Etop iff self.adjusted() > Emax
       
  1587             context._raise_error(Inexact)
       
  1588             context._raise_error(Rounded)
       
  1589             return context._raise_error(Overflow, 'above Emax', self._sign)
       
  1590         self_is_subnormal = exp_min < Etiny
       
  1591         if self_is_subnormal:
       
  1592             context._raise_error(Subnormal)
       
  1593             exp_min = Etiny
       
  1594 
       
  1595         # round if self has too many digits
       
  1596         if self._exp < exp_min:
       
  1597             context._raise_error(Rounded)
       
  1598             digits = len(self._int) + self._exp - exp_min
       
  1599             if digits < 0:
       
  1600                 self = _dec_from_triple(self._sign, '1', exp_min-1)
       
  1601                 digits = 0
       
  1602             this_function = getattr(self, self._pick_rounding_function[context.rounding])
       
  1603             changed = this_function(digits)
       
  1604             coeff = self._int[:digits] or '0'
       
  1605             if changed == 1:
       
  1606                 coeff = str(int(coeff)+1)
       
  1607             ans = _dec_from_triple(self._sign, coeff, exp_min)
       
  1608 
       
  1609             if changed:
       
  1610                 context._raise_error(Inexact)
       
  1611                 if self_is_subnormal:
       
  1612                     context._raise_error(Underflow)
       
  1613                     if not ans:
       
  1614                         # raise Clamped on underflow to 0
       
  1615                         context._raise_error(Clamped)
       
  1616                 elif len(ans._int) == context.prec+1:
       
  1617                     # we get here only if rescaling rounds the
       
  1618                     # cofficient up to exactly 10**context.prec
       
  1619                     if ans._exp < Etop:
       
  1620                         ans = _dec_from_triple(ans._sign,
       
  1621                                                    ans._int[:-1], ans._exp+1)
       
  1622                     else:
       
  1623                         # Inexact and Rounded have already been raised
       
  1624                         ans = context._raise_error(Overflow, 'above Emax',
       
  1625                                                    self._sign)
       
  1626             return ans
       
  1627 
       
  1628         # fold down if _clamp == 1 and self has too few digits
       
  1629         if context._clamp == 1 and self._exp > Etop:
       
  1630             context._raise_error(Clamped)
       
  1631             self_padded = self._int + '0'*(self._exp - Etop)
       
  1632             return _dec_from_triple(self._sign, self_padded, Etop)
       
  1633 
       
  1634         # here self was representable to begin with; return unchanged
       
  1635         return Decimal(self)
       
  1636 
       
  1637     _pick_rounding_function = {}
       
  1638 
       
  1639     # for each of the rounding functions below:
       
  1640     #   self is a finite, nonzero Decimal
       
  1641     #   prec is an integer satisfying 0 <= prec < len(self._int)
       
  1642     #
       
  1643     # each function returns either -1, 0, or 1, as follows:
       
  1644     #   1 indicates that self should be rounded up (away from zero)
       
  1645     #   0 indicates that self should be truncated, and that all the
       
  1646     #     digits to be truncated are zeros (so the value is unchanged)
       
  1647     #  -1 indicates that there are nonzero digits to be truncated
       
  1648 
       
  1649     def _round_down(self, prec):
       
  1650         """Also known as round-towards-0, truncate."""
       
  1651         if _all_zeros(self._int, prec):
       
  1652             return 0
       
  1653         else:
       
  1654             return -1
       
  1655 
       
  1656     def _round_up(self, prec):
       
  1657         """Rounds away from 0."""
       
  1658         return -self._round_down(prec)
       
  1659 
       
  1660     def _round_half_up(self, prec):
       
  1661         """Rounds 5 up (away from 0)"""
       
  1662         if self._int[prec] in '56789':
       
  1663             return 1
       
  1664         elif _all_zeros(self._int, prec):
       
  1665             return 0
       
  1666         else:
       
  1667             return -1
       
  1668 
       
  1669     def _round_half_down(self, prec):
       
  1670         """Round 5 down"""
       
  1671         if _exact_half(self._int, prec):
       
  1672             return -1
       
  1673         else:
       
  1674             return self._round_half_up(prec)
       
  1675 
       
  1676     def _round_half_even(self, prec):
       
  1677         """Round 5 to even, rest to nearest."""
       
  1678         if _exact_half(self._int, prec) and \
       
  1679                 (prec == 0 or self._int[prec-1] in '02468'):
       
  1680             return -1
       
  1681         else:
       
  1682             return self._round_half_up(prec)
       
  1683 
       
  1684     def _round_ceiling(self, prec):
       
  1685         """Rounds up (not away from 0 if negative.)"""
       
  1686         if self._sign:
       
  1687             return self._round_down(prec)
       
  1688         else:
       
  1689             return -self._round_down(prec)
       
  1690 
       
  1691     def _round_floor(self, prec):
       
  1692         """Rounds down (not towards 0 if negative)"""
       
  1693         if not self._sign:
       
  1694             return self._round_down(prec)
       
  1695         else:
       
  1696             return -self._round_down(prec)
       
  1697 
       
  1698     def _round_05up(self, prec):
       
  1699         """Round down unless digit prec-1 is 0 or 5."""
       
  1700         if prec and self._int[prec-1] not in '05':
       
  1701             return self._round_down(prec)
       
  1702         else:
       
  1703             return -self._round_down(prec)
       
  1704 
       
  1705     def fma(self, other, third, context=None):
       
  1706         """Fused multiply-add.
       
  1707 
       
  1708         Returns self*other+third with no rounding of the intermediate
       
  1709         product self*other.
       
  1710 
       
  1711         self and other are multiplied together, with no rounding of
       
  1712         the result.  The third operand is then added to the result,
       
  1713         and a single final rounding is performed.
       
  1714         """
       
  1715 
       
  1716         other = _convert_other(other, raiseit=True)
       
  1717 
       
  1718         # compute product; raise InvalidOperation if either operand is
       
  1719         # a signaling NaN or if the product is zero times infinity.
       
  1720         if self._is_special or other._is_special:
       
  1721             if context is None:
       
  1722                 context = getcontext()
       
  1723             if self._exp == 'N':
       
  1724                 return context._raise_error(InvalidOperation, 'sNaN', self)
       
  1725             if other._exp == 'N':
       
  1726                 return context._raise_error(InvalidOperation, 'sNaN', other)
       
  1727             if self._exp == 'n':
       
  1728                 product = self
       
  1729             elif other._exp == 'n':
       
  1730                 product = other
       
  1731             elif self._exp == 'F':
       
  1732                 if not other:
       
  1733                     return context._raise_error(InvalidOperation,
       
  1734                                                 'INF * 0 in fma')
       
  1735                 product = Infsign[self._sign ^ other._sign]
       
  1736             elif other._exp == 'F':
       
  1737                 if not self:
       
  1738                     return context._raise_error(InvalidOperation,
       
  1739                                                 '0 * INF in fma')
       
  1740                 product = Infsign[self._sign ^ other._sign]
       
  1741         else:
       
  1742             product = _dec_from_triple(self._sign ^ other._sign,
       
  1743                                        str(int(self._int) * int(other._int)),
       
  1744                                        self._exp + other._exp)
       
  1745 
       
  1746         third = _convert_other(third, raiseit=True)
       
  1747         return product.__add__(third, context)
       
  1748 
       
  1749     def _power_modulo(self, other, modulo, context=None):
       
  1750         """Three argument version of __pow__"""
       
  1751 
       
  1752         # if can't convert other and modulo to Decimal, raise
       
  1753         # TypeError; there's no point returning NotImplemented (no
       
  1754         # equivalent of __rpow__ for three argument pow)
       
  1755         other = _convert_other(other, raiseit=True)
       
  1756         modulo = _convert_other(modulo, raiseit=True)
       
  1757 
       
  1758         if context is None:
       
  1759             context = getcontext()
       
  1760 
       
  1761         # deal with NaNs: if there are any sNaNs then first one wins,
       
  1762         # (i.e. behaviour for NaNs is identical to that of fma)
       
  1763         self_is_nan = self._isnan()
       
  1764         other_is_nan = other._isnan()
       
  1765         modulo_is_nan = modulo._isnan()
       
  1766         if self_is_nan or other_is_nan or modulo_is_nan:
       
  1767             if self_is_nan == 2:
       
  1768                 return context._raise_error(InvalidOperation, 'sNaN',
       
  1769                                         self)
       
  1770             if other_is_nan == 2:
       
  1771                 return context._raise_error(InvalidOperation, 'sNaN',
       
  1772                                         other)
       
  1773             if modulo_is_nan == 2:
       
  1774                 return context._raise_error(InvalidOperation, 'sNaN',
       
  1775                                         modulo)
       
  1776             if self_is_nan:
       
  1777                 return self._fix_nan(context)
       
  1778             if other_is_nan:
       
  1779                 return other._fix_nan(context)
       
  1780             return modulo._fix_nan(context)
       
  1781 
       
  1782         # check inputs: we apply same restrictions as Python's pow()
       
  1783         if not (self._isinteger() and
       
  1784                 other._isinteger() and
       
  1785                 modulo._isinteger()):
       
  1786             return context._raise_error(InvalidOperation,
       
  1787                                         'pow() 3rd argument not allowed '
       
  1788                                         'unless all arguments are integers')
       
  1789         if other < 0:
       
  1790             return context._raise_error(InvalidOperation,
       
  1791                                         'pow() 2nd argument cannot be '
       
  1792                                         'negative when 3rd argument specified')
       
  1793         if not modulo:
       
  1794             return context._raise_error(InvalidOperation,
       
  1795                                         'pow() 3rd argument cannot be 0')
       
  1796 
       
  1797         # additional restriction for decimal: the modulus must be less
       
  1798         # than 10**prec in absolute value
       
  1799         if modulo.adjusted() >= context.prec:
       
  1800             return context._raise_error(InvalidOperation,
       
  1801                                         'insufficient precision: pow() 3rd '
       
  1802                                         'argument must not have more than '
       
  1803                                         'precision digits')
       
  1804 
       
  1805         # define 0**0 == NaN, for consistency with two-argument pow
       
  1806         # (even though it hurts!)
       
  1807         if not other and not self:
       
  1808             return context._raise_error(InvalidOperation,
       
  1809                                         'at least one of pow() 1st argument '
       
  1810                                         'and 2nd argument must be nonzero ;'
       
  1811                                         '0**0 is not defined')
       
  1812 
       
  1813         # compute sign of result
       
  1814         if other._iseven():
       
  1815             sign = 0
       
  1816         else:
       
  1817             sign = self._sign
       
  1818 
       
  1819         # convert modulo to a Python integer, and self and other to
       
  1820         # Decimal integers (i.e. force their exponents to be >= 0)
       
  1821         modulo = abs(int(modulo))
       
  1822         base = _WorkRep(self.to_integral_value())
       
  1823         exponent = _WorkRep(other.to_integral_value())
       
  1824 
       
  1825         # compute result using integer pow()
       
  1826         base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
       
  1827         for i in xrange(exponent.exp):
       
  1828             base = pow(base, 10, modulo)
       
  1829         base = pow(base, exponent.int, modulo)
       
  1830 
       
  1831         return _dec_from_triple(sign, str(base), 0)
       
  1832 
       
  1833     def _power_exact(self, other, p):
       
  1834         """Attempt to compute self**other exactly.
       
  1835 
       
  1836         Given Decimals self and other and an integer p, attempt to
       
  1837         compute an exact result for the power self**other, with p
       
  1838         digits of precision.  Return None if self**other is not
       
  1839         exactly representable in p digits.
       
  1840 
       
  1841         Assumes that elimination of special cases has already been
       
  1842         performed: self and other must both be nonspecial; self must
       
  1843         be positive and not numerically equal to 1; other must be
       
  1844         nonzero.  For efficiency, other._exp should not be too large,
       
  1845         so that 10**abs(other._exp) is a feasible calculation."""
       
  1846 
       
  1847         # In the comments below, we write x for the value of self and
       
  1848         # y for the value of other.  Write x = xc*10**xe and y =
       
  1849         # yc*10**ye.
       
  1850 
       
  1851         # The main purpose of this method is to identify the *failure*
       
  1852         # of x**y to be exactly representable with as little effort as
       
  1853         # possible.  So we look for cheap and easy tests that
       
  1854         # eliminate the possibility of x**y being exact.  Only if all
       
  1855         # these tests are passed do we go on to actually compute x**y.
       
  1856 
       
  1857         # Here's the main idea.  First normalize both x and y.  We
       
  1858         # express y as a rational m/n, with m and n relatively prime
       
  1859         # and n>0.  Then for x**y to be exactly representable (at
       
  1860         # *any* precision), xc must be the nth power of a positive
       
  1861         # integer and xe must be divisible by n.  If m is negative
       
  1862         # then additionally xc must be a power of either 2 or 5, hence
       
  1863         # a power of 2**n or 5**n.
       
  1864         #
       
  1865         # There's a limit to how small |y| can be: if y=m/n as above
       
  1866         # then:
       
  1867         #
       
  1868         #  (1) if xc != 1 then for the result to be representable we
       
  1869         #      need xc**(1/n) >= 2, and hence also xc**|y| >= 2.  So
       
  1870         #      if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
       
  1871         #      2**(1/|y|), hence xc**|y| < 2 and the result is not
       
  1872         #      representable.
       
  1873         #
       
  1874         #  (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1.  Hence if
       
  1875         #      |y| < 1/|xe| then the result is not representable.
       
  1876         #
       
  1877         # Note that since x is not equal to 1, at least one of (1) and
       
  1878         # (2) must apply.  Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
       
  1879         # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
       
  1880         #
       
  1881         # There's also a limit to how large y can be, at least if it's
       
  1882         # positive: the normalized result will have coefficient xc**y,
       
  1883         # so if it's representable then xc**y < 10**p, and y <
       
  1884         # p/log10(xc).  Hence if y*log10(xc) >= p then the result is
       
  1885         # not exactly representable.
       
  1886 
       
  1887         # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
       
  1888         # so |y| < 1/xe and the result is not representable.
       
  1889         # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
       
  1890         # < 1/nbits(xc).
       
  1891 
       
  1892         x = _WorkRep(self)
       
  1893         xc, xe = x.int, x.exp
       
  1894         while xc % 10 == 0:
       
  1895             xc //= 10
       
  1896             xe += 1
       
  1897 
       
  1898         y = _WorkRep(other)
       
  1899         yc, ye = y.int, y.exp
       
  1900         while yc % 10 == 0:
       
  1901             yc //= 10
       
  1902             ye += 1
       
  1903 
       
  1904         # case where xc == 1: result is 10**(xe*y), with xe*y
       
  1905         # required to be an integer
       
  1906         if xc == 1:
       
  1907             if ye >= 0:
       
  1908                 exponent = xe*yc*10**ye
       
  1909             else:
       
  1910                 exponent, remainder = divmod(xe*yc, 10**-ye)
       
  1911                 if remainder:
       
  1912                     return None
       
  1913             if y.sign == 1:
       
  1914                 exponent = -exponent
       
  1915             # if other is a nonnegative integer, use ideal exponent
       
  1916             if other._isinteger() and other._sign == 0:
       
  1917                 ideal_exponent = self._exp*int(other)
       
  1918                 zeros = min(exponent-ideal_exponent, p-1)
       
  1919             else:
       
  1920                 zeros = 0
       
  1921             return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
       
  1922 
       
  1923         # case where y is negative: xc must be either a power
       
  1924         # of 2 or a power of 5.
       
  1925         if y.sign == 1:
       
  1926             last_digit = xc % 10
       
  1927             if last_digit in (2,4,6,8):
       
  1928                 # quick test for power of 2
       
  1929                 if xc & -xc != xc:
       
  1930                     return None
       
  1931                 # now xc is a power of 2; e is its exponent
       
  1932                 e = _nbits(xc)-1
       
  1933                 # find e*y and xe*y; both must be integers
       
  1934                 if ye >= 0:
       
  1935                     y_as_int = yc*10**ye
       
  1936                     e = e*y_as_int
       
  1937                     xe = xe*y_as_int
       
  1938                 else:
       
  1939                     ten_pow = 10**-ye
       
  1940                     e, remainder = divmod(e*yc, ten_pow)
       
  1941                     if remainder:
       
  1942                         return None
       
  1943                     xe, remainder = divmod(xe*yc, ten_pow)
       
  1944                     if remainder:
       
  1945                         return None
       
  1946 
       
  1947                 if e*65 >= p*93: # 93/65 > log(10)/log(5)
       
  1948                     return None
       
  1949                 xc = 5**e
       
  1950 
       
  1951             elif last_digit == 5:
       
  1952                 # e >= log_5(xc) if xc is a power of 5; we have
       
  1953                 # equality all the way up to xc=5**2658
       
  1954                 e = _nbits(xc)*28//65
       
  1955                 xc, remainder = divmod(5**e, xc)
       
  1956                 if remainder:
       
  1957                     return None
       
  1958                 while xc % 5 == 0:
       
  1959                     xc //= 5
       
  1960                     e -= 1
       
  1961                 if ye >= 0:
       
  1962                     y_as_integer = yc*10**ye
       
  1963                     e = e*y_as_integer
       
  1964                     xe = xe*y_as_integer
       
  1965                 else:
       
  1966                     ten_pow = 10**-ye
       
  1967                     e, remainder = divmod(e*yc, ten_pow)
       
  1968                     if remainder:
       
  1969                         return None
       
  1970                     xe, remainder = divmod(xe*yc, ten_pow)
       
  1971                     if remainder:
       
  1972                         return None
       
  1973                 if e*3 >= p*10: # 10/3 > log(10)/log(2)
       
  1974                     return None
       
  1975                 xc = 2**e
       
  1976             else:
       
  1977                 return None
       
  1978 
       
  1979             if xc >= 10**p:
       
  1980                 return None
       
  1981             xe = -e-xe
       
  1982             return _dec_from_triple(0, str(xc), xe)
       
  1983 
       
  1984         # now y is positive; find m and n such that y = m/n
       
  1985         if ye >= 0:
       
  1986             m, n = yc*10**ye, 1
       
  1987         else:
       
  1988             if xe != 0 and len(str(abs(yc*xe))) <= -ye:
       
  1989                 return None
       
  1990             xc_bits = _nbits(xc)
       
  1991             if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
       
  1992                 return None
       
  1993             m, n = yc, 10**(-ye)
       
  1994             while m % 2 == n % 2 == 0:
       
  1995                 m //= 2
       
  1996                 n //= 2
       
  1997             while m % 5 == n % 5 == 0:
       
  1998                 m //= 5
       
  1999                 n //= 5
       
  2000 
       
  2001         # compute nth root of xc*10**xe
       
  2002         if n > 1:
       
  2003             # if 1 < xc < 2**n then xc isn't an nth power
       
  2004             if xc != 1 and xc_bits <= n:
       
  2005                 return None
       
  2006 
       
  2007             xe, rem = divmod(xe, n)
       
  2008             if rem != 0:
       
  2009                 return None
       
  2010 
       
  2011             # compute nth root of xc using Newton's method
       
  2012             a = 1L << -(-_nbits(xc)//n) # initial estimate
       
  2013             while True:
       
  2014                 q, r = divmod(xc, a**(n-1))
       
  2015                 if a <= q:
       
  2016                     break
       
  2017                 else:
       
  2018                     a = (a*(n-1) + q)//n
       
  2019             if not (a == q and r == 0):
       
  2020                 return None
       
  2021             xc = a
       
  2022 
       
  2023         # now xc*10**xe is the nth root of the original xc*10**xe
       
  2024         # compute mth power of xc*10**xe
       
  2025 
       
  2026         # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
       
  2027         # 10**p and the result is not representable.
       
  2028         if xc > 1 and m > p*100//_log10_lb(xc):
       
  2029             return None
       
  2030         xc = xc**m
       
  2031         xe *= m
       
  2032         if xc > 10**p:
       
  2033             return None
       
  2034 
       
  2035         # by this point the result *is* exactly representable
       
  2036         # adjust the exponent to get as close as possible to the ideal
       
  2037         # exponent, if necessary
       
  2038         str_xc = str(xc)
       
  2039         if other._isinteger() and other._sign == 0:
       
  2040             ideal_exponent = self._exp*int(other)
       
  2041             zeros = min(xe-ideal_exponent, p-len(str_xc))
       
  2042         else:
       
  2043             zeros = 0
       
  2044         return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
       
  2045 
       
  2046     def __pow__(self, other, modulo=None, context=None):
       
  2047         """Return self ** other [ % modulo].
       
  2048 
       
  2049         With two arguments, compute self**other.
       
  2050 
       
  2051         With three arguments, compute (self**other) % modulo.  For the
       
  2052         three argument form, the following restrictions on the
       
  2053         arguments hold:
       
  2054 
       
  2055          - all three arguments must be integral
       
  2056          - other must be nonnegative
       
  2057          - either self or other (or both) must be nonzero
       
  2058          - modulo must be nonzero and must have at most p digits,
       
  2059            where p is the context precision.
       
  2060 
       
  2061         If any of these restrictions is violated the InvalidOperation
       
  2062         flag is raised.
       
  2063 
       
  2064         The result of pow(self, other, modulo) is identical to the
       
  2065         result that would be obtained by computing (self**other) %
       
  2066         modulo with unbounded precision, but is computed more
       
  2067         efficiently.  It is always exact.
       
  2068         """
       
  2069 
       
  2070         if modulo is not None:
       
  2071             return self._power_modulo(other, modulo, context)
       
  2072 
       
  2073         other = _convert_other(other)
       
  2074         if other is NotImplemented:
       
  2075             return other
       
  2076 
       
  2077         if context is None:
       
  2078             context = getcontext()
       
  2079 
       
  2080         # either argument is a NaN => result is NaN
       
  2081         ans = self._check_nans(other, context)
       
  2082         if ans:
       
  2083             return ans
       
  2084 
       
  2085         # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
       
  2086         if not other:
       
  2087             if not self:
       
  2088                 return context._raise_error(InvalidOperation, '0 ** 0')
       
  2089             else:
       
  2090                 return Dec_p1
       
  2091 
       
  2092         # result has sign 1 iff self._sign is 1 and other is an odd integer
       
  2093         result_sign = 0
       
  2094         if self._sign == 1:
       
  2095             if other._isinteger():
       
  2096                 if not other._iseven():
       
  2097                     result_sign = 1
       
  2098             else:
       
  2099                 # -ve**noninteger = NaN
       
  2100                 # (-0)**noninteger = 0**noninteger
       
  2101                 if self:
       
  2102                     return context._raise_error(InvalidOperation,
       
  2103                         'x ** y with x negative and y not an integer')
       
  2104             # negate self, without doing any unwanted rounding
       
  2105             self = self.copy_negate()
       
  2106 
       
  2107         # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
       
  2108         if not self:
       
  2109             if other._sign == 0:
       
  2110                 return _dec_from_triple(result_sign, '0', 0)
       
  2111             else:
       
  2112                 return Infsign[result_sign]
       
  2113 
       
  2114         # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
       
  2115         if self._isinfinity():
       
  2116             if other._sign == 0:
       
  2117                 return Infsign[result_sign]
       
  2118             else:
       
  2119                 return _dec_from_triple(result_sign, '0', 0)
       
  2120 
       
  2121         # 1**other = 1, but the choice of exponent and the flags
       
  2122         # depend on the exponent of self, and on whether other is a
       
  2123         # positive integer, a negative integer, or neither
       
  2124         if self == Dec_p1:
       
  2125             if other._isinteger():
       
  2126                 # exp = max(self._exp*max(int(other), 0),
       
  2127                 # 1-context.prec) but evaluating int(other) directly
       
  2128                 # is dangerous until we know other is small (other
       
  2129                 # could be 1e999999999)
       
  2130                 if other._sign == 1:
       
  2131                     multiplier = 0
       
  2132                 elif other > context.prec:
       
  2133                     multiplier = context.prec
       
  2134                 else:
       
  2135                     multiplier = int(other)
       
  2136 
       
  2137                 exp = self._exp * multiplier
       
  2138                 if exp < 1-context.prec:
       
  2139                     exp = 1-context.prec
       
  2140                     context._raise_error(Rounded)
       
  2141             else:
       
  2142                 context._raise_error(Inexact)
       
  2143                 context._raise_error(Rounded)
       
  2144                 exp = 1-context.prec
       
  2145 
       
  2146             return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
       
  2147 
       
  2148         # compute adjusted exponent of self
       
  2149         self_adj = self.adjusted()
       
  2150 
       
  2151         # self ** infinity is infinity if self > 1, 0 if self < 1
       
  2152         # self ** -infinity is infinity if self < 1, 0 if self > 1
       
  2153         if other._isinfinity():
       
  2154             if (other._sign == 0) == (self_adj < 0):
       
  2155                 return _dec_from_triple(result_sign, '0', 0)
       
  2156             else:
       
  2157                 return Infsign[result_sign]
       
  2158 
       
  2159         # from here on, the result always goes through the call
       
  2160         # to _fix at the end of this function.
       
  2161         ans = None
       
  2162 
       
  2163         # crude test to catch cases of extreme overflow/underflow.  If
       
  2164         # log10(self)*other >= 10**bound and bound >= len(str(Emax))
       
  2165         # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
       
  2166         # self**other >= 10**(Emax+1), so overflow occurs.  The test
       
  2167         # for underflow is similar.
       
  2168         bound = self._log10_exp_bound() + other.adjusted()
       
  2169         if (self_adj >= 0) == (other._sign == 0):
       
  2170             # self > 1 and other +ve, or self < 1 and other -ve
       
  2171             # possibility of overflow
       
  2172             if bound >= len(str(context.Emax)):
       
  2173                 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
       
  2174         else:
       
  2175             # self > 1 and other -ve, or self < 1 and other +ve
       
  2176             # possibility of underflow to 0
       
  2177             Etiny = context.Etiny()
       
  2178             if bound >= len(str(-Etiny)):
       
  2179                 ans = _dec_from_triple(result_sign, '1', Etiny-1)
       
  2180 
       
  2181         # try for an exact result with precision +1
       
  2182         if ans is None:
       
  2183             ans = self._power_exact(other, context.prec + 1)
       
  2184             if ans is not None and result_sign == 1:
       
  2185                 ans = _dec_from_triple(1, ans._int, ans._exp)
       
  2186 
       
  2187         # usual case: inexact result, x**y computed directly as exp(y*log(x))
       
  2188         if ans is None:
       
  2189             p = context.prec
       
  2190             x = _WorkRep(self)
       
  2191             xc, xe = x.int, x.exp
       
  2192             y = _WorkRep(other)
       
  2193             yc, ye = y.int, y.exp
       
  2194             if y.sign == 1:
       
  2195                 yc = -yc
       
  2196 
       
  2197             # compute correctly rounded result:  start with precision +3,
       
  2198             # then increase precision until result is unambiguously roundable
       
  2199             extra = 3
       
  2200             while True:
       
  2201                 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
       
  2202                 if coeff % (5*10**(len(str(coeff))-p-1)):
       
  2203                     break
       
  2204                 extra += 3
       
  2205 
       
  2206             ans = _dec_from_triple(result_sign, str(coeff), exp)
       
  2207 
       
  2208         # the specification says that for non-integer other we need to
       
  2209         # raise Inexact, even when the result is actually exact.  In
       
  2210         # the same way, we need to raise Underflow here if the result
       
  2211         # is subnormal.  (The call to _fix will take care of raising
       
  2212         # Rounded and Subnormal, as usual.)
       
  2213         if not other._isinteger():
       
  2214             context._raise_error(Inexact)
       
  2215             # pad with zeros up to length context.prec+1 if necessary
       
  2216             if len(ans._int) <= context.prec:
       
  2217                 expdiff = context.prec+1 - len(ans._int)
       
  2218                 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
       
  2219                                        ans._exp-expdiff)
       
  2220             if ans.adjusted() < context.Emin:
       
  2221                 context._raise_error(Underflow)
       
  2222 
       
  2223         # unlike exp, ln and log10, the power function respects the
       
  2224         # rounding mode; no need to use ROUND_HALF_EVEN here
       
  2225         ans = ans._fix(context)
       
  2226         return ans
       
  2227 
       
  2228     def __rpow__(self, other, context=None):
       
  2229         """Swaps self/other and returns __pow__."""
       
  2230         other = _convert_other(other)
       
  2231         if other is NotImplemented:
       
  2232             return other
       
  2233         return other.__pow__(self, context=context)
       
  2234 
       
  2235     def normalize(self, context=None):
       
  2236         """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
       
  2237 
       
  2238         if context is None:
       
  2239             context = getcontext()
       
  2240 
       
  2241         if self._is_special:
       
  2242             ans = self._check_nans(context=context)
       
  2243             if ans:
       
  2244                 return ans
       
  2245 
       
  2246         dup = self._fix(context)
       
  2247         if dup._isinfinity():
       
  2248             return dup
       
  2249 
       
  2250         if not dup:
       
  2251             return _dec_from_triple(dup._sign, '0', 0)
       
  2252         exp_max = [context.Emax, context.Etop()][context._clamp]
       
  2253         end = len(dup._int)
       
  2254         exp = dup._exp
       
  2255         while dup._int[end-1] == '0' and exp < exp_max:
       
  2256             exp += 1
       
  2257             end -= 1
       
  2258         return _dec_from_triple(dup._sign, dup._int[:end], exp)
       
  2259 
       
  2260     def quantize(self, exp, rounding=None, context=None, watchexp=True):
       
  2261         """Quantize self so its exponent is the same as that of exp.
       
  2262 
       
  2263         Similar to self._rescale(exp._exp) but with error checking.
       
  2264         """
       
  2265         exp = _convert_other(exp, raiseit=True)
       
  2266 
       
  2267         if context is None:
       
  2268             context = getcontext()
       
  2269         if rounding is None:
       
  2270             rounding = context.rounding
       
  2271 
       
  2272         if self._is_special or exp._is_special:
       
  2273             ans = self._check_nans(exp, context)
       
  2274             if ans:
       
  2275                 return ans
       
  2276 
       
  2277             if exp._isinfinity() or self._isinfinity():
       
  2278                 if exp._isinfinity() and self._isinfinity():
       
  2279                     return Decimal(self)  # if both are inf, it is OK
       
  2280                 return context._raise_error(InvalidOperation,
       
  2281                                         'quantize with one INF')
       
  2282 
       
  2283         # if we're not watching exponents, do a simple rescale
       
  2284         if not watchexp:
       
  2285             ans = self._rescale(exp._exp, rounding)
       
  2286             # raise Inexact and Rounded where appropriate
       
  2287             if ans._exp > self._exp:
       
  2288                 context._raise_error(Rounded)
       
  2289                 if ans != self:
       
  2290                     context._raise_error(Inexact)
       
  2291             return ans
       
  2292 
       
  2293         # exp._exp should be between Etiny and Emax
       
  2294         if not (context.Etiny() <= exp._exp <= context.Emax):
       
  2295             return context._raise_error(InvalidOperation,
       
  2296                    'target exponent out of bounds in quantize')
       
  2297 
       
  2298         if not self:
       
  2299             ans = _dec_from_triple(self._sign, '0', exp._exp)
       
  2300             return ans._fix(context)
       
  2301 
       
  2302         self_adjusted = self.adjusted()
       
  2303         if self_adjusted > context.Emax:
       
  2304             return context._raise_error(InvalidOperation,
       
  2305                                         'exponent of quantize result too large for current context')
       
  2306         if self_adjusted - exp._exp + 1 > context.prec:
       
  2307             return context._raise_error(InvalidOperation,
       
  2308                                         'quantize result has too many digits for current context')
       
  2309 
       
  2310         ans = self._rescale(exp._exp, rounding)
       
  2311         if ans.adjusted() > context.Emax:
       
  2312             return context._raise_error(InvalidOperation,
       
  2313                                         'exponent of quantize result too large for current context')
       
  2314         if len(ans._int) > context.prec:
       
  2315             return context._raise_error(InvalidOperation,
       
  2316                                         'quantize result has too many digits for current context')
       
  2317 
       
  2318         # raise appropriate flags
       
  2319         if ans._exp > self._exp:
       
  2320             context._raise_error(Rounded)
       
  2321             if ans != self:
       
  2322                 context._raise_error(Inexact)
       
  2323         if ans and ans.adjusted() < context.Emin:
       
  2324             context._raise_error(Subnormal)
       
  2325 
       
  2326         # call to fix takes care of any necessary folddown
       
  2327         ans = ans._fix(context)
       
  2328         return ans
       
  2329 
       
  2330     def same_quantum(self, other):
       
  2331         """Return True if self and other have the same exponent; otherwise
       
  2332         return False.
       
  2333 
       
  2334         If either operand is a special value, the following rules are used:
       
  2335            * return True if both operands are infinities
       
  2336            * return True if both operands are NaNs
       
  2337            * otherwise, return False.
       
  2338         """
       
  2339         other = _convert_other(other, raiseit=True)
       
  2340         if self._is_special or other._is_special:
       
  2341             return (self.is_nan() and other.is_nan() or
       
  2342                     self.is_infinite() and other.is_infinite())
       
  2343         return self._exp == other._exp
       
  2344 
       
  2345     def _rescale(self, exp, rounding):
       
  2346         """Rescale self so that the exponent is exp, either by padding with zeros
       
  2347         or by truncating digits, using the given rounding mode.
       
  2348 
       
  2349         Specials are returned without change.  This operation is
       
  2350         quiet: it raises no flags, and uses no information from the
       
  2351         context.
       
  2352 
       
  2353         exp = exp to scale to (an integer)
       
  2354         rounding = rounding mode
       
  2355         """
       
  2356         if self._is_special:
       
  2357             return Decimal(self)
       
  2358         if not self:
       
  2359             return _dec_from_triple(self._sign, '0', exp)
       
  2360 
       
  2361         if self._exp >= exp:
       
  2362             # pad answer with zeros if necessary
       
  2363             return _dec_from_triple(self._sign,
       
  2364                                         self._int + '0'*(self._exp - exp), exp)
       
  2365 
       
  2366         # too many digits; round and lose data.  If self.adjusted() <
       
  2367         # exp-1, replace self by 10**(exp-1) before rounding
       
  2368         digits = len(self._int) + self._exp - exp
       
  2369         if digits < 0:
       
  2370             self = _dec_from_triple(self._sign, '1', exp-1)
       
  2371             digits = 0
       
  2372         this_function = getattr(self, self._pick_rounding_function[rounding])
       
  2373         changed = this_function(digits)
       
  2374         coeff = self._int[:digits] or '0'
       
  2375         if changed == 1:
       
  2376             coeff = str(int(coeff)+1)
       
  2377         return _dec_from_triple(self._sign, coeff, exp)
       
  2378 
       
  2379     def _round(self, places, rounding):
       
  2380         """Round a nonzero, nonspecial Decimal to a fixed number of
       
  2381         significant figures, using the given rounding mode.
       
  2382 
       
  2383         Infinities, NaNs and zeros are returned unaltered.
       
  2384 
       
  2385         This operation is quiet: it raises no flags, and uses no
       
  2386         information from the context.
       
  2387 
       
  2388         """
       
  2389         if places <= 0:
       
  2390             raise ValueError("argument should be at least 1 in _round")
       
  2391         if self._is_special or not self:
       
  2392             return Decimal(self)
       
  2393         ans = self._rescale(self.adjusted()+1-places, rounding)
       
  2394         # it can happen that the rescale alters the adjusted exponent;
       
  2395         # for example when rounding 99.97 to 3 significant figures.
       
  2396         # When this happens we end up with an extra 0 at the end of
       
  2397         # the number; a second rescale fixes this.
       
  2398         if ans.adjusted() != self.adjusted():
       
  2399             ans = ans._rescale(ans.adjusted()+1-places, rounding)
       
  2400         return ans
       
  2401 
       
  2402     def to_integral_exact(self, rounding=None, context=None):
       
  2403         """Rounds to a nearby integer.
       
  2404 
       
  2405         If no rounding mode is specified, take the rounding mode from
       
  2406         the context.  This method raises the Rounded and Inexact flags
       
  2407         when appropriate.
       
  2408 
       
  2409         See also: to_integral_value, which does exactly the same as
       
  2410         this method except that it doesn't raise Inexact or Rounded.
       
  2411         """
       
  2412         if self._is_special:
       
  2413             ans = self._check_nans(context=context)
       
  2414             if ans:
       
  2415                 return ans
       
  2416             return Decimal(self)
       
  2417         if self._exp >= 0:
       
  2418             return Decimal(self)
       
  2419         if not self:
       
  2420             return _dec_from_triple(self._sign, '0', 0)
       
  2421         if context is None:
       
  2422             context = getcontext()
       
  2423         if rounding is None:
       
  2424             rounding = context.rounding
       
  2425         context._raise_error(Rounded)
       
  2426         ans = self._rescale(0, rounding)
       
  2427         if ans != self:
       
  2428             context._raise_error(Inexact)
       
  2429         return ans
       
  2430 
       
  2431     def to_integral_value(self, rounding=None, context=None):
       
  2432         """Rounds to the nearest integer, without raising inexact, rounded."""
       
  2433         if context is None:
       
  2434             context = getcontext()
       
  2435         if rounding is None:
       
  2436             rounding = context.rounding
       
  2437         if self._is_special:
       
  2438             ans = self._check_nans(context=context)
       
  2439             if ans:
       
  2440                 return ans
       
  2441             return Decimal(self)
       
  2442         if self._exp >= 0:
       
  2443             return Decimal(self)
       
  2444         else:
       
  2445             return self._rescale(0, rounding)
       
  2446 
       
  2447     # the method name changed, but we provide also the old one, for compatibility
       
  2448     to_integral = to_integral_value
       
  2449 
       
  2450     def sqrt(self, context=None):
       
  2451         """Return the square root of self."""
       
  2452         if context is None:
       
  2453             context = getcontext()
       
  2454 
       
  2455         if self._is_special:
       
  2456             ans = self._check_nans(context=context)
       
  2457             if ans:
       
  2458                 return ans
       
  2459 
       
  2460             if self._isinfinity() and self._sign == 0:
       
  2461                 return Decimal(self)
       
  2462 
       
  2463         if not self:
       
  2464             # exponent = self._exp // 2.  sqrt(-0) = -0
       
  2465             ans = _dec_from_triple(self._sign, '0', self._exp // 2)
       
  2466             return ans._fix(context)
       
  2467 
       
  2468         if self._sign == 1:
       
  2469             return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
       
  2470 
       
  2471         # At this point self represents a positive number.  Let p be
       
  2472         # the desired precision and express self in the form c*100**e
       
  2473         # with c a positive real number and e an integer, c and e
       
  2474         # being chosen so that 100**(p-1) <= c < 100**p.  Then the
       
  2475         # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
       
  2476         # <= sqrt(c) < 10**p, so the closest representable Decimal at
       
  2477         # precision p is n*10**e where n = round_half_even(sqrt(c)),
       
  2478         # the closest integer to sqrt(c) with the even integer chosen
       
  2479         # in the case of a tie.
       
  2480         #
       
  2481         # To ensure correct rounding in all cases, we use the
       
  2482         # following trick: we compute the square root to an extra
       
  2483         # place (precision p+1 instead of precision p), rounding down.
       
  2484         # Then, if the result is inexact and its last digit is 0 or 5,
       
  2485         # we increase the last digit to 1 or 6 respectively; if it's
       
  2486         # exact we leave the last digit alone.  Now the final round to
       
  2487         # p places (or fewer in the case of underflow) will round
       
  2488         # correctly and raise the appropriate flags.
       
  2489 
       
  2490         # use an extra digit of precision
       
  2491         prec = context.prec+1
       
  2492 
       
  2493         # write argument in the form c*100**e where e = self._exp//2
       
  2494         # is the 'ideal' exponent, to be used if the square root is
       
  2495         # exactly representable.  l is the number of 'digits' of c in
       
  2496         # base 100, so that 100**(l-1) <= c < 100**l.
       
  2497         op = _WorkRep(self)
       
  2498         e = op.exp >> 1
       
  2499         if op.exp & 1:
       
  2500             c = op.int * 10
       
  2501             l = (len(self._int) >> 1) + 1
       
  2502         else:
       
  2503             c = op.int
       
  2504             l = len(self._int)+1 >> 1
       
  2505 
       
  2506         # rescale so that c has exactly prec base 100 'digits'
       
  2507         shift = prec-l
       
  2508         if shift >= 0:
       
  2509             c *= 100**shift
       
  2510             exact = True
       
  2511         else:
       
  2512             c, remainder = divmod(c, 100**-shift)
       
  2513             exact = not remainder
       
  2514         e -= shift
       
  2515 
       
  2516         # find n = floor(sqrt(c)) using Newton's method
       
  2517         n = 10**prec
       
  2518         while True:
       
  2519             q = c//n
       
  2520             if n <= q:
       
  2521                 break
       
  2522             else:
       
  2523                 n = n + q >> 1
       
  2524         exact = exact and n*n == c
       
  2525 
       
  2526         if exact:
       
  2527             # result is exact; rescale to use ideal exponent e
       
  2528             if shift >= 0:
       
  2529                 # assert n % 10**shift == 0
       
  2530                 n //= 10**shift
       
  2531             else:
       
  2532                 n *= 10**-shift
       
  2533             e += shift
       
  2534         else:
       
  2535             # result is not exact; fix last digit as described above
       
  2536             if n % 5 == 0:
       
  2537                 n += 1
       
  2538 
       
  2539         ans = _dec_from_triple(0, str(n), e)
       
  2540 
       
  2541         # round, and fit to current context
       
  2542         context = context._shallow_copy()
       
  2543         rounding = context._set_rounding(ROUND_HALF_EVEN)
       
  2544         ans = ans._fix(context)
       
  2545         context.rounding = rounding
       
  2546 
       
  2547         return ans
       
  2548 
       
  2549     def max(self, other, context=None):
       
  2550         """Returns the larger value.
       
  2551 
       
  2552         Like max(self, other) except if one is not a number, returns
       
  2553         NaN (and signals if one is sNaN).  Also rounds.
       
  2554         """
       
  2555         other = _convert_other(other, raiseit=True)
       
  2556 
       
  2557         if context is None:
       
  2558             context = getcontext()
       
  2559 
       
  2560         if self._is_special or other._is_special:
       
  2561             # If one operand is a quiet NaN and the other is number, then the
       
  2562             # number is always returned
       
  2563             sn = self._isnan()
       
  2564             on = other._isnan()
       
  2565             if sn or on:
       
  2566                 if on == 1 and sn != 2:
       
  2567                     return self._fix_nan(context)
       
  2568                 if sn == 1 and on != 2:
       
  2569                     return other._fix_nan(context)
       
  2570                 return self._check_nans(other, context)
       
  2571 
       
  2572         c = self._cmp(other)
       
  2573         if c == 0:
       
  2574             # If both operands are finite and equal in numerical value
       
  2575             # then an ordering is applied:
       
  2576             #
       
  2577             # If the signs differ then max returns the operand with the
       
  2578             # positive sign and min returns the operand with the negative sign
       
  2579             #
       
  2580             # If the signs are the same then the exponent is used to select
       
  2581             # the result.  This is exactly the ordering used in compare_total.
       
  2582             c = self.compare_total(other)
       
  2583 
       
  2584         if c == -1:
       
  2585             ans = other
       
  2586         else:
       
  2587             ans = self
       
  2588 
       
  2589         return ans._fix(context)
       
  2590 
       
  2591     def min(self, other, context=None):
       
  2592         """Returns the smaller value.
       
  2593 
       
  2594         Like min(self, other) except if one is not a number, returns
       
  2595         NaN (and signals if one is sNaN).  Also rounds.
       
  2596         """
       
  2597         other = _convert_other(other, raiseit=True)
       
  2598 
       
  2599         if context is None:
       
  2600             context = getcontext()
       
  2601 
       
  2602         if self._is_special or other._is_special:
       
  2603             # If one operand is a quiet NaN and the other is number, then the
       
  2604             # number is always returned
       
  2605             sn = self._isnan()
       
  2606             on = other._isnan()
       
  2607             if sn or on:
       
  2608                 if on == 1 and sn != 2:
       
  2609                     return self._fix_nan(context)
       
  2610                 if sn == 1 and on != 2:
       
  2611                     return other._fix_nan(context)
       
  2612                 return self._check_nans(other, context)
       
  2613 
       
  2614         c = self._cmp(other)
       
  2615         if c == 0:
       
  2616             c = self.compare_total(other)
       
  2617 
       
  2618         if c == -1:
       
  2619             ans = self
       
  2620         else:
       
  2621             ans = other
       
  2622 
       
  2623         return ans._fix(context)
       
  2624 
       
  2625     def _isinteger(self):
       
  2626         """Returns whether self is an integer"""
       
  2627         if self._is_special:
       
  2628             return False
       
  2629         if self._exp >= 0:
       
  2630             return True
       
  2631         rest = self._int[self._exp:]
       
  2632         return rest == '0'*len(rest)
       
  2633 
       
  2634     def _iseven(self):
       
  2635         """Returns True if self is even.  Assumes self is an integer."""
       
  2636         if not self or self._exp > 0:
       
  2637             return True
       
  2638         return self._int[-1+self._exp] in '02468'
       
  2639 
       
  2640     def adjusted(self):
       
  2641         """Return the adjusted exponent of self"""
       
  2642         try:
       
  2643             return self._exp + len(self._int) - 1
       
  2644         # If NaN or Infinity, self._exp is string
       
  2645         except TypeError:
       
  2646             return 0
       
  2647 
       
  2648     def canonical(self, context=None):
       
  2649         """Returns the same Decimal object.
       
  2650 
       
  2651         As we do not have different encodings for the same number, the
       
  2652         received object already is in its canonical form.
       
  2653         """
       
  2654         return self
       
  2655 
       
  2656     def compare_signal(self, other, context=None):
       
  2657         """Compares self to the other operand numerically.
       
  2658 
       
  2659         It's pretty much like compare(), but all NaNs signal, with signaling
       
  2660         NaNs taking precedence over quiet NaNs.
       
  2661         """
       
  2662         other = _convert_other(other, raiseit = True)
       
  2663         ans = self._compare_check_nans(other, context)
       
  2664         if ans:
       
  2665             return ans
       
  2666         return self.compare(other, context=context)
       
  2667 
       
  2668     def compare_total(self, other):
       
  2669         """Compares self to other using the abstract representations.
       
  2670 
       
  2671         This is not like the standard compare, which use their numerical
       
  2672         value. Note that a total ordering is defined for all possible abstract
       
  2673         representations.
       
  2674         """
       
  2675         # if one is negative and the other is positive, it's easy
       
  2676         if self._sign and not other._sign:
       
  2677             return Dec_n1
       
  2678         if not self._sign and other._sign:
       
  2679             return Dec_p1
       
  2680         sign = self._sign
       
  2681 
       
  2682         # let's handle both NaN types
       
  2683         self_nan = self._isnan()
       
  2684         other_nan = other._isnan()
       
  2685         if self_nan or other_nan:
       
  2686             if self_nan == other_nan:
       
  2687                 if self._int < other._int:
       
  2688                     if sign:
       
  2689                         return Dec_p1
       
  2690                     else:
       
  2691                         return Dec_n1
       
  2692                 if self._int > other._int:
       
  2693                     if sign:
       
  2694                         return Dec_n1
       
  2695                     else:
       
  2696                         return Dec_p1
       
  2697                 return Dec_0
       
  2698 
       
  2699             if sign:
       
  2700                 if self_nan == 1:
       
  2701                     return Dec_n1
       
  2702                 if other_nan == 1:
       
  2703                     return Dec_p1
       
  2704                 if self_nan == 2:
       
  2705                     return Dec_n1
       
  2706                 if other_nan == 2:
       
  2707                     return Dec_p1
       
  2708             else:
       
  2709                 if self_nan == 1:
       
  2710                     return Dec_p1
       
  2711                 if other_nan == 1:
       
  2712                     return Dec_n1
       
  2713                 if self_nan == 2:
       
  2714                     return Dec_p1
       
  2715                 if other_nan == 2:
       
  2716                     return Dec_n1
       
  2717 
       
  2718         if self < other:
       
  2719             return Dec_n1
       
  2720         if self > other:
       
  2721             return Dec_p1
       
  2722 
       
  2723         if self._exp < other._exp:
       
  2724             if sign:
       
  2725                 return Dec_p1
       
  2726             else:
       
  2727                 return Dec_n1
       
  2728         if self._exp > other._exp:
       
  2729             if sign:
       
  2730                 return Dec_n1
       
  2731             else:
       
  2732                 return Dec_p1
       
  2733         return Dec_0
       
  2734 
       
  2735 
       
  2736     def compare_total_mag(self, other):
       
  2737         """Compares self to other using abstract repr., ignoring sign.
       
  2738 
       
  2739         Like compare_total, but with operand's sign ignored and assumed to be 0.
       
  2740         """
       
  2741         s = self.copy_abs()
       
  2742         o = other.copy_abs()
       
  2743         return s.compare_total(o)
       
  2744 
       
  2745     def copy_abs(self):
       
  2746         """Returns a copy with the sign set to 0. """
       
  2747         return _dec_from_triple(0, self._int, self._exp, self._is_special)
       
  2748 
       
  2749     def copy_negate(self):
       
  2750         """Returns a copy with the sign inverted."""
       
  2751         if self._sign:
       
  2752             return _dec_from_triple(0, self._int, self._exp, self._is_special)
       
  2753         else:
       
  2754             return _dec_from_triple(1, self._int, self._exp, self._is_special)
       
  2755 
       
  2756     def copy_sign(self, other):
       
  2757         """Returns self with the sign of other."""
       
  2758         return _dec_from_triple(other._sign, self._int,
       
  2759                                 self._exp, self._is_special)
       
  2760 
       
  2761     def exp(self, context=None):
       
  2762         """Returns e ** self."""
       
  2763 
       
  2764         if context is None:
       
  2765             context = getcontext()
       
  2766 
       
  2767         # exp(NaN) = NaN
       
  2768         ans = self._check_nans(context=context)
       
  2769         if ans:
       
  2770             return ans
       
  2771 
       
  2772         # exp(-Infinity) = 0
       
  2773         if self._isinfinity() == -1:
       
  2774             return Dec_0
       
  2775 
       
  2776         # exp(0) = 1
       
  2777         if not self:
       
  2778             return Dec_p1
       
  2779 
       
  2780         # exp(Infinity) = Infinity
       
  2781         if self._isinfinity() == 1:
       
  2782             return Decimal(self)
       
  2783 
       
  2784         # the result is now guaranteed to be inexact (the true
       
  2785         # mathematical result is transcendental). There's no need to
       
  2786         # raise Rounded and Inexact here---they'll always be raised as
       
  2787         # a result of the call to _fix.
       
  2788         p = context.prec
       
  2789         adj = self.adjusted()
       
  2790 
       
  2791         # we only need to do any computation for quite a small range
       
  2792         # of adjusted exponents---for example, -29 <= adj <= 10 for
       
  2793         # the default context.  For smaller exponent the result is
       
  2794         # indistinguishable from 1 at the given precision, while for
       
  2795         # larger exponent the result either overflows or underflows.
       
  2796         if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
       
  2797             # overflow
       
  2798             ans = _dec_from_triple(0, '1', context.Emax+1)
       
  2799         elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
       
  2800             # underflow to 0
       
  2801             ans = _dec_from_triple(0, '1', context.Etiny()-1)
       
  2802         elif self._sign == 0 and adj < -p:
       
  2803             # p+1 digits; final round will raise correct flags
       
  2804             ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
       
  2805         elif self._sign == 1 and adj < -p-1:
       
  2806             # p+1 digits; final round will raise correct flags
       
  2807             ans = _dec_from_triple(0, '9'*(p+1), -p-1)
       
  2808         # general case
       
  2809         else:
       
  2810             op = _WorkRep(self)
       
  2811             c, e = op.int, op.exp
       
  2812             if op.sign == 1:
       
  2813                 c = -c
       
  2814 
       
  2815             # compute correctly rounded result: increase precision by
       
  2816             # 3 digits at a time until we get an unambiguously
       
  2817             # roundable result
       
  2818             extra = 3
       
  2819             while True:
       
  2820                 coeff, exp = _dexp(c, e, p+extra)
       
  2821                 if coeff % (5*10**(len(str(coeff))-p-1)):
       
  2822                     break
       
  2823                 extra += 3
       
  2824 
       
  2825             ans = _dec_from_triple(0, str(coeff), exp)
       
  2826 
       
  2827         # at this stage, ans should round correctly with *any*
       
  2828         # rounding mode, not just with ROUND_HALF_EVEN
       
  2829         context = context._shallow_copy()
       
  2830         rounding = context._set_rounding(ROUND_HALF_EVEN)
       
  2831         ans = ans._fix(context)
       
  2832         context.rounding = rounding
       
  2833 
       
  2834         return ans
       
  2835 
       
  2836     def is_canonical(self):
       
  2837         """Return True if self is canonical; otherwise return False.
       
  2838 
       
  2839         Currently, the encoding of a Decimal instance is always
       
  2840         canonical, so this method returns True for any Decimal.
       
  2841         """
       
  2842         return True
       
  2843 
       
  2844     def is_finite(self):
       
  2845         """Return True if self is finite; otherwise return False.
       
  2846 
       
  2847         A Decimal instance is considered finite if it is neither
       
  2848         infinite nor a NaN.
       
  2849         """
       
  2850         return not self._is_special
       
  2851 
       
  2852     def is_infinite(self):
       
  2853         """Return True if self is infinite; otherwise return False."""
       
  2854         return self._exp == 'F'
       
  2855 
       
  2856     def is_nan(self):
       
  2857         """Return True if self is a qNaN or sNaN; otherwise return False."""
       
  2858         return self._exp in ('n', 'N')
       
  2859 
       
  2860     def is_normal(self, context=None):
       
  2861         """Return True if self is a normal number; otherwise return False."""
       
  2862         if self._is_special or not self:
       
  2863             return False
       
  2864         if context is None:
       
  2865             context = getcontext()
       
  2866         return context.Emin <= self.adjusted() <= context.Emax
       
  2867 
       
  2868     def is_qnan(self):
       
  2869         """Return True if self is a quiet NaN; otherwise return False."""
       
  2870         return self._exp == 'n'
       
  2871 
       
  2872     def is_signed(self):
       
  2873         """Return True if self is negative; otherwise return False."""
       
  2874         return self._sign == 1
       
  2875 
       
  2876     def is_snan(self):
       
  2877         """Return True if self is a signaling NaN; otherwise return False."""
       
  2878         return self._exp == 'N'
       
  2879 
       
  2880     def is_subnormal(self, context=None):
       
  2881         """Return True if self is subnormal; otherwise return False."""
       
  2882         if self._is_special or not self:
       
  2883             return False
       
  2884         if context is None:
       
  2885             context = getcontext()
       
  2886         return self.adjusted() < context.Emin
       
  2887 
       
  2888     def is_zero(self):
       
  2889         """Return True if self is a zero; otherwise return False."""
       
  2890         return not self._is_special and self._int == '0'
       
  2891 
       
  2892     def _ln_exp_bound(self):
       
  2893         """Compute a lower bound for the adjusted exponent of self.ln().
       
  2894         In other words, compute r such that self.ln() >= 10**r.  Assumes
       
  2895         that self is finite and positive and that self != 1.
       
  2896         """
       
  2897 
       
  2898         # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
       
  2899         adj = self._exp + len(self._int) - 1
       
  2900         if adj >= 1:
       
  2901             # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
       
  2902             return len(str(adj*23//10)) - 1
       
  2903         if adj <= -2:
       
  2904             # argument <= 0.1
       
  2905             return len(str((-1-adj)*23//10)) - 1
       
  2906         op = _WorkRep(self)
       
  2907         c, e = op.int, op.exp
       
  2908         if adj == 0:
       
  2909             # 1 < self < 10
       
  2910             num = str(c-10**-e)
       
  2911             den = str(c)
       
  2912             return len(num) - len(den) - (num < den)
       
  2913         # adj == -1, 0.1 <= self < 1
       
  2914         return e + len(str(10**-e - c)) - 1
       
  2915 
       
  2916 
       
  2917     def ln(self, context=None):
       
  2918         """Returns the natural (base e) logarithm of self."""
       
  2919 
       
  2920         if context is None:
       
  2921             context = getcontext()
       
  2922 
       
  2923         # ln(NaN) = NaN
       
  2924         ans = self._check_nans(context=context)
       
  2925         if ans:
       
  2926             return ans
       
  2927 
       
  2928         # ln(0.0) == -Infinity
       
  2929         if not self:
       
  2930             return negInf
       
  2931 
       
  2932         # ln(Infinity) = Infinity
       
  2933         if self._isinfinity() == 1:
       
  2934             return Inf
       
  2935 
       
  2936         # ln(1.0) == 0.0
       
  2937         if self == Dec_p1:
       
  2938             return Dec_0
       
  2939 
       
  2940         # ln(negative) raises InvalidOperation
       
  2941         if self._sign == 1:
       
  2942             return context._raise_error(InvalidOperation,
       
  2943                                         'ln of a negative value')
       
  2944 
       
  2945         # result is irrational, so necessarily inexact
       
  2946         op = _WorkRep(self)
       
  2947         c, e = op.int, op.exp
       
  2948         p = context.prec
       
  2949 
       
  2950         # correctly rounded result: repeatedly increase precision by 3
       
  2951         # until we get an unambiguously roundable result
       
  2952         places = p - self._ln_exp_bound() + 2 # at least p+3 places
       
  2953         while True:
       
  2954             coeff = _dlog(c, e, places)
       
  2955             # assert len(str(abs(coeff)))-p >= 1
       
  2956             if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
       
  2957                 break
       
  2958             places += 3
       
  2959         ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
       
  2960 
       
  2961         context = context._shallow_copy()
       
  2962         rounding = context._set_rounding(ROUND_HALF_EVEN)
       
  2963         ans = ans._fix(context)
       
  2964         context.rounding = rounding
       
  2965         return ans
       
  2966 
       
  2967     def _log10_exp_bound(self):
       
  2968         """Compute a lower bound for the adjusted exponent of self.log10().
       
  2969         In other words, find r such that self.log10() >= 10**r.
       
  2970         Assumes that self is finite and positive and that self != 1.
       
  2971         """
       
  2972 
       
  2973         # For x >= 10 or x < 0.1 we only need a bound on the integer
       
  2974         # part of log10(self), and this comes directly from the
       
  2975         # exponent of x.  For 0.1 <= x <= 10 we use the inequalities
       
  2976         # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
       
  2977         # (1-1/x)/2.31 > 0.  If x < 1 then |log10(x)| > (1-x)/2.31 > 0
       
  2978 
       
  2979         adj = self._exp + len(self._int) - 1
       
  2980         if adj >= 1:
       
  2981             # self >= 10
       
  2982             return len(str(adj))-1
       
  2983         if adj <= -2:
       
  2984             # self < 0.1
       
  2985             return len(str(-1-adj))-1
       
  2986         op = _WorkRep(self)
       
  2987         c, e = op.int, op.exp
       
  2988         if adj == 0:
       
  2989             # 1 < self < 10
       
  2990             num = str(c-10**-e)
       
  2991             den = str(231*c)
       
  2992             return len(num) - len(den) - (num < den) + 2
       
  2993         # adj == -1, 0.1 <= self < 1
       
  2994         num = str(10**-e-c)
       
  2995         return len(num) + e - (num < "231") - 1
       
  2996 
       
  2997     def log10(self, context=None):
       
  2998         """Returns the base 10 logarithm of self."""
       
  2999 
       
  3000         if context is None:
       
  3001             context = getcontext()
       
  3002 
       
  3003         # log10(NaN) = NaN
       
  3004         ans = self._check_nans(context=context)
       
  3005         if ans:
       
  3006             return ans
       
  3007 
       
  3008         # log10(0.0) == -Infinity
       
  3009         if not self:
       
  3010             return negInf
       
  3011 
       
  3012         # log10(Infinity) = Infinity
       
  3013         if self._isinfinity() == 1:
       
  3014             return Inf
       
  3015 
       
  3016         # log10(negative or -Infinity) raises InvalidOperation
       
  3017         if self._sign == 1:
       
  3018             return context._raise_error(InvalidOperation,
       
  3019                                         'log10 of a negative value')
       
  3020 
       
  3021         # log10(10**n) = n
       
  3022         if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
       
  3023             # answer may need rounding
       
  3024             ans = Decimal(self._exp + len(self._int) - 1)
       
  3025         else:
       
  3026             # result is irrational, so necessarily inexact
       
  3027             op = _WorkRep(self)
       
  3028             c, e = op.int, op.exp
       
  3029             p = context.prec
       
  3030 
       
  3031             # correctly rounded result: repeatedly increase precision
       
  3032             # until result is unambiguously roundable
       
  3033             places = p-self._log10_exp_bound()+2
       
  3034             while True:
       
  3035                 coeff = _dlog10(c, e, places)
       
  3036                 # assert len(str(abs(coeff)))-p >= 1
       
  3037                 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
       
  3038                     break
       
  3039                 places += 3
       
  3040             ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
       
  3041 
       
  3042         context = context._shallow_copy()
       
  3043         rounding = context._set_rounding(ROUND_HALF_EVEN)
       
  3044         ans = ans._fix(context)
       
  3045         context.rounding = rounding
       
  3046         return ans
       
  3047 
       
  3048     def logb(self, context=None):
       
  3049         """ Returns the exponent of the magnitude of self's MSD.
       
  3050 
       
  3051         The result is the integer which is the exponent of the magnitude
       
  3052         of the most significant digit of self (as though it were truncated
       
  3053         to a single digit while maintaining the value of that digit and
       
  3054         without limiting the resulting exponent).
       
  3055         """
       
  3056         # logb(NaN) = NaN
       
  3057         ans = self._check_nans(context=context)
       
  3058         if ans:
       
  3059             return ans
       
  3060 
       
  3061         if context is None:
       
  3062             context = getcontext()
       
  3063 
       
  3064         # logb(+/-Inf) = +Inf
       
  3065         if self._isinfinity():
       
  3066             return Inf
       
  3067 
       
  3068         # logb(0) = -Inf, DivisionByZero
       
  3069         if not self:
       
  3070             return context._raise_error(DivisionByZero, 'logb(0)', 1)
       
  3071 
       
  3072         # otherwise, simply return the adjusted exponent of self, as a
       
  3073         # Decimal.  Note that no attempt is made to fit the result
       
  3074         # into the current context.
       
  3075         return Decimal(self.adjusted())
       
  3076 
       
  3077     def _islogical(self):
       
  3078         """Return True if self is a logical operand.
       
  3079 
       
  3080         For being logical, it must be a finite number with a sign of 0,
       
  3081         an exponent of 0, and a coefficient whose digits must all be
       
  3082         either 0 or 1.
       
  3083         """
       
  3084         if self._sign != 0 or self._exp != 0:
       
  3085             return False
       
  3086         for dig in self._int:
       
  3087             if dig not in '01':
       
  3088                 return False
       
  3089         return True
       
  3090 
       
  3091     def _fill_logical(self, context, opa, opb):
       
  3092         dif = context.prec - len(opa)
       
  3093         if dif > 0:
       
  3094             opa = '0'*dif + opa
       
  3095         elif dif < 0:
       
  3096             opa = opa[-context.prec:]
       
  3097         dif = context.prec - len(opb)
       
  3098         if dif > 0:
       
  3099             opb = '0'*dif + opb
       
  3100         elif dif < 0:
       
  3101             opb = opb[-context.prec:]
       
  3102         return opa, opb
       
  3103 
       
  3104     def logical_and(self, other, context=None):
       
  3105         """Applies an 'and' operation between self and other's digits."""
       
  3106         if context is None:
       
  3107             context = getcontext()
       
  3108         if not self._islogical() or not other._islogical():
       
  3109             return context._raise_error(InvalidOperation)
       
  3110 
       
  3111         # fill to context.prec
       
  3112         (opa, opb) = self._fill_logical(context, self._int, other._int)
       
  3113 
       
  3114         # make the operation, and clean starting zeroes
       
  3115         result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
       
  3116         return _dec_from_triple(0, result.lstrip('0') or '0', 0)
       
  3117 
       
  3118     def logical_invert(self, context=None):
       
  3119         """Invert all its digits."""
       
  3120         if context is None:
       
  3121             context = getcontext()
       
  3122         return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
       
  3123                                 context)
       
  3124 
       
  3125     def logical_or(self, other, context=None):
       
  3126         """Applies an 'or' operation between self and other's digits."""
       
  3127         if context is None:
       
  3128             context = getcontext()
       
  3129         if not self._islogical() or not other._islogical():
       
  3130             return context._raise_error(InvalidOperation)
       
  3131 
       
  3132         # fill to context.prec
       
  3133         (opa, opb) = self._fill_logical(context, self._int, other._int)
       
  3134 
       
  3135         # make the operation, and clean starting zeroes
       
  3136         result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
       
  3137         return _dec_from_triple(0, result.lstrip('0') or '0', 0)
       
  3138 
       
  3139     def logical_xor(self, other, context=None):
       
  3140         """Applies an 'xor' operation between self and other's digits."""
       
  3141         if context is None:
       
  3142             context = getcontext()
       
  3143         if not self._islogical() or not other._islogical():
       
  3144             return context._raise_error(InvalidOperation)
       
  3145 
       
  3146         # fill to context.prec
       
  3147         (opa, opb) = self._fill_logical(context, self._int, other._int)
       
  3148 
       
  3149         # make the operation, and clean starting zeroes
       
  3150         result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
       
  3151         return _dec_from_triple(0, result.lstrip('0') or '0', 0)
       
  3152 
       
  3153     def max_mag(self, other, context=None):
       
  3154         """Compares the values numerically with their sign ignored."""
       
  3155         other = _convert_other(other, raiseit=True)
       
  3156 
       
  3157         if context is None:
       
  3158             context = getcontext()
       
  3159 
       
  3160         if self._is_special or other._is_special:
       
  3161             # If one operand is a quiet NaN and the other is number, then the
       
  3162             # number is always returned
       
  3163             sn = self._isnan()
       
  3164             on = other._isnan()
       
  3165             if sn or on:
       
  3166                 if on == 1 and sn != 2:
       
  3167                     return self._fix_nan(context)
       
  3168                 if sn == 1 and on != 2:
       
  3169                     return other._fix_nan(context)
       
  3170                 return self._check_nans(other, context)
       
  3171 
       
  3172         c = self.copy_abs()._cmp(other.copy_abs())
       
  3173         if c == 0:
       
  3174             c = self.compare_total(other)
       
  3175 
       
  3176         if c == -1:
       
  3177             ans = other
       
  3178         else:
       
  3179             ans = self
       
  3180 
       
  3181         return ans._fix(context)
       
  3182 
       
  3183     def min_mag(self, other, context=None):
       
  3184         """Compares the values numerically with their sign ignored."""
       
  3185         other = _convert_other(other, raiseit=True)
       
  3186 
       
  3187         if context is None:
       
  3188             context = getcontext()
       
  3189 
       
  3190         if self._is_special or other._is_special:
       
  3191             # If one operand is a quiet NaN and the other is number, then the
       
  3192             # number is always returned
       
  3193             sn = self._isnan()
       
  3194             on = other._isnan()
       
  3195             if sn or on:
       
  3196                 if on == 1 and sn != 2:
       
  3197                     return self._fix_nan(context)
       
  3198                 if sn == 1 and on != 2:
       
  3199                     return other._fix_nan(context)
       
  3200                 return self._check_nans(other, context)
       
  3201 
       
  3202         c = self.copy_abs()._cmp(other.copy_abs())
       
  3203         if c == 0:
       
  3204             c = self.compare_total(other)
       
  3205 
       
  3206         if c == -1:
       
  3207             ans = self
       
  3208         else:
       
  3209             ans = other
       
  3210 
       
  3211         return ans._fix(context)
       
  3212 
       
  3213     def next_minus(self, context=None):
       
  3214         """Returns the largest representable number smaller than itself."""
       
  3215         if context is None:
       
  3216             context = getcontext()
       
  3217 
       
  3218         ans = self._check_nans(context=context)
       
  3219         if ans:
       
  3220             return ans
       
  3221 
       
  3222         if self._isinfinity() == -1:
       
  3223             return negInf
       
  3224         if self._isinfinity() == 1:
       
  3225             return _dec_from_triple(0, '9'*context.prec, context.Etop())
       
  3226 
       
  3227         context = context.copy()
       
  3228         context._set_rounding(ROUND_FLOOR)
       
  3229         context._ignore_all_flags()
       
  3230         new_self = self._fix(context)
       
  3231         if new_self != self:
       
  3232             return new_self
       
  3233         return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
       
  3234                             context)
       
  3235 
       
  3236     def next_plus(self, context=None):
       
  3237         """Returns the smallest representable number larger than itself."""
       
  3238         if context is None:
       
  3239             context = getcontext()
       
  3240 
       
  3241         ans = self._check_nans(context=context)
       
  3242         if ans:
       
  3243             return ans
       
  3244 
       
  3245         if self._isinfinity() == 1:
       
  3246             return Inf
       
  3247         if self._isinfinity() == -1:
       
  3248             return _dec_from_triple(1, '9'*context.prec, context.Etop())
       
  3249 
       
  3250         context = context.copy()
       
  3251         context._set_rounding(ROUND_CEILING)
       
  3252         context._ignore_all_flags()
       
  3253         new_self = self._fix(context)
       
  3254         if new_self != self:
       
  3255             return new_self
       
  3256         return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
       
  3257                             context)
       
  3258 
       
  3259     def next_toward(self, other, context=None):
       
  3260         """Returns the number closest to self, in the direction towards other.
       
  3261 
       
  3262         The result is the closest representable number to self
       
  3263         (excluding self) that is in the direction towards other,
       
  3264         unless both have the same value.  If the two operands are
       
  3265         numerically equal, then the result is a copy of self with the
       
  3266         sign set to be the same as the sign of other.
       
  3267         """
       
  3268         other = _convert_other(other, raiseit=True)
       
  3269 
       
  3270         if context is None:
       
  3271             context = getcontext()
       
  3272 
       
  3273         ans = self._check_nans(other, context)
       
  3274         if ans:
       
  3275             return ans
       
  3276 
       
  3277         comparison = self._cmp(other)
       
  3278         if comparison == 0:
       
  3279             return self.copy_sign(other)
       
  3280 
       
  3281         if comparison == -1:
       
  3282             ans = self.next_plus(context)
       
  3283         else: # comparison == 1
       
  3284             ans = self.next_minus(context)
       
  3285 
       
  3286         # decide which flags to raise using value of ans
       
  3287         if ans._isinfinity():
       
  3288             context._raise_error(Overflow,
       
  3289                                  'Infinite result from next_toward',
       
  3290                                  ans._sign)
       
  3291             context._raise_error(Rounded)
       
  3292             context._raise_error(Inexact)
       
  3293         elif ans.adjusted() < context.Emin:
       
  3294             context._raise_error(Underflow)
       
  3295             context._raise_error(Subnormal)
       
  3296             context._raise_error(Rounded)
       
  3297             context._raise_error(Inexact)
       
  3298             # if precision == 1 then we don't raise Clamped for a
       
  3299             # result 0E-Etiny.
       
  3300             if not ans:
       
  3301                 context._raise_error(Clamped)
       
  3302 
       
  3303         return ans
       
  3304 
       
  3305     def number_class(self, context=None):
       
  3306         """Returns an indication of the class of self.
       
  3307 
       
  3308         The class is one of the following strings:
       
  3309           sNaN
       
  3310           NaN
       
  3311           -Infinity
       
  3312           -Normal
       
  3313           -Subnormal
       
  3314           -Zero
       
  3315           +Zero
       
  3316           +Subnormal
       
  3317           +Normal
       
  3318           +Infinity
       
  3319         """
       
  3320         if self.is_snan():
       
  3321             return "sNaN"
       
  3322         if self.is_qnan():
       
  3323             return "NaN"
       
  3324         inf = self._isinfinity()
       
  3325         if inf == 1:
       
  3326             return "+Infinity"
       
  3327         if inf == -1:
       
  3328             return "-Infinity"
       
  3329         if self.is_zero():
       
  3330             if self._sign:
       
  3331                 return "-Zero"
       
  3332             else:
       
  3333                 return "+Zero"
       
  3334         if context is None:
       
  3335             context = getcontext()
       
  3336         if self.is_subnormal(context=context):
       
  3337             if self._sign:
       
  3338                 return "-Subnormal"
       
  3339             else:
       
  3340                 return "+Subnormal"
       
  3341         # just a normal, regular, boring number, :)
       
  3342         if self._sign:
       
  3343             return "-Normal"
       
  3344         else:
       
  3345             return "+Normal"
       
  3346 
       
  3347     def radix(self):
       
  3348         """Just returns 10, as this is Decimal, :)"""
       
  3349         return Decimal(10)
       
  3350 
       
  3351     def rotate(self, other, context=None):
       
  3352         """Returns a rotated copy of self, value-of-other times."""
       
  3353         if context is None:
       
  3354             context = getcontext()
       
  3355 
       
  3356         ans = self._check_nans(other, context)
       
  3357         if ans:
       
  3358             return ans
       
  3359 
       
  3360         if other._exp != 0:
       
  3361             return context._raise_error(InvalidOperation)
       
  3362         if not (-context.prec <= int(other) <= context.prec):
       
  3363             return context._raise_error(InvalidOperation)
       
  3364 
       
  3365         if self._isinfinity():
       
  3366             return Decimal(self)
       
  3367 
       
  3368         # get values, pad if necessary
       
  3369         torot = int(other)
       
  3370         rotdig = self._int
       
  3371         topad = context.prec - len(rotdig)
       
  3372         if topad:
       
  3373             rotdig = '0'*topad + rotdig
       
  3374 
       
  3375         # let's rotate!
       
  3376         rotated = rotdig[torot:] + rotdig[:torot]
       
  3377         return _dec_from_triple(self._sign,
       
  3378                                 rotated.lstrip('0') or '0', self._exp)
       
  3379 
       
  3380     def scaleb (self, other, context=None):
       
  3381         """Returns self operand after adding the second value to its exp."""
       
  3382         if context is None:
       
  3383             context = getcontext()
       
  3384 
       
  3385         ans = self._check_nans(other, context)
       
  3386         if ans:
       
  3387             return ans
       
  3388 
       
  3389         if other._exp != 0:
       
  3390             return context._raise_error(InvalidOperation)
       
  3391         liminf = -2 * (context.Emax + context.prec)
       
  3392         limsup =  2 * (context.Emax + context.prec)
       
  3393         if not (liminf <= int(other) <= limsup):
       
  3394             return context._raise_error(InvalidOperation)
       
  3395 
       
  3396         if self._isinfinity():
       
  3397             return Decimal(self)
       
  3398 
       
  3399         d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
       
  3400         d = d._fix(context)
       
  3401         return d
       
  3402 
       
  3403     def shift(self, other, context=None):
       
  3404         """Returns a shifted copy of self, value-of-other times."""
       
  3405         if context is None:
       
  3406             context = getcontext()
       
  3407 
       
  3408         ans = self._check_nans(other, context)
       
  3409         if ans:
       
  3410             return ans
       
  3411 
       
  3412         if other._exp != 0:
       
  3413             return context._raise_error(InvalidOperation)
       
  3414         if not (-context.prec <= int(other) <= context.prec):
       
  3415             return context._raise_error(InvalidOperation)
       
  3416 
       
  3417         if self._isinfinity():
       
  3418             return Decimal(self)
       
  3419 
       
  3420         # get values, pad if necessary
       
  3421         torot = int(other)
       
  3422         if not torot:
       
  3423             return Decimal(self)
       
  3424         rotdig = self._int
       
  3425         topad = context.prec - len(rotdig)
       
  3426         if topad:
       
  3427             rotdig = '0'*topad + rotdig
       
  3428 
       
  3429         # let's shift!
       
  3430         if torot < 0:
       
  3431             rotated = rotdig[:torot]
       
  3432         else:
       
  3433             rotated = rotdig + '0'*torot
       
  3434             rotated = rotated[-context.prec:]
       
  3435 
       
  3436         return _dec_from_triple(self._sign,
       
  3437                                     rotated.lstrip('0') or '0', self._exp)
       
  3438 
       
  3439     # Support for pickling, copy, and deepcopy
       
  3440     def __reduce__(self):
       
  3441         return (self.__class__, (str(self),))
       
  3442 
       
  3443     def __copy__(self):
       
  3444         if type(self) == Decimal:
       
  3445             return self     # I'm immutable; therefore I am my own clone
       
  3446         return self.__class__(str(self))
       
  3447 
       
  3448     def __deepcopy__(self, memo):
       
  3449         if type(self) == Decimal:
       
  3450             return self     # My components are also immutable
       
  3451         return self.__class__(str(self))
       
  3452 
       
  3453     # PEP 3101 support.  See also _parse_format_specifier and _format_align
       
  3454     def __format__(self, specifier, context=None):
       
  3455         """Format a Decimal instance according to the given specifier.
       
  3456 
       
  3457         The specifier should be a standard format specifier, with the
       
  3458         form described in PEP 3101.  Formatting types 'e', 'E', 'f',
       
  3459         'F', 'g', 'G', and '%' are supported.  If the formatting type
       
  3460         is omitted it defaults to 'g' or 'G', depending on the value
       
  3461         of context.capitals.
       
  3462 
       
  3463         At this time the 'n' format specifier type (which is supposed
       
  3464         to use the current locale) is not supported.
       
  3465         """
       
  3466 
       
  3467         # Note: PEP 3101 says that if the type is not present then
       
  3468         # there should be at least one digit after the decimal point.
       
  3469         # We take the liberty of ignoring this requirement for
       
  3470         # Decimal---it's presumably there to make sure that
       
  3471         # format(float, '') behaves similarly to str(float).
       
  3472         if context is None:
       
  3473             context = getcontext()
       
  3474 
       
  3475         spec = _parse_format_specifier(specifier)
       
  3476 
       
  3477         # special values don't care about the type or precision...
       
  3478         if self._is_special:
       
  3479             return _format_align(str(self), spec)
       
  3480 
       
  3481         # a type of None defaults to 'g' or 'G', depending on context
       
  3482         # if type is '%', adjust exponent of self accordingly
       
  3483         if spec['type'] is None:
       
  3484             spec['type'] = ['g', 'G'][context.capitals]
       
  3485         elif spec['type'] == '%':
       
  3486             self = _dec_from_triple(self._sign, self._int, self._exp+2)
       
  3487 
       
  3488         # round if necessary, taking rounding mode from the context
       
  3489         rounding = context.rounding
       
  3490         precision = spec['precision']
       
  3491         if precision is not None:
       
  3492             if spec['type'] in 'eE':
       
  3493                 self = self._round(precision+1, rounding)
       
  3494             elif spec['type'] in 'gG':
       
  3495                 if len(self._int) > precision:
       
  3496                     self = self._round(precision, rounding)
       
  3497             elif spec['type'] in 'fF%':
       
  3498                 self = self._rescale(-precision, rounding)
       
  3499         # special case: zeros with a positive exponent can't be
       
  3500         # represented in fixed point; rescale them to 0e0.
       
  3501         elif not self and self._exp > 0 and spec['type'] in 'fF%':
       
  3502             self = self._rescale(0, rounding)
       
  3503 
       
  3504         # figure out placement of the decimal point
       
  3505         leftdigits = self._exp + len(self._int)
       
  3506         if spec['type'] in 'fF%':
       
  3507             dotplace = leftdigits
       
  3508         elif spec['type'] in 'eE':
       
  3509             if not self and precision is not None:
       
  3510                 dotplace = 1 - precision
       
  3511             else:
       
  3512                 dotplace = 1
       
  3513         elif spec['type'] in 'gG':
       
  3514             if self._exp <= 0 and leftdigits > -6:
       
  3515                 dotplace = leftdigits
       
  3516             else:
       
  3517                 dotplace = 1
       
  3518 
       
  3519         # figure out main part of numeric string...
       
  3520         if dotplace <= 0:
       
  3521             num = '0.' + '0'*(-dotplace) + self._int
       
  3522         elif dotplace >= len(self._int):
       
  3523             # make sure we're not padding a '0' with extra zeros on the right
       
  3524             assert dotplace==len(self._int) or self._int != '0'
       
  3525             num = self._int + '0'*(dotplace-len(self._int))
       
  3526         else:
       
  3527             num = self._int[:dotplace] + '.' + self._int[dotplace:]
       
  3528 
       
  3529         # ...then the trailing exponent, or trailing '%'
       
  3530         if leftdigits != dotplace or spec['type'] in 'eE':
       
  3531             echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
       
  3532             num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
       
  3533         elif spec['type'] == '%':
       
  3534             num = num + '%'
       
  3535 
       
  3536         # add sign
       
  3537         if self._sign == 1:
       
  3538             num = '-' + num
       
  3539         return _format_align(num, spec)
       
  3540 
       
  3541 
       
  3542 def _dec_from_triple(sign, coefficient, exponent, special=False):
       
  3543     """Create a decimal instance directly, without any validation,
       
  3544     normalization (e.g. removal of leading zeros) or argument
       
  3545     conversion.
       
  3546 
       
  3547     This function is for *internal use only*.
       
  3548     """
       
  3549 
       
  3550     self = object.__new__(Decimal)
       
  3551     self._sign = sign
       
  3552     self._int = coefficient
       
  3553     self._exp = exponent
       
  3554     self._is_special = special
       
  3555 
       
  3556     return self
       
  3557 
       
  3558 ##### Context class #######################################################
       
  3559 
       
  3560 
       
  3561 # get rounding method function:
       
  3562 rounding_functions = [name for name in Decimal.__dict__.keys()
       
  3563                                     if name.startswith('_round_')]
       
  3564 for name in rounding_functions:
       
  3565     # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
       
  3566     globalname = name[1:].upper()
       
  3567     val = globals()[globalname]
       
  3568     Decimal._pick_rounding_function[val] = name
       
  3569 
       
  3570 del name, val, globalname, rounding_functions
       
  3571 
       
  3572 class _ContextManager(object):
       
  3573     """Context manager class to support localcontext().
       
  3574 
       
  3575       Sets a copy of the supplied context in __enter__() and restores
       
  3576       the previous decimal context in __exit__()
       
  3577     """
       
  3578     def __init__(self, new_context):
       
  3579         self.new_context = new_context.copy()
       
  3580     def __enter__(self):
       
  3581         self.saved_context = getcontext()
       
  3582         setcontext(self.new_context)
       
  3583         return self.new_context
       
  3584     def __exit__(self, t, v, tb):
       
  3585         setcontext(self.saved_context)
       
  3586 
       
  3587 class Context(object):
       
  3588     """Contains the context for a Decimal instance.
       
  3589 
       
  3590     Contains:
       
  3591     prec - precision (for use in rounding, division, square roots..)
       
  3592     rounding - rounding type (how you round)
       
  3593     traps - If traps[exception] = 1, then the exception is
       
  3594                     raised when it is caused.  Otherwise, a value is
       
  3595                     substituted in.
       
  3596     flags  - When an exception is caused, flags[exception] is set.
       
  3597              (Whether or not the trap_enabler is set)
       
  3598              Should be reset by user of Decimal instance.
       
  3599     Emin -   Minimum exponent
       
  3600     Emax -   Maximum exponent
       
  3601     capitals -      If 1, 1*10^1 is printed as 1E+1.
       
  3602                     If 0, printed as 1e1
       
  3603     _clamp - If 1, change exponents if too high (Default 0)
       
  3604     """
       
  3605 
       
  3606     def __init__(self, prec=None, rounding=None,
       
  3607                  traps=None, flags=None,
       
  3608                  Emin=None, Emax=None,
       
  3609                  capitals=None, _clamp=0,
       
  3610                  _ignored_flags=None):
       
  3611         if flags is None:
       
  3612             flags = []
       
  3613         if _ignored_flags is None:
       
  3614             _ignored_flags = []
       
  3615         if not isinstance(flags, dict):
       
  3616             flags = dict([(s, int(s in flags)) for s in _signals])
       
  3617             del s
       
  3618         if traps is not None and not isinstance(traps, dict):
       
  3619             traps = dict([(s, int(s in traps)) for s in _signals])
       
  3620             del s
       
  3621         for name, val in locals().items():
       
  3622             if val is None:
       
  3623                 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
       
  3624             else:
       
  3625                 setattr(self, name, val)
       
  3626         del self.self
       
  3627 
       
  3628     def __repr__(self):
       
  3629         """Show the current context."""
       
  3630         s = []
       
  3631         s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
       
  3632                  'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
       
  3633                  % vars(self))
       
  3634         names = [f.__name__ for f, v in self.flags.items() if v]
       
  3635         s.append('flags=[' + ', '.join(names) + ']')
       
  3636         names = [t.__name__ for t, v in self.traps.items() if v]
       
  3637         s.append('traps=[' + ', '.join(names) + ']')
       
  3638         return ', '.join(s) + ')'
       
  3639 
       
  3640     def clear_flags(self):
       
  3641         """Reset all flags to zero"""
       
  3642         for flag in self.flags:
       
  3643             self.flags[flag] = 0
       
  3644 
       
  3645     def _shallow_copy(self):
       
  3646         """Returns a shallow copy from self."""
       
  3647         nc = Context(self.prec, self.rounding, self.traps,
       
  3648                      self.flags, self.Emin, self.Emax,
       
  3649                      self.capitals, self._clamp, self._ignored_flags)
       
  3650         return nc
       
  3651 
       
  3652     def copy(self):
       
  3653         """Returns a deep copy from self."""
       
  3654         nc = Context(self.prec, self.rounding, self.traps.copy(),
       
  3655                      self.flags.copy(), self.Emin, self.Emax,
       
  3656                      self.capitals, self._clamp, self._ignored_flags)
       
  3657         return nc
       
  3658     __copy__ = copy
       
  3659 
       
  3660     def _raise_error(self, condition, explanation = None, *args):
       
  3661         """Handles an error
       
  3662 
       
  3663         If the flag is in _ignored_flags, returns the default response.
       
  3664         Otherwise, it sets the flag, then, if the corresponding
       
  3665         trap_enabler is set, it reaises the exception.  Otherwise, it returns
       
  3666         the default value after setting the flag.
       
  3667         """
       
  3668         error = _condition_map.get(condition, condition)
       
  3669         if error in self._ignored_flags:
       
  3670             # Don't touch the flag
       
  3671             return error().handle(self, *args)
       
  3672 
       
  3673         self.flags[error] = 1
       
  3674         if not self.traps[error]:
       
  3675             # The errors define how to handle themselves.
       
  3676             return condition().handle(self, *args)
       
  3677 
       
  3678         # Errors should only be risked on copies of the context
       
  3679         # self._ignored_flags = []
       
  3680         raise error(explanation)
       
  3681 
       
  3682     def _ignore_all_flags(self):
       
  3683         """Ignore all flags, if they are raised"""
       
  3684         return self._ignore_flags(*_signals)
       
  3685 
       
  3686     def _ignore_flags(self, *flags):
       
  3687         """Ignore the flags, if they are raised"""
       
  3688         # Do not mutate-- This way, copies of a context leave the original
       
  3689         # alone.
       
  3690         self._ignored_flags = (self._ignored_flags + list(flags))
       
  3691         return list(flags)
       
  3692 
       
  3693     def _regard_flags(self, *flags):
       
  3694         """Stop ignoring the flags, if they are raised"""
       
  3695         if flags and isinstance(flags[0], (tuple,list)):
       
  3696             flags = flags[0]
       
  3697         for flag in flags:
       
  3698             self._ignored_flags.remove(flag)
       
  3699 
       
  3700     # We inherit object.__hash__, so we must deny this explicitly
       
  3701     __hash__ = None
       
  3702 
       
  3703     def Etiny(self):
       
  3704         """Returns Etiny (= Emin - prec + 1)"""
       
  3705         return int(self.Emin - self.prec + 1)
       
  3706 
       
  3707     def Etop(self):
       
  3708         """Returns maximum exponent (= Emax - prec + 1)"""
       
  3709         return int(self.Emax - self.prec + 1)
       
  3710 
       
  3711     def _set_rounding(self, type):
       
  3712         """Sets the rounding type.
       
  3713 
       
  3714         Sets the rounding type, and returns the current (previous)
       
  3715         rounding type.  Often used like:
       
  3716 
       
  3717         context = context.copy()
       
  3718         # so you don't change the calling context
       
  3719         # if an error occurs in the middle.
       
  3720         rounding = context._set_rounding(ROUND_UP)
       
  3721         val = self.__sub__(other, context=context)
       
  3722         context._set_rounding(rounding)
       
  3723 
       
  3724         This will make it round up for that operation.
       
  3725         """
       
  3726         rounding = self.rounding
       
  3727         self.rounding= type
       
  3728         return rounding
       
  3729 
       
  3730     def create_decimal(self, num='0'):
       
  3731         """Creates a new Decimal instance but using self as context.
       
  3732 
       
  3733         This method implements the to-number operation of the
       
  3734         IBM Decimal specification."""
       
  3735 
       
  3736         if isinstance(num, basestring) and num != num.strip():
       
  3737             return self._raise_error(ConversionSyntax,
       
  3738                                      "no trailing or leading whitespace is "
       
  3739                                      "permitted.")
       
  3740 
       
  3741         d = Decimal(num, context=self)
       
  3742         if d._isnan() and len(d._int) > self.prec - self._clamp:
       
  3743             return self._raise_error(ConversionSyntax,
       
  3744                                      "diagnostic info too long in NaN")
       
  3745         return d._fix(self)
       
  3746 
       
  3747     # Methods
       
  3748     def abs(self, a):
       
  3749         """Returns the absolute value of the operand.
       
  3750 
       
  3751         If the operand is negative, the result is the same as using the minus
       
  3752         operation on the operand.  Otherwise, the result is the same as using
       
  3753         the plus operation on the operand.
       
  3754 
       
  3755         >>> ExtendedContext.abs(Decimal('2.1'))
       
  3756         Decimal('2.1')
       
  3757         >>> ExtendedContext.abs(Decimal('-100'))
       
  3758         Decimal('100')
       
  3759         >>> ExtendedContext.abs(Decimal('101.5'))
       
  3760         Decimal('101.5')
       
  3761         >>> ExtendedContext.abs(Decimal('-101.5'))
       
  3762         Decimal('101.5')
       
  3763         """
       
  3764         return a.__abs__(context=self)
       
  3765 
       
  3766     def add(self, a, b):
       
  3767         """Return the sum of the two operands.
       
  3768 
       
  3769         >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
       
  3770         Decimal('19.00')
       
  3771         >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
       
  3772         Decimal('1.02E+4')
       
  3773         """
       
  3774         return a.__add__(b, context=self)
       
  3775 
       
  3776     def _apply(self, a):
       
  3777         return str(a._fix(self))
       
  3778 
       
  3779     def canonical(self, a):
       
  3780         """Returns the same Decimal object.
       
  3781 
       
  3782         As we do not have different encodings for the same number, the
       
  3783         received object already is in its canonical form.
       
  3784 
       
  3785         >>> ExtendedContext.canonical(Decimal('2.50'))
       
  3786         Decimal('2.50')
       
  3787         """
       
  3788         return a.canonical(context=self)
       
  3789 
       
  3790     def compare(self, a, b):
       
  3791         """Compares values numerically.
       
  3792 
       
  3793         If the signs of the operands differ, a value representing each operand
       
  3794         ('-1' if the operand is less than zero, '0' if the operand is zero or
       
  3795         negative zero, or '1' if the operand is greater than zero) is used in
       
  3796         place of that operand for the comparison instead of the actual
       
  3797         operand.
       
  3798 
       
  3799         The comparison is then effected by subtracting the second operand from
       
  3800         the first and then returning a value according to the result of the
       
  3801         subtraction: '-1' if the result is less than zero, '0' if the result is
       
  3802         zero or negative zero, or '1' if the result is greater than zero.
       
  3803 
       
  3804         >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
       
  3805         Decimal('-1')
       
  3806         >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
       
  3807         Decimal('0')
       
  3808         >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
       
  3809         Decimal('0')
       
  3810         >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
       
  3811         Decimal('1')
       
  3812         >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
       
  3813         Decimal('1')
       
  3814         >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
       
  3815         Decimal('-1')
       
  3816         """
       
  3817         return a.compare(b, context=self)
       
  3818 
       
  3819     def compare_signal(self, a, b):
       
  3820         """Compares the values of the two operands numerically.
       
  3821 
       
  3822         It's pretty much like compare(), but all NaNs signal, with signaling
       
  3823         NaNs taking precedence over quiet NaNs.
       
  3824 
       
  3825         >>> c = ExtendedContext
       
  3826         >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
       
  3827         Decimal('-1')
       
  3828         >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
       
  3829         Decimal('0')
       
  3830         >>> c.flags[InvalidOperation] = 0
       
  3831         >>> print c.flags[InvalidOperation]
       
  3832         0
       
  3833         >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
       
  3834         Decimal('NaN')
       
  3835         >>> print c.flags[InvalidOperation]
       
  3836         1
       
  3837         >>> c.flags[InvalidOperation] = 0
       
  3838         >>> print c.flags[InvalidOperation]
       
  3839         0
       
  3840         >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
       
  3841         Decimal('NaN')
       
  3842         >>> print c.flags[InvalidOperation]
       
  3843         1
       
  3844         """
       
  3845         return a.compare_signal(b, context=self)
       
  3846 
       
  3847     def compare_total(self, a, b):
       
  3848         """Compares two operands using their abstract representation.
       
  3849 
       
  3850         This is not like the standard compare, which use their numerical
       
  3851         value. Note that a total ordering is defined for all possible abstract
       
  3852         representations.
       
  3853 
       
  3854         >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
       
  3855         Decimal('-1')
       
  3856         >>> ExtendedContext.compare_total(Decimal('-127'),  Decimal('12'))
       
  3857         Decimal('-1')
       
  3858         >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
       
  3859         Decimal('-1')
       
  3860         >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
       
  3861         Decimal('0')
       
  3862         >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('12.300'))
       
  3863         Decimal('1')
       
  3864         >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('NaN'))
       
  3865         Decimal('-1')
       
  3866         """
       
  3867         return a.compare_total(b)
       
  3868 
       
  3869     def compare_total_mag(self, a, b):
       
  3870         """Compares two operands using their abstract representation ignoring sign.
       
  3871 
       
  3872         Like compare_total, but with operand's sign ignored and assumed to be 0.
       
  3873         """
       
  3874         return a.compare_total_mag(b)
       
  3875 
       
  3876     def copy_abs(self, a):
       
  3877         """Returns a copy of the operand with the sign set to 0.
       
  3878 
       
  3879         >>> ExtendedContext.copy_abs(Decimal('2.1'))
       
  3880         Decimal('2.1')
       
  3881         >>> ExtendedContext.copy_abs(Decimal('-100'))
       
  3882         Decimal('100')
       
  3883         """
       
  3884         return a.copy_abs()
       
  3885 
       
  3886     def copy_decimal(self, a):
       
  3887         """Returns a copy of the decimal objet.
       
  3888 
       
  3889         >>> ExtendedContext.copy_decimal(Decimal('2.1'))
       
  3890         Decimal('2.1')
       
  3891         >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
       
  3892         Decimal('-1.00')
       
  3893         """
       
  3894         return Decimal(a)
       
  3895 
       
  3896     def copy_negate(self, a):
       
  3897         """Returns a copy of the operand with the sign inverted.
       
  3898 
       
  3899         >>> ExtendedContext.copy_negate(Decimal('101.5'))
       
  3900         Decimal('-101.5')
       
  3901         >>> ExtendedContext.copy_negate(Decimal('-101.5'))
       
  3902         Decimal('101.5')
       
  3903         """
       
  3904         return a.copy_negate()
       
  3905 
       
  3906     def copy_sign(self, a, b):
       
  3907         """Copies the second operand's sign to the first one.
       
  3908 
       
  3909         In detail, it returns a copy of the first operand with the sign
       
  3910         equal to the sign of the second operand.
       
  3911 
       
  3912         >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
       
  3913         Decimal('1.50')
       
  3914         >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
       
  3915         Decimal('1.50')
       
  3916         >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
       
  3917         Decimal('-1.50')
       
  3918         >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
       
  3919         Decimal('-1.50')
       
  3920         """
       
  3921         return a.copy_sign(b)
       
  3922 
       
  3923     def divide(self, a, b):
       
  3924         """Decimal division in a specified context.
       
  3925 
       
  3926         >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
       
  3927         Decimal('0.333333333')
       
  3928         >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
       
  3929         Decimal('0.666666667')
       
  3930         >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
       
  3931         Decimal('2.5')
       
  3932         >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
       
  3933         Decimal('0.1')
       
  3934         >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
       
  3935         Decimal('1')
       
  3936         >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
       
  3937         Decimal('4.00')
       
  3938         >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
       
  3939         Decimal('1.20')
       
  3940         >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
       
  3941         Decimal('10')
       
  3942         >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
       
  3943         Decimal('1000')
       
  3944         >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
       
  3945         Decimal('1.20E+6')
       
  3946         """
       
  3947         return a.__div__(b, context=self)
       
  3948 
       
  3949     def divide_int(self, a, b):
       
  3950         """Divides two numbers and returns the integer part of the result.
       
  3951 
       
  3952         >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
       
  3953         Decimal('0')
       
  3954         >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
       
  3955         Decimal('3')
       
  3956         >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
       
  3957         Decimal('3')
       
  3958         """
       
  3959         return a.__floordiv__(b, context=self)
       
  3960 
       
  3961     def divmod(self, a, b):
       
  3962         return a.__divmod__(b, context=self)
       
  3963 
       
  3964     def exp(self, a):
       
  3965         """Returns e ** a.
       
  3966 
       
  3967         >>> c = ExtendedContext.copy()
       
  3968         >>> c.Emin = -999
       
  3969         >>> c.Emax = 999
       
  3970         >>> c.exp(Decimal('-Infinity'))
       
  3971         Decimal('0')
       
  3972         >>> c.exp(Decimal('-1'))
       
  3973         Decimal('0.367879441')
       
  3974         >>> c.exp(Decimal('0'))
       
  3975         Decimal('1')
       
  3976         >>> c.exp(Decimal('1'))
       
  3977         Decimal('2.71828183')
       
  3978         >>> c.exp(Decimal('0.693147181'))
       
  3979         Decimal('2.00000000')
       
  3980         >>> c.exp(Decimal('+Infinity'))
       
  3981         Decimal('Infinity')
       
  3982         """
       
  3983         return a.exp(context=self)
       
  3984 
       
  3985     def fma(self, a, b, c):
       
  3986         """Returns a multiplied by b, plus c.
       
  3987 
       
  3988         The first two operands are multiplied together, using multiply,
       
  3989         the third operand is then added to the result of that
       
  3990         multiplication, using add, all with only one final rounding.
       
  3991 
       
  3992         >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
       
  3993         Decimal('22')
       
  3994         >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
       
  3995         Decimal('-8')
       
  3996         >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
       
  3997         Decimal('1.38435736E+12')
       
  3998         """
       
  3999         return a.fma(b, c, context=self)
       
  4000 
       
  4001     def is_canonical(self, a):
       
  4002         """Return True if the operand is canonical; otherwise return False.
       
  4003 
       
  4004         Currently, the encoding of a Decimal instance is always
       
  4005         canonical, so this method returns True for any Decimal.
       
  4006 
       
  4007         >>> ExtendedContext.is_canonical(Decimal('2.50'))
       
  4008         True
       
  4009         """
       
  4010         return a.is_canonical()
       
  4011 
       
  4012     def is_finite(self, a):
       
  4013         """Return True if the operand is finite; otherwise return False.
       
  4014 
       
  4015         A Decimal instance is considered finite if it is neither
       
  4016         infinite nor a NaN.
       
  4017 
       
  4018         >>> ExtendedContext.is_finite(Decimal('2.50'))
       
  4019         True
       
  4020         >>> ExtendedContext.is_finite(Decimal('-0.3'))
       
  4021         True
       
  4022         >>> ExtendedContext.is_finite(Decimal('0'))
       
  4023         True
       
  4024         >>> ExtendedContext.is_finite(Decimal('Inf'))
       
  4025         False
       
  4026         >>> ExtendedContext.is_finite(Decimal('NaN'))
       
  4027         False
       
  4028         """
       
  4029         return a.is_finite()
       
  4030 
       
  4031     def is_infinite(self, a):
       
  4032         """Return True if the operand is infinite; otherwise return False.
       
  4033 
       
  4034         >>> ExtendedContext.is_infinite(Decimal('2.50'))
       
  4035         False
       
  4036         >>> ExtendedContext.is_infinite(Decimal('-Inf'))
       
  4037         True
       
  4038         >>> ExtendedContext.is_infinite(Decimal('NaN'))
       
  4039         False
       
  4040         """
       
  4041         return a.is_infinite()
       
  4042 
       
  4043     def is_nan(self, a):
       
  4044         """Return True if the operand is a qNaN or sNaN;
       
  4045         otherwise return False.
       
  4046 
       
  4047         >>> ExtendedContext.is_nan(Decimal('2.50'))
       
  4048         False
       
  4049         >>> ExtendedContext.is_nan(Decimal('NaN'))
       
  4050         True
       
  4051         >>> ExtendedContext.is_nan(Decimal('-sNaN'))
       
  4052         True
       
  4053         """
       
  4054         return a.is_nan()
       
  4055 
       
  4056     def is_normal(self, a):
       
  4057         """Return True if the operand is a normal number;
       
  4058         otherwise return False.
       
  4059 
       
  4060         >>> c = ExtendedContext.copy()
       
  4061         >>> c.Emin = -999
       
  4062         >>> c.Emax = 999
       
  4063         >>> c.is_normal(Decimal('2.50'))
       
  4064         True
       
  4065         >>> c.is_normal(Decimal('0.1E-999'))
       
  4066         False
       
  4067         >>> c.is_normal(Decimal('0.00'))
       
  4068         False
       
  4069         >>> c.is_normal(Decimal('-Inf'))
       
  4070         False
       
  4071         >>> c.is_normal(Decimal('NaN'))
       
  4072         False
       
  4073         """
       
  4074         return a.is_normal(context=self)
       
  4075 
       
  4076     def is_qnan(self, a):
       
  4077         """Return True if the operand is a quiet NaN; otherwise return False.
       
  4078 
       
  4079         >>> ExtendedContext.is_qnan(Decimal('2.50'))
       
  4080         False
       
  4081         >>> ExtendedContext.is_qnan(Decimal('NaN'))
       
  4082         True
       
  4083         >>> ExtendedContext.is_qnan(Decimal('sNaN'))
       
  4084         False
       
  4085         """
       
  4086         return a.is_qnan()
       
  4087 
       
  4088     def is_signed(self, a):
       
  4089         """Return True if the operand is negative; otherwise return False.
       
  4090 
       
  4091         >>> ExtendedContext.is_signed(Decimal('2.50'))
       
  4092         False
       
  4093         >>> ExtendedContext.is_signed(Decimal('-12'))
       
  4094         True
       
  4095         >>> ExtendedContext.is_signed(Decimal('-0'))
       
  4096         True
       
  4097         """
       
  4098         return a.is_signed()
       
  4099 
       
  4100     def is_snan(self, a):
       
  4101         """Return True if the operand is a signaling NaN;
       
  4102         otherwise return False.
       
  4103 
       
  4104         >>> ExtendedContext.is_snan(Decimal('2.50'))
       
  4105         False
       
  4106         >>> ExtendedContext.is_snan(Decimal('NaN'))
       
  4107         False
       
  4108         >>> ExtendedContext.is_snan(Decimal('sNaN'))
       
  4109         True
       
  4110         """
       
  4111         return a.is_snan()
       
  4112 
       
  4113     def is_subnormal(self, a):
       
  4114         """Return True if the operand is subnormal; otherwise return False.
       
  4115 
       
  4116         >>> c = ExtendedContext.copy()
       
  4117         >>> c.Emin = -999
       
  4118         >>> c.Emax = 999
       
  4119         >>> c.is_subnormal(Decimal('2.50'))
       
  4120         False
       
  4121         >>> c.is_subnormal(Decimal('0.1E-999'))
       
  4122         True
       
  4123         >>> c.is_subnormal(Decimal('0.00'))
       
  4124         False
       
  4125         >>> c.is_subnormal(Decimal('-Inf'))
       
  4126         False
       
  4127         >>> c.is_subnormal(Decimal('NaN'))
       
  4128         False
       
  4129         """
       
  4130         return a.is_subnormal(context=self)
       
  4131 
       
  4132     def is_zero(self, a):
       
  4133         """Return True if the operand is a zero; otherwise return False.
       
  4134 
       
  4135         >>> ExtendedContext.is_zero(Decimal('0'))
       
  4136         True
       
  4137         >>> ExtendedContext.is_zero(Decimal('2.50'))
       
  4138         False
       
  4139         >>> ExtendedContext.is_zero(Decimal('-0E+2'))
       
  4140         True
       
  4141         """
       
  4142         return a.is_zero()
       
  4143 
       
  4144     def ln(self, a):
       
  4145         """Returns the natural (base e) logarithm of the operand.
       
  4146 
       
  4147         >>> c = ExtendedContext.copy()
       
  4148         >>> c.Emin = -999
       
  4149         >>> c.Emax = 999
       
  4150         >>> c.ln(Decimal('0'))
       
  4151         Decimal('-Infinity')
       
  4152         >>> c.ln(Decimal('1.000'))
       
  4153         Decimal('0')
       
  4154         >>> c.ln(Decimal('2.71828183'))
       
  4155         Decimal('1.00000000')
       
  4156         >>> c.ln(Decimal('10'))
       
  4157         Decimal('2.30258509')
       
  4158         >>> c.ln(Decimal('+Infinity'))
       
  4159         Decimal('Infinity')
       
  4160         """
       
  4161         return a.ln(context=self)
       
  4162 
       
  4163     def log10(self, a):
       
  4164         """Returns the base 10 logarithm of the operand.
       
  4165 
       
  4166         >>> c = ExtendedContext.copy()
       
  4167         >>> c.Emin = -999
       
  4168         >>> c.Emax = 999
       
  4169         >>> c.log10(Decimal('0'))
       
  4170         Decimal('-Infinity')
       
  4171         >>> c.log10(Decimal('0.001'))
       
  4172         Decimal('-3')
       
  4173         >>> c.log10(Decimal('1.000'))
       
  4174         Decimal('0')
       
  4175         >>> c.log10(Decimal('2'))
       
  4176         Decimal('0.301029996')
       
  4177         >>> c.log10(Decimal('10'))
       
  4178         Decimal('1')
       
  4179         >>> c.log10(Decimal('70'))
       
  4180         Decimal('1.84509804')
       
  4181         >>> c.log10(Decimal('+Infinity'))
       
  4182         Decimal('Infinity')
       
  4183         """
       
  4184         return a.log10(context=self)
       
  4185 
       
  4186     def logb(self, a):
       
  4187         """ Returns the exponent of the magnitude of the operand's MSD.
       
  4188 
       
  4189         The result is the integer which is the exponent of the magnitude
       
  4190         of the most significant digit of the operand (as though the
       
  4191         operand were truncated to a single digit while maintaining the
       
  4192         value of that digit and without limiting the resulting exponent).
       
  4193 
       
  4194         >>> ExtendedContext.logb(Decimal('250'))
       
  4195         Decimal('2')
       
  4196         >>> ExtendedContext.logb(Decimal('2.50'))
       
  4197         Decimal('0')
       
  4198         >>> ExtendedContext.logb(Decimal('0.03'))
       
  4199         Decimal('-2')
       
  4200         >>> ExtendedContext.logb(Decimal('0'))
       
  4201         Decimal('-Infinity')
       
  4202         """
       
  4203         return a.logb(context=self)
       
  4204 
       
  4205     def logical_and(self, a, b):
       
  4206         """Applies the logical operation 'and' between each operand's digits.
       
  4207 
       
  4208         The operands must be both logical numbers.
       
  4209 
       
  4210         >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
       
  4211         Decimal('0')
       
  4212         >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
       
  4213         Decimal('0')
       
  4214         >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
       
  4215         Decimal('0')
       
  4216         >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
       
  4217         Decimal('1')
       
  4218         >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
       
  4219         Decimal('1000')
       
  4220         >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
       
  4221         Decimal('10')
       
  4222         """
       
  4223         return a.logical_and(b, context=self)
       
  4224 
       
  4225     def logical_invert(self, a):
       
  4226         """Invert all the digits in the operand.
       
  4227 
       
  4228         The operand must be a logical number.
       
  4229 
       
  4230         >>> ExtendedContext.logical_invert(Decimal('0'))
       
  4231         Decimal('111111111')
       
  4232         >>> ExtendedContext.logical_invert(Decimal('1'))
       
  4233         Decimal('111111110')
       
  4234         >>> ExtendedContext.logical_invert(Decimal('111111111'))
       
  4235         Decimal('0')
       
  4236         >>> ExtendedContext.logical_invert(Decimal('101010101'))
       
  4237         Decimal('10101010')
       
  4238         """
       
  4239         return a.logical_invert(context=self)
       
  4240 
       
  4241     def logical_or(self, a, b):
       
  4242         """Applies the logical operation 'or' between each operand's digits.
       
  4243 
       
  4244         The operands must be both logical numbers.
       
  4245 
       
  4246         >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
       
  4247         Decimal('0')
       
  4248         >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
       
  4249         Decimal('1')
       
  4250         >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
       
  4251         Decimal('1')
       
  4252         >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
       
  4253         Decimal('1')
       
  4254         >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
       
  4255         Decimal('1110')
       
  4256         >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
       
  4257         Decimal('1110')
       
  4258         """
       
  4259         return a.logical_or(b, context=self)
       
  4260 
       
  4261     def logical_xor(self, a, b):
       
  4262         """Applies the logical operation 'xor' between each operand's digits.
       
  4263 
       
  4264         The operands must be both logical numbers.
       
  4265 
       
  4266         >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
       
  4267         Decimal('0')
       
  4268         >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
       
  4269         Decimal('1')
       
  4270         >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
       
  4271         Decimal('1')
       
  4272         >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
       
  4273         Decimal('0')
       
  4274         >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
       
  4275         Decimal('110')
       
  4276         >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
       
  4277         Decimal('1101')
       
  4278         """
       
  4279         return a.logical_xor(b, context=self)
       
  4280 
       
  4281     def max(self, a,b):
       
  4282         """max compares two values numerically and returns the maximum.
       
  4283 
       
  4284         If either operand is a NaN then the general rules apply.
       
  4285         Otherwise, the operands are compared as though by the compare
       
  4286         operation.  If they are numerically equal then the left-hand operand
       
  4287         is chosen as the result.  Otherwise the maximum (closer to positive
       
  4288         infinity) of the two operands is chosen as the result.
       
  4289 
       
  4290         >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
       
  4291         Decimal('3')
       
  4292         >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
       
  4293         Decimal('3')
       
  4294         >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
       
  4295         Decimal('1')
       
  4296         >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
       
  4297         Decimal('7')
       
  4298         """
       
  4299         return a.max(b, context=self)
       
  4300 
       
  4301     def max_mag(self, a, b):
       
  4302         """Compares the values numerically with their sign ignored."""
       
  4303         return a.max_mag(b, context=self)
       
  4304 
       
  4305     def min(self, a,b):
       
  4306         """min compares two values numerically and returns the minimum.
       
  4307 
       
  4308         If either operand is a NaN then the general rules apply.
       
  4309         Otherwise, the operands are compared as though by the compare
       
  4310         operation.  If they are numerically equal then the left-hand operand
       
  4311         is chosen as the result.  Otherwise the minimum (closer to negative
       
  4312         infinity) of the two operands is chosen as the result.
       
  4313 
       
  4314         >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
       
  4315         Decimal('2')
       
  4316         >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
       
  4317         Decimal('-10')
       
  4318         >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
       
  4319         Decimal('1.0')
       
  4320         >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
       
  4321         Decimal('7')
       
  4322         """
       
  4323         return a.min(b, context=self)
       
  4324 
       
  4325     def min_mag(self, a, b):
       
  4326         """Compares the values numerically with their sign ignored."""
       
  4327         return a.min_mag(b, context=self)
       
  4328 
       
  4329     def minus(self, a):
       
  4330         """Minus corresponds to unary prefix minus in Python.
       
  4331 
       
  4332         The operation is evaluated using the same rules as subtract; the
       
  4333         operation minus(a) is calculated as subtract('0', a) where the '0'
       
  4334         has the same exponent as the operand.
       
  4335 
       
  4336         >>> ExtendedContext.minus(Decimal('1.3'))
       
  4337         Decimal('-1.3')
       
  4338         >>> ExtendedContext.minus(Decimal('-1.3'))
       
  4339         Decimal('1.3')
       
  4340         """
       
  4341         return a.__neg__(context=self)
       
  4342 
       
  4343     def multiply(self, a, b):
       
  4344         """multiply multiplies two operands.
       
  4345 
       
  4346         If either operand is a special value then the general rules apply.
       
  4347         Otherwise, the operands are multiplied together ('long multiplication'),
       
  4348         resulting in a number which may be as long as the sum of the lengths
       
  4349         of the two operands.
       
  4350 
       
  4351         >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
       
  4352         Decimal('3.60')
       
  4353         >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
       
  4354         Decimal('21')
       
  4355         >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
       
  4356         Decimal('0.72')
       
  4357         >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
       
  4358         Decimal('-0.0')
       
  4359         >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
       
  4360         Decimal('4.28135971E+11')
       
  4361         """
       
  4362         return a.__mul__(b, context=self)
       
  4363 
       
  4364     def next_minus(self, a):
       
  4365         """Returns the largest representable number smaller than a.
       
  4366 
       
  4367         >>> c = ExtendedContext.copy()
       
  4368         >>> c.Emin = -999
       
  4369         >>> c.Emax = 999
       
  4370         >>> ExtendedContext.next_minus(Decimal('1'))
       
  4371         Decimal('0.999999999')
       
  4372         >>> c.next_minus(Decimal('1E-1007'))
       
  4373         Decimal('0E-1007')
       
  4374         >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
       
  4375         Decimal('-1.00000004')
       
  4376         >>> c.next_minus(Decimal('Infinity'))
       
  4377         Decimal('9.99999999E+999')
       
  4378         """
       
  4379         return a.next_minus(context=self)
       
  4380 
       
  4381     def next_plus(self, a):
       
  4382         """Returns the smallest representable number larger than a.
       
  4383 
       
  4384         >>> c = ExtendedContext.copy()
       
  4385         >>> c.Emin = -999
       
  4386         >>> c.Emax = 999
       
  4387         >>> ExtendedContext.next_plus(Decimal('1'))
       
  4388         Decimal('1.00000001')
       
  4389         >>> c.next_plus(Decimal('-1E-1007'))
       
  4390         Decimal('-0E-1007')
       
  4391         >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
       
  4392         Decimal('-1.00000002')
       
  4393         >>> c.next_plus(Decimal('-Infinity'))
       
  4394         Decimal('-9.99999999E+999')
       
  4395         """
       
  4396         return a.next_plus(context=self)
       
  4397 
       
  4398     def next_toward(self, a, b):
       
  4399         """Returns the number closest to a, in direction towards b.
       
  4400 
       
  4401         The result is the closest representable number from the first
       
  4402         operand (but not the first operand) that is in the direction
       
  4403         towards the second operand, unless the operands have the same
       
  4404         value.
       
  4405 
       
  4406         >>> c = ExtendedContext.copy()
       
  4407         >>> c.Emin = -999
       
  4408         >>> c.Emax = 999
       
  4409         >>> c.next_toward(Decimal('1'), Decimal('2'))
       
  4410         Decimal('1.00000001')
       
  4411         >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
       
  4412         Decimal('-0E-1007')
       
  4413         >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
       
  4414         Decimal('-1.00000002')
       
  4415         >>> c.next_toward(Decimal('1'), Decimal('0'))
       
  4416         Decimal('0.999999999')
       
  4417         >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
       
  4418         Decimal('0E-1007')
       
  4419         >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
       
  4420         Decimal('-1.00000004')
       
  4421         >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
       
  4422         Decimal('-0.00')
       
  4423         """
       
  4424         return a.next_toward(b, context=self)
       
  4425 
       
  4426     def normalize(self, a):
       
  4427         """normalize reduces an operand to its simplest form.
       
  4428 
       
  4429         Essentially a plus operation with all trailing zeros removed from the
       
  4430         result.
       
  4431 
       
  4432         >>> ExtendedContext.normalize(Decimal('2.1'))
       
  4433         Decimal('2.1')
       
  4434         >>> ExtendedContext.normalize(Decimal('-2.0'))
       
  4435         Decimal('-2')
       
  4436         >>> ExtendedContext.normalize(Decimal('1.200'))
       
  4437         Decimal('1.2')
       
  4438         >>> ExtendedContext.normalize(Decimal('-120'))
       
  4439         Decimal('-1.2E+2')
       
  4440         >>> ExtendedContext.normalize(Decimal('120.00'))
       
  4441         Decimal('1.2E+2')
       
  4442         >>> ExtendedContext.normalize(Decimal('0.00'))
       
  4443         Decimal('0')
       
  4444         """
       
  4445         return a.normalize(context=self)
       
  4446 
       
  4447     def number_class(self, a):
       
  4448         """Returns an indication of the class of the operand.
       
  4449 
       
  4450         The class is one of the following strings:
       
  4451           -sNaN
       
  4452           -NaN
       
  4453           -Infinity
       
  4454           -Normal
       
  4455           -Subnormal
       
  4456           -Zero
       
  4457           +Zero
       
  4458           +Subnormal
       
  4459           +Normal
       
  4460           +Infinity
       
  4461 
       
  4462         >>> c = Context(ExtendedContext)
       
  4463         >>> c.Emin = -999
       
  4464         >>> c.Emax = 999
       
  4465         >>> c.number_class(Decimal('Infinity'))
       
  4466         '+Infinity'
       
  4467         >>> c.number_class(Decimal('1E-10'))
       
  4468         '+Normal'
       
  4469         >>> c.number_class(Decimal('2.50'))
       
  4470         '+Normal'
       
  4471         >>> c.number_class(Decimal('0.1E-999'))
       
  4472         '+Subnormal'
       
  4473         >>> c.number_class(Decimal('0'))
       
  4474         '+Zero'
       
  4475         >>> c.number_class(Decimal('-0'))
       
  4476         '-Zero'
       
  4477         >>> c.number_class(Decimal('-0.1E-999'))
       
  4478         '-Subnormal'
       
  4479         >>> c.number_class(Decimal('-1E-10'))
       
  4480         '-Normal'
       
  4481         >>> c.number_class(Decimal('-2.50'))
       
  4482         '-Normal'
       
  4483         >>> c.number_class(Decimal('-Infinity'))
       
  4484         '-Infinity'
       
  4485         >>> c.number_class(Decimal('NaN'))
       
  4486         'NaN'
       
  4487         >>> c.number_class(Decimal('-NaN'))
       
  4488         'NaN'
       
  4489         >>> c.number_class(Decimal('sNaN'))
       
  4490         'sNaN'
       
  4491         """
       
  4492         return a.number_class(context=self)
       
  4493 
       
  4494     def plus(self, a):
       
  4495         """Plus corresponds to unary prefix plus in Python.
       
  4496 
       
  4497         The operation is evaluated using the same rules as add; the
       
  4498         operation plus(a) is calculated as add('0', a) where the '0'
       
  4499         has the same exponent as the operand.
       
  4500 
       
  4501         >>> ExtendedContext.plus(Decimal('1.3'))
       
  4502         Decimal('1.3')
       
  4503         >>> ExtendedContext.plus(Decimal('-1.3'))
       
  4504         Decimal('-1.3')
       
  4505         """
       
  4506         return a.__pos__(context=self)
       
  4507 
       
  4508     def power(self, a, b, modulo=None):
       
  4509         """Raises a to the power of b, to modulo if given.
       
  4510 
       
  4511         With two arguments, compute a**b.  If a is negative then b
       
  4512         must be integral.  The result will be inexact unless b is
       
  4513         integral and the result is finite and can be expressed exactly
       
  4514         in 'precision' digits.
       
  4515 
       
  4516         With three arguments, compute (a**b) % modulo.  For the
       
  4517         three argument form, the following restrictions on the
       
  4518         arguments hold:
       
  4519 
       
  4520          - all three arguments must be integral
       
  4521          - b must be nonnegative
       
  4522          - at least one of a or b must be nonzero
       
  4523          - modulo must be nonzero and have at most 'precision' digits
       
  4524 
       
  4525         The result of pow(a, b, modulo) is identical to the result
       
  4526         that would be obtained by computing (a**b) % modulo with
       
  4527         unbounded precision, but is computed more efficiently.  It is
       
  4528         always exact.
       
  4529 
       
  4530         >>> c = ExtendedContext.copy()
       
  4531         >>> c.Emin = -999
       
  4532         >>> c.Emax = 999
       
  4533         >>> c.power(Decimal('2'), Decimal('3'))
       
  4534         Decimal('8')
       
  4535         >>> c.power(Decimal('-2'), Decimal('3'))
       
  4536         Decimal('-8')
       
  4537         >>> c.power(Decimal('2'), Decimal('-3'))
       
  4538         Decimal('0.125')
       
  4539         >>> c.power(Decimal('1.7'), Decimal('8'))
       
  4540         Decimal('69.7575744')
       
  4541         >>> c.power(Decimal('10'), Decimal('0.301029996'))
       
  4542         Decimal('2.00000000')
       
  4543         >>> c.power(Decimal('Infinity'), Decimal('-1'))
       
  4544         Decimal('0')
       
  4545         >>> c.power(Decimal('Infinity'), Decimal('0'))
       
  4546         Decimal('1')
       
  4547         >>> c.power(Decimal('Infinity'), Decimal('1'))
       
  4548         Decimal('Infinity')
       
  4549         >>> c.power(Decimal('-Infinity'), Decimal('-1'))
       
  4550         Decimal('-0')
       
  4551         >>> c.power(Decimal('-Infinity'), Decimal('0'))
       
  4552         Decimal('1')
       
  4553         >>> c.power(Decimal('-Infinity'), Decimal('1'))
       
  4554         Decimal('-Infinity')
       
  4555         >>> c.power(Decimal('-Infinity'), Decimal('2'))
       
  4556         Decimal('Infinity')
       
  4557         >>> c.power(Decimal('0'), Decimal('0'))
       
  4558         Decimal('NaN')
       
  4559 
       
  4560         >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
       
  4561         Decimal('11')
       
  4562         >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
       
  4563         Decimal('-11')
       
  4564         >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
       
  4565         Decimal('1')
       
  4566         >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
       
  4567         Decimal('11')
       
  4568         >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
       
  4569         Decimal('11729830')
       
  4570         >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
       
  4571         Decimal('-0')
       
  4572         >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
       
  4573         Decimal('1')
       
  4574         """
       
  4575         return a.__pow__(b, modulo, context=self)
       
  4576 
       
  4577     def quantize(self, a, b):
       
  4578         """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
       
  4579 
       
  4580         The coefficient of the result is derived from that of the left-hand
       
  4581         operand.  It may be rounded using the current rounding setting (if the
       
  4582         exponent is being increased), multiplied by a positive power of ten (if
       
  4583         the exponent is being decreased), or is unchanged (if the exponent is
       
  4584         already equal to that of the right-hand operand).
       
  4585 
       
  4586         Unlike other operations, if the length of the coefficient after the
       
  4587         quantize operation would be greater than precision then an Invalid
       
  4588         operation condition is raised.  This guarantees that, unless there is
       
  4589         an error condition, the exponent of the result of a quantize is always
       
  4590         equal to that of the right-hand operand.
       
  4591 
       
  4592         Also unlike other operations, quantize will never raise Underflow, even
       
  4593         if the result is subnormal and inexact.
       
  4594 
       
  4595         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
       
  4596         Decimal('2.170')
       
  4597         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
       
  4598         Decimal('2.17')
       
  4599         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
       
  4600         Decimal('2.2')
       
  4601         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
       
  4602         Decimal('2')
       
  4603         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
       
  4604         Decimal('0E+1')
       
  4605         >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
       
  4606         Decimal('-Infinity')
       
  4607         >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
       
  4608         Decimal('NaN')
       
  4609         >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
       
  4610         Decimal('-0')
       
  4611         >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
       
  4612         Decimal('-0E+5')
       
  4613         >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
       
  4614         Decimal('NaN')
       
  4615         >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
       
  4616         Decimal('NaN')
       
  4617         >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
       
  4618         Decimal('217.0')
       
  4619         >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
       
  4620         Decimal('217')
       
  4621         >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
       
  4622         Decimal('2.2E+2')
       
  4623         >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
       
  4624         Decimal('2E+2')
       
  4625         """
       
  4626         return a.quantize(b, context=self)
       
  4627 
       
  4628     def radix(self):
       
  4629         """Just returns 10, as this is Decimal, :)
       
  4630 
       
  4631         >>> ExtendedContext.radix()
       
  4632         Decimal('10')
       
  4633         """
       
  4634         return Decimal(10)
       
  4635 
       
  4636     def remainder(self, a, b):
       
  4637         """Returns the remainder from integer division.
       
  4638 
       
  4639         The result is the residue of the dividend after the operation of
       
  4640         calculating integer division as described for divide-integer, rounded
       
  4641         to precision digits if necessary.  The sign of the result, if
       
  4642         non-zero, is the same as that of the original dividend.
       
  4643 
       
  4644         This operation will fail under the same conditions as integer division
       
  4645         (that is, if integer division on the same two operands would fail, the
       
  4646         remainder cannot be calculated).
       
  4647 
       
  4648         >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
       
  4649         Decimal('2.1')
       
  4650         >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
       
  4651         Decimal('1')
       
  4652         >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
       
  4653         Decimal('-1')
       
  4654         >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
       
  4655         Decimal('0.2')
       
  4656         >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
       
  4657         Decimal('0.1')
       
  4658         >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
       
  4659         Decimal('1.0')
       
  4660         """
       
  4661         return a.__mod__(b, context=self)
       
  4662 
       
  4663     def remainder_near(self, a, b):
       
  4664         """Returns to be "a - b * n", where n is the integer nearest the exact
       
  4665         value of "x / b" (if two integers are equally near then the even one
       
  4666         is chosen).  If the result is equal to 0 then its sign will be the
       
  4667         sign of a.
       
  4668 
       
  4669         This operation will fail under the same conditions as integer division
       
  4670         (that is, if integer division on the same two operands would fail, the
       
  4671         remainder cannot be calculated).
       
  4672 
       
  4673         >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
       
  4674         Decimal('-0.9')
       
  4675         >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
       
  4676         Decimal('-2')
       
  4677         >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
       
  4678         Decimal('1')
       
  4679         >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
       
  4680         Decimal('-1')
       
  4681         >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
       
  4682         Decimal('0.2')
       
  4683         >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
       
  4684         Decimal('0.1')
       
  4685         >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
       
  4686         Decimal('-0.3')
       
  4687         """
       
  4688         return a.remainder_near(b, context=self)
       
  4689 
       
  4690     def rotate(self, a, b):
       
  4691         """Returns a rotated copy of a, b times.
       
  4692 
       
  4693         The coefficient of the result is a rotated copy of the digits in
       
  4694         the coefficient of the first operand.  The number of places of
       
  4695         rotation is taken from the absolute value of the second operand,
       
  4696         with the rotation being to the left if the second operand is
       
  4697         positive or to the right otherwise.
       
  4698 
       
  4699         >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
       
  4700         Decimal('400000003')
       
  4701         >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
       
  4702         Decimal('12')
       
  4703         >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
       
  4704         Decimal('891234567')
       
  4705         >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
       
  4706         Decimal('123456789')
       
  4707         >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
       
  4708         Decimal('345678912')
       
  4709         """
       
  4710         return a.rotate(b, context=self)
       
  4711 
       
  4712     def same_quantum(self, a, b):
       
  4713         """Returns True if the two operands have the same exponent.
       
  4714 
       
  4715         The result is never affected by either the sign or the coefficient of
       
  4716         either operand.
       
  4717 
       
  4718         >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
       
  4719         False
       
  4720         >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
       
  4721         True
       
  4722         >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
       
  4723         False
       
  4724         >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
       
  4725         True
       
  4726         """
       
  4727         return a.same_quantum(b)
       
  4728 
       
  4729     def scaleb (self, a, b):
       
  4730         """Returns the first operand after adding the second value its exp.
       
  4731 
       
  4732         >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
       
  4733         Decimal('0.0750')
       
  4734         >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
       
  4735         Decimal('7.50')
       
  4736         >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
       
  4737         Decimal('7.50E+3')
       
  4738         """
       
  4739         return a.scaleb (b, context=self)
       
  4740 
       
  4741     def shift(self, a, b):
       
  4742         """Returns a shifted copy of a, b times.
       
  4743 
       
  4744         The coefficient of the result is a shifted copy of the digits
       
  4745         in the coefficient of the first operand.  The number of places
       
  4746         to shift is taken from the absolute value of the second operand,
       
  4747         with the shift being to the left if the second operand is
       
  4748         positive or to the right otherwise.  Digits shifted into the
       
  4749         coefficient are zeros.
       
  4750 
       
  4751         >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
       
  4752         Decimal('400000000')
       
  4753         >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
       
  4754         Decimal('0')
       
  4755         >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
       
  4756         Decimal('1234567')
       
  4757         >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
       
  4758         Decimal('123456789')
       
  4759         >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
       
  4760         Decimal('345678900')
       
  4761         """
       
  4762         return a.shift(b, context=self)
       
  4763 
       
  4764     def sqrt(self, a):
       
  4765         """Square root of a non-negative number to context precision.
       
  4766 
       
  4767         If the result must be inexact, it is rounded using the round-half-even
       
  4768         algorithm.
       
  4769 
       
  4770         >>> ExtendedContext.sqrt(Decimal('0'))
       
  4771         Decimal('0')
       
  4772         >>> ExtendedContext.sqrt(Decimal('-0'))
       
  4773         Decimal('-0')
       
  4774         >>> ExtendedContext.sqrt(Decimal('0.39'))
       
  4775         Decimal('0.624499800')
       
  4776         >>> ExtendedContext.sqrt(Decimal('100'))
       
  4777         Decimal('10')
       
  4778         >>> ExtendedContext.sqrt(Decimal('1'))
       
  4779         Decimal('1')
       
  4780         >>> ExtendedContext.sqrt(Decimal('1.0'))
       
  4781         Decimal('1.0')
       
  4782         >>> ExtendedContext.sqrt(Decimal('1.00'))
       
  4783         Decimal('1.0')
       
  4784         >>> ExtendedContext.sqrt(Decimal('7'))
       
  4785         Decimal('2.64575131')
       
  4786         >>> ExtendedContext.sqrt(Decimal('10'))
       
  4787         Decimal('3.16227766')
       
  4788         >>> ExtendedContext.prec
       
  4789         9
       
  4790         """
       
  4791         return a.sqrt(context=self)
       
  4792 
       
  4793     def subtract(self, a, b):
       
  4794         """Return the difference between the two operands.
       
  4795 
       
  4796         >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
       
  4797         Decimal('0.23')
       
  4798         >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
       
  4799         Decimal('0.00')
       
  4800         >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
       
  4801         Decimal('-0.77')
       
  4802         """
       
  4803         return a.__sub__(b, context=self)
       
  4804 
       
  4805     def to_eng_string(self, a):
       
  4806         """Converts a number to a string, using scientific notation.
       
  4807 
       
  4808         The operation is not affected by the context.
       
  4809         """
       
  4810         return a.to_eng_string(context=self)
       
  4811 
       
  4812     def to_sci_string(self, a):
       
  4813         """Converts a number to a string, using scientific notation.
       
  4814 
       
  4815         The operation is not affected by the context.
       
  4816         """
       
  4817         return a.__str__(context=self)
       
  4818 
       
  4819     def to_integral_exact(self, a):
       
  4820         """Rounds to an integer.
       
  4821 
       
  4822         When the operand has a negative exponent, the result is the same
       
  4823         as using the quantize() operation using the given operand as the
       
  4824         left-hand-operand, 1E+0 as the right-hand-operand, and the precision
       
  4825         of the operand as the precision setting; Inexact and Rounded flags
       
  4826         are allowed in this operation.  The rounding mode is taken from the
       
  4827         context.
       
  4828 
       
  4829         >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
       
  4830         Decimal('2')
       
  4831         >>> ExtendedContext.to_integral_exact(Decimal('100'))
       
  4832         Decimal('100')
       
  4833         >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
       
  4834         Decimal('100')
       
  4835         >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
       
  4836         Decimal('102')
       
  4837         >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
       
  4838         Decimal('-102')
       
  4839         >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
       
  4840         Decimal('1.0E+6')
       
  4841         >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
       
  4842         Decimal('7.89E+77')
       
  4843         >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
       
  4844         Decimal('-Infinity')
       
  4845         """
       
  4846         return a.to_integral_exact(context=self)
       
  4847 
       
  4848     def to_integral_value(self, a):
       
  4849         """Rounds to an integer.
       
  4850 
       
  4851         When the operand has a negative exponent, the result is the same
       
  4852         as using the quantize() operation using the given operand as the
       
  4853         left-hand-operand, 1E+0 as the right-hand-operand, and the precision
       
  4854         of the operand as the precision setting, except that no flags will
       
  4855         be set.  The rounding mode is taken from the context.
       
  4856 
       
  4857         >>> ExtendedContext.to_integral_value(Decimal('2.1'))
       
  4858         Decimal('2')
       
  4859         >>> ExtendedContext.to_integral_value(Decimal('100'))
       
  4860         Decimal('100')
       
  4861         >>> ExtendedContext.to_integral_value(Decimal('100.0'))
       
  4862         Decimal('100')
       
  4863         >>> ExtendedContext.to_integral_value(Decimal('101.5'))
       
  4864         Decimal('102')
       
  4865         >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
       
  4866         Decimal('-102')
       
  4867         >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
       
  4868         Decimal('1.0E+6')
       
  4869         >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
       
  4870         Decimal('7.89E+77')
       
  4871         >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
       
  4872         Decimal('-Infinity')
       
  4873         """
       
  4874         return a.to_integral_value(context=self)
       
  4875 
       
  4876     # the method name changed, but we provide also the old one, for compatibility
       
  4877     to_integral = to_integral_value
       
  4878 
       
  4879 class _WorkRep(object):
       
  4880     __slots__ = ('sign','int','exp')
       
  4881     # sign: 0 or 1
       
  4882     # int:  int or long
       
  4883     # exp:  None, int, or string
       
  4884 
       
  4885     def __init__(self, value=None):
       
  4886         if value is None:
       
  4887             self.sign = None
       
  4888             self.int = 0
       
  4889             self.exp = None
       
  4890         elif isinstance(value, Decimal):
       
  4891             self.sign = value._sign
       
  4892             self.int = int(value._int)
       
  4893             self.exp = value._exp
       
  4894         else:
       
  4895             # assert isinstance(value, tuple)
       
  4896             self.sign = value[0]
       
  4897             self.int = value[1]
       
  4898             self.exp = value[2]
       
  4899 
       
  4900     def __repr__(self):
       
  4901         return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
       
  4902 
       
  4903     __str__ = __repr__
       
  4904 
       
  4905 
       
  4906 
       
  4907 def _normalize(op1, op2, prec = 0):
       
  4908     """Normalizes op1, op2 to have the same exp and length of coefficient.
       
  4909 
       
  4910     Done during addition.
       
  4911     """
       
  4912     if op1.exp < op2.exp:
       
  4913         tmp = op2
       
  4914         other = op1
       
  4915     else:
       
  4916         tmp = op1
       
  4917         other = op2
       
  4918 
       
  4919     # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
       
  4920     # Then adding 10**exp to tmp has the same effect (after rounding)
       
  4921     # as adding any positive quantity smaller than 10**exp; similarly
       
  4922     # for subtraction.  So if other is smaller than 10**exp we replace
       
  4923     # it with 10**exp.  This avoids tmp.exp - other.exp getting too large.
       
  4924     tmp_len = len(str(tmp.int))
       
  4925     other_len = len(str(other.int))
       
  4926     exp = tmp.exp + min(-1, tmp_len - prec - 2)
       
  4927     if other_len + other.exp - 1 < exp:
       
  4928         other.int = 1
       
  4929         other.exp = exp
       
  4930 
       
  4931     tmp.int *= 10 ** (tmp.exp - other.exp)
       
  4932     tmp.exp = other.exp
       
  4933     return op1, op2
       
  4934 
       
  4935 ##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
       
  4936 
       
  4937 # This function from Tim Peters was taken from here:
       
  4938 # http://mail.python.org/pipermail/python-list/1999-July/007758.html
       
  4939 # The correction being in the function definition is for speed, and
       
  4940 # the whole function is not resolved with math.log because of avoiding
       
  4941 # the use of floats.
       
  4942 def _nbits(n, correction = {
       
  4943         '0': 4, '1': 3, '2': 2, '3': 2,
       
  4944         '4': 1, '5': 1, '6': 1, '7': 1,
       
  4945         '8': 0, '9': 0, 'a': 0, 'b': 0,
       
  4946         'c': 0, 'd': 0, 'e': 0, 'f': 0}):
       
  4947     """Number of bits in binary representation of the positive integer n,
       
  4948     or 0 if n == 0.
       
  4949     """
       
  4950     if n < 0:
       
  4951         raise ValueError("The argument to _nbits should be nonnegative.")
       
  4952     hex_n = "%x" % n
       
  4953     return 4*len(hex_n) - correction[hex_n[0]]
       
  4954 
       
  4955 def _sqrt_nearest(n, a):
       
  4956     """Closest integer to the square root of the positive integer n.  a is
       
  4957     an initial approximation to the square root.  Any positive integer
       
  4958     will do for a, but the closer a is to the square root of n the
       
  4959     faster convergence will be.
       
  4960 
       
  4961     """
       
  4962     if n <= 0 or a <= 0:
       
  4963         raise ValueError("Both arguments to _sqrt_nearest should be positive.")
       
  4964 
       
  4965     b=0
       
  4966     while a != b:
       
  4967         b, a = a, a--n//a>>1
       
  4968     return a
       
  4969 
       
  4970 def _rshift_nearest(x, shift):
       
  4971     """Given an integer x and a nonnegative integer shift, return closest
       
  4972     integer to x / 2**shift; use round-to-even in case of a tie.
       
  4973 
       
  4974     """
       
  4975     b, q = 1L << shift, x >> shift
       
  4976     return q + (2*(x & (b-1)) + (q&1) > b)
       
  4977 
       
  4978 def _div_nearest(a, b):
       
  4979     """Closest integer to a/b, a and b positive integers; rounds to even
       
  4980     in the case of a tie.
       
  4981 
       
  4982     """
       
  4983     q, r = divmod(a, b)
       
  4984     return q + (2*r + (q&1) > b)
       
  4985 
       
  4986 def _ilog(x, M, L = 8):
       
  4987     """Integer approximation to M*log(x/M), with absolute error boundable
       
  4988     in terms only of x/M.
       
  4989 
       
  4990     Given positive integers x and M, return an integer approximation to
       
  4991     M * log(x/M).  For L = 8 and 0.1 <= x/M <= 10 the difference
       
  4992     between the approximation and the exact result is at most 22.  For
       
  4993     L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15.  In
       
  4994     both cases these are upper bounds on the error; it will usually be
       
  4995     much smaller."""
       
  4996 
       
  4997     # The basic algorithm is the following: let log1p be the function
       
  4998     # log1p(x) = log(1+x).  Then log(x/M) = log1p((x-M)/M).  We use
       
  4999     # the reduction
       
  5000     #
       
  5001     #    log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
       
  5002     #
       
  5003     # repeatedly until the argument to log1p is small (< 2**-L in
       
  5004     # absolute value).  For small y we can use the Taylor series
       
  5005     # expansion
       
  5006     #
       
  5007     #    log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
       
  5008     #
       
  5009     # truncating at T such that y**T is small enough.  The whole
       
  5010     # computation is carried out in a form of fixed-point arithmetic,
       
  5011     # with a real number z being represented by an integer
       
  5012     # approximation to z*M.  To avoid loss of precision, the y below
       
  5013     # is actually an integer approximation to 2**R*y*M, where R is the
       
  5014     # number of reductions performed so far.
       
  5015 
       
  5016     y = x-M
       
  5017     # argument reduction; R = number of reductions performed
       
  5018     R = 0
       
  5019     while (R <= L and long(abs(y)) << L-R >= M or
       
  5020            R > L and abs(y) >> R-L >= M):
       
  5021         y = _div_nearest(long(M*y) << 1,
       
  5022                          M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
       
  5023         R += 1
       
  5024 
       
  5025     # Taylor series with T terms
       
  5026     T = -int(-10*len(str(M))//(3*L))
       
  5027     yshift = _rshift_nearest(y, R)
       
  5028     w = _div_nearest(M, T)
       
  5029     for k in xrange(T-1, 0, -1):
       
  5030         w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
       
  5031 
       
  5032     return _div_nearest(w*y, M)
       
  5033 
       
  5034 def _dlog10(c, e, p):
       
  5035     """Given integers c, e and p with c > 0, p >= 0, compute an integer
       
  5036     approximation to 10**p * log10(c*10**e), with an absolute error of
       
  5037     at most 1.  Assumes that c*10**e is not exactly 1."""
       
  5038 
       
  5039     # increase precision by 2; compensate for this by dividing
       
  5040     # final result by 100
       
  5041     p += 2
       
  5042 
       
  5043     # write c*10**e as d*10**f with either:
       
  5044     #   f >= 0 and 1 <= d <= 10, or
       
  5045     #   f <= 0 and 0.1 <= d <= 1.
       
  5046     # Thus for c*10**e close to 1, f = 0
       
  5047     l = len(str(c))
       
  5048     f = e+l - (e+l >= 1)
       
  5049 
       
  5050     if p > 0:
       
  5051         M = 10**p
       
  5052         k = e+p-f
       
  5053         if k >= 0:
       
  5054             c *= 10**k
       
  5055         else:
       
  5056             c = _div_nearest(c, 10**-k)
       
  5057 
       
  5058         log_d = _ilog(c, M) # error < 5 + 22 = 27
       
  5059         log_10 = _log10_digits(p) # error < 1
       
  5060         log_d = _div_nearest(log_d*M, log_10)
       
  5061         log_tenpower = f*M # exact
       
  5062     else:
       
  5063         log_d = 0  # error < 2.31
       
  5064         log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
       
  5065 
       
  5066     return _div_nearest(log_tenpower+log_d, 100)
       
  5067 
       
  5068 def _dlog(c, e, p):
       
  5069     """Given integers c, e and p with c > 0, compute an integer
       
  5070     approximation to 10**p * log(c*10**e), with an absolute error of
       
  5071     at most 1.  Assumes that c*10**e is not exactly 1."""
       
  5072 
       
  5073     # Increase precision by 2. The precision increase is compensated
       
  5074     # for at the end with a division by 100.
       
  5075     p += 2
       
  5076 
       
  5077     # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
       
  5078     # or f <= 0 and 0.1 <= d <= 1.  Then we can compute 10**p * log(c*10**e)
       
  5079     # as 10**p * log(d) + 10**p*f * log(10).
       
  5080     l = len(str(c))
       
  5081     f = e+l - (e+l >= 1)
       
  5082 
       
  5083     # compute approximation to 10**p*log(d), with error < 27
       
  5084     if p > 0:
       
  5085         k = e+p-f
       
  5086         if k >= 0:
       
  5087             c *= 10**k
       
  5088         else:
       
  5089             c = _div_nearest(c, 10**-k)  # error of <= 0.5 in c
       
  5090 
       
  5091         # _ilog magnifies existing error in c by a factor of at most 10
       
  5092         log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
       
  5093     else:
       
  5094         # p <= 0: just approximate the whole thing by 0; error < 2.31
       
  5095         log_d = 0
       
  5096 
       
  5097     # compute approximation to f*10**p*log(10), with error < 11.
       
  5098     if f:
       
  5099         extra = len(str(abs(f)))-1
       
  5100         if p + extra >= 0:
       
  5101             # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
       
  5102             # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
       
  5103             f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
       
  5104         else:
       
  5105             f_log_ten = 0
       
  5106     else:
       
  5107         f_log_ten = 0
       
  5108 
       
  5109     # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
       
  5110     return _div_nearest(f_log_ten + log_d, 100)
       
  5111 
       
  5112 class _Log10Memoize(object):
       
  5113     """Class to compute, store, and allow retrieval of, digits of the
       
  5114     constant log(10) = 2.302585....  This constant is needed by
       
  5115     Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
       
  5116     def __init__(self):
       
  5117         self.digits = "23025850929940456840179914546843642076011014886"
       
  5118 
       
  5119     def getdigits(self, p):
       
  5120         """Given an integer p >= 0, return floor(10**p)*log(10).
       
  5121 
       
  5122         For example, self.getdigits(3) returns 2302.
       
  5123         """
       
  5124         # digits are stored as a string, for quick conversion to
       
  5125         # integer in the case that we've already computed enough
       
  5126         # digits; the stored digits should always be correct
       
  5127         # (truncated, not rounded to nearest).
       
  5128         if p < 0:
       
  5129             raise ValueError("p should be nonnegative")
       
  5130 
       
  5131         if p >= len(self.digits):
       
  5132             # compute p+3, p+6, p+9, ... digits; continue until at
       
  5133             # least one of the extra digits is nonzero
       
  5134             extra = 3
       
  5135             while True:
       
  5136                 # compute p+extra digits, correct to within 1ulp
       
  5137                 M = 10**(p+extra+2)
       
  5138                 digits = str(_div_nearest(_ilog(10*M, M), 100))
       
  5139                 if digits[-extra:] != '0'*extra:
       
  5140                     break
       
  5141                 extra += 3
       
  5142             # keep all reliable digits so far; remove trailing zeros
       
  5143             # and next nonzero digit
       
  5144             self.digits = digits.rstrip('0')[:-1]
       
  5145         return int(self.digits[:p+1])
       
  5146 
       
  5147 _log10_digits = _Log10Memoize().getdigits
       
  5148 
       
  5149 def _iexp(x, M, L=8):
       
  5150     """Given integers x and M, M > 0, such that x/M is small in absolute
       
  5151     value, compute an integer approximation to M*exp(x/M).  For 0 <=
       
  5152     x/M <= 2.4, the absolute error in the result is bounded by 60 (and
       
  5153     is usually much smaller)."""
       
  5154 
       
  5155     # Algorithm: to compute exp(z) for a real number z, first divide z
       
  5156     # by a suitable power R of 2 so that |z/2**R| < 2**-L.  Then
       
  5157     # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
       
  5158     # series
       
  5159     #
       
  5160     #     expm1(x) = x + x**2/2! + x**3/3! + ...
       
  5161     #
       
  5162     # Now use the identity
       
  5163     #
       
  5164     #     expm1(2x) = expm1(x)*(expm1(x)+2)
       
  5165     #
       
  5166     # R times to compute the sequence expm1(z/2**R),
       
  5167     # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
       
  5168 
       
  5169     # Find R such that x/2**R/M <= 2**-L
       
  5170     R = _nbits((long(x)<<L)//M)
       
  5171 
       
  5172     # Taylor series.  (2**L)**T > M
       
  5173     T = -int(-10*len(str(M))//(3*L))
       
  5174     y = _div_nearest(x, T)
       
  5175     Mshift = long(M)<<R
       
  5176     for i in xrange(T-1, 0, -1):
       
  5177         y = _div_nearest(x*(Mshift + y), Mshift * i)
       
  5178 
       
  5179     # Expansion
       
  5180     for k in xrange(R-1, -1, -1):
       
  5181         Mshift = long(M)<<(k+2)
       
  5182         y = _div_nearest(y*(y+Mshift), Mshift)
       
  5183 
       
  5184     return M+y
       
  5185 
       
  5186 def _dexp(c, e, p):
       
  5187     """Compute an approximation to exp(c*10**e), with p decimal places of
       
  5188     precision.
       
  5189 
       
  5190     Returns integers d, f such that:
       
  5191 
       
  5192       10**(p-1) <= d <= 10**p, and
       
  5193       (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
       
  5194 
       
  5195     In other words, d*10**f is an approximation to exp(c*10**e) with p
       
  5196     digits of precision, and with an error in d of at most 1.  This is
       
  5197     almost, but not quite, the same as the error being < 1ulp: when d
       
  5198     = 10**(p-1) the error could be up to 10 ulp."""
       
  5199 
       
  5200     # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
       
  5201     p += 2
       
  5202 
       
  5203     # compute log(10) with extra precision = adjusted exponent of c*10**e
       
  5204     extra = max(0, e + len(str(c)) - 1)
       
  5205     q = p + extra
       
  5206 
       
  5207     # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
       
  5208     # rounding down
       
  5209     shift = e+q
       
  5210     if shift >= 0:
       
  5211         cshift = c*10**shift
       
  5212     else:
       
  5213         cshift = c//10**-shift
       
  5214     quot, rem = divmod(cshift, _log10_digits(q))
       
  5215 
       
  5216     # reduce remainder back to original precision
       
  5217     rem = _div_nearest(rem, 10**extra)
       
  5218 
       
  5219     # error in result of _iexp < 120;  error after division < 0.62
       
  5220     return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
       
  5221 
       
  5222 def _dpower(xc, xe, yc, ye, p):
       
  5223     """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
       
  5224     y = yc*10**ye, compute x**y.  Returns a pair of integers (c, e) such that:
       
  5225 
       
  5226       10**(p-1) <= c <= 10**p, and
       
  5227       (c-1)*10**e < x**y < (c+1)*10**e
       
  5228 
       
  5229     in other words, c*10**e is an approximation to x**y with p digits
       
  5230     of precision, and with an error in c of at most 1.  (This is
       
  5231     almost, but not quite, the same as the error being < 1ulp: when c
       
  5232     == 10**(p-1) we can only guarantee error < 10ulp.)
       
  5233 
       
  5234     We assume that: x is positive and not equal to 1, and y is nonzero.
       
  5235     """
       
  5236 
       
  5237     # Find b such that 10**(b-1) <= |y| <= 10**b
       
  5238     b = len(str(abs(yc))) + ye
       
  5239 
       
  5240     # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
       
  5241     lxc = _dlog(xc, xe, p+b+1)
       
  5242 
       
  5243     # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
       
  5244     shift = ye-b
       
  5245     if shift >= 0:
       
  5246         pc = lxc*yc*10**shift
       
  5247     else:
       
  5248         pc = _div_nearest(lxc*yc, 10**-shift)
       
  5249 
       
  5250     if pc == 0:
       
  5251         # we prefer a result that isn't exactly 1; this makes it
       
  5252         # easier to compute a correctly rounded result in __pow__
       
  5253         if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
       
  5254             coeff, exp = 10**(p-1)+1, 1-p
       
  5255         else:
       
  5256             coeff, exp = 10**p-1, -p
       
  5257     else:
       
  5258         coeff, exp = _dexp(pc, -(p+1), p+1)
       
  5259         coeff = _div_nearest(coeff, 10)
       
  5260         exp += 1
       
  5261 
       
  5262     return coeff, exp
       
  5263 
       
  5264 def _log10_lb(c, correction = {
       
  5265         '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
       
  5266         '6': 23, '7': 16, '8': 10, '9': 5}):
       
  5267     """Compute a lower bound for 100*log10(c) for a positive integer c."""
       
  5268     if c <= 0:
       
  5269         raise ValueError("The argument to _log10_lb should be nonnegative.")
       
  5270     str_c = str(c)
       
  5271     return 100*len(str_c) - correction[str_c[0]]
       
  5272 
       
  5273 ##### Helper Functions ####################################################
       
  5274 
       
  5275 def _convert_other(other, raiseit=False):
       
  5276     """Convert other to Decimal.
       
  5277 
       
  5278     Verifies that it's ok to use in an implicit construction.
       
  5279     """
       
  5280     if isinstance(other, Decimal):
       
  5281         return other
       
  5282     if isinstance(other, (int, long)):
       
  5283         return Decimal(other)
       
  5284     if raiseit:
       
  5285         raise TypeError("Unable to convert %s to Decimal" % other)
       
  5286     return NotImplemented
       
  5287 
       
  5288 ##### Setup Specific Contexts ############################################
       
  5289 
       
  5290 # The default context prototype used by Context()
       
  5291 # Is mutable, so that new contexts can have different default values
       
  5292 
       
  5293 DefaultContext = Context(
       
  5294         prec=28, rounding=ROUND_HALF_EVEN,
       
  5295         traps=[DivisionByZero, Overflow, InvalidOperation],
       
  5296         flags=[],
       
  5297         Emax=999999999,
       
  5298         Emin=-999999999,
       
  5299         capitals=1
       
  5300 )
       
  5301 
       
  5302 # Pre-made alternate contexts offered by the specification
       
  5303 # Don't change these; the user should be able to select these
       
  5304 # contexts and be able to reproduce results from other implementations
       
  5305 # of the spec.
       
  5306 
       
  5307 BasicContext = Context(
       
  5308         prec=9, rounding=ROUND_HALF_UP,
       
  5309         traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
       
  5310         flags=[],
       
  5311 )
       
  5312 
       
  5313 ExtendedContext = Context(
       
  5314         prec=9, rounding=ROUND_HALF_EVEN,
       
  5315         traps=[],
       
  5316         flags=[],
       
  5317 )
       
  5318 
       
  5319 
       
  5320 ##### crud for parsing strings #############################################
       
  5321 #
       
  5322 # Regular expression used for parsing numeric strings.  Additional
       
  5323 # comments:
       
  5324 #
       
  5325 # 1. Uncomment the two '\s*' lines to allow leading and/or trailing
       
  5326 # whitespace.  But note that the specification disallows whitespace in
       
  5327 # a numeric string.
       
  5328 #
       
  5329 # 2. For finite numbers (not infinities and NaNs) the body of the
       
  5330 # number between the optional sign and the optional exponent must have
       
  5331 # at least one decimal digit, possibly after the decimal point.  The
       
  5332 # lookahead expression '(?=\d|\.\d)' checks this.
       
  5333 #
       
  5334 # As the flag UNICODE is not enabled here, we're explicitly avoiding any
       
  5335 # other meaning for \d than the numbers [0-9].
       
  5336 
       
  5337 import re
       
  5338 _parser = re.compile(r"""        # A numeric string consists of:
       
  5339 #    \s*
       
  5340     (?P<sign>[-+])?              # an optional sign, followed by either...
       
  5341     (
       
  5342         (?=[0-9]|\.[0-9])        # ...a number (with at least one digit)
       
  5343         (?P<int>[0-9]*)          # having a (possibly empty) integer part
       
  5344         (\.(?P<frac>[0-9]*))?    # followed by an optional fractional part
       
  5345         (E(?P<exp>[-+]?[0-9]+))? # followed by an optional exponent, or...
       
  5346     |
       
  5347         Inf(inity)?              # ...an infinity, or...
       
  5348     |
       
  5349         (?P<signal>s)?           # ...an (optionally signaling)
       
  5350         NaN                      # NaN
       
  5351         (?P<diag>[0-9]*)         # with (possibly empty) diagnostic info.
       
  5352     )
       
  5353 #    \s*
       
  5354     \Z
       
  5355 """, re.VERBOSE | re.IGNORECASE).match
       
  5356 
       
  5357 _all_zeros = re.compile('0*$').match
       
  5358 _exact_half = re.compile('50*$').match
       
  5359 
       
  5360 ##### PEP3101 support functions ##############################################
       
  5361 # The functions parse_format_specifier and format_align have little to do
       
  5362 # with the Decimal class, and could potentially be reused for other pure
       
  5363 # Python numeric classes that want to implement __format__
       
  5364 #
       
  5365 # A format specifier for Decimal looks like:
       
  5366 #
       
  5367 #   [[fill]align][sign][0][minimumwidth][.precision][type]
       
  5368 #
       
  5369 
       
  5370 _parse_format_specifier_regex = re.compile(r"""\A
       
  5371 (?:
       
  5372    (?P<fill>.)?
       
  5373    (?P<align>[<>=^])
       
  5374 )?
       
  5375 (?P<sign>[-+ ])?
       
  5376 (?P<zeropad>0)?
       
  5377 (?P<minimumwidth>(?!0)\d+)?
       
  5378 (?:\.(?P<precision>0|(?!0)\d+))?
       
  5379 (?P<type>[eEfFgG%])?
       
  5380 \Z
       
  5381 """, re.VERBOSE)
       
  5382 
       
  5383 del re
       
  5384 
       
  5385 def _parse_format_specifier(format_spec):
       
  5386     """Parse and validate a format specifier.
       
  5387 
       
  5388     Turns a standard numeric format specifier into a dict, with the
       
  5389     following entries:
       
  5390 
       
  5391       fill: fill character to pad field to minimum width
       
  5392       align: alignment type, either '<', '>', '=' or '^'
       
  5393       sign: either '+', '-' or ' '
       
  5394       minimumwidth: nonnegative integer giving minimum width
       
  5395       precision: nonnegative integer giving precision, or None
       
  5396       type: one of the characters 'eEfFgG%', or None
       
  5397       unicode: either True or False (always True for Python 3.x)
       
  5398 
       
  5399     """
       
  5400     m = _parse_format_specifier_regex.match(format_spec)
       
  5401     if m is None:
       
  5402         raise ValueError("Invalid format specifier: " + format_spec)
       
  5403 
       
  5404     # get the dictionary
       
  5405     format_dict = m.groupdict()
       
  5406 
       
  5407     # defaults for fill and alignment
       
  5408     fill = format_dict['fill']
       
  5409     align = format_dict['align']
       
  5410     if format_dict.pop('zeropad') is not None:
       
  5411         # in the face of conflict, refuse the temptation to guess
       
  5412         if fill is not None and fill != '0':
       
  5413             raise ValueError("Fill character conflicts with '0'"
       
  5414                              " in format specifier: " + format_spec)
       
  5415         if align is not None and align != '=':
       
  5416             raise ValueError("Alignment conflicts with '0' in "
       
  5417                              "format specifier: " + format_spec)
       
  5418         fill = '0'
       
  5419         align = '='
       
  5420     format_dict['fill'] = fill or ' '
       
  5421     format_dict['align'] = align or '<'
       
  5422 
       
  5423     if format_dict['sign'] is None:
       
  5424         format_dict['sign'] = '-'
       
  5425 
       
  5426     # turn minimumwidth and precision entries into integers.
       
  5427     # minimumwidth defaults to 0; precision remains None if not given
       
  5428     format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
       
  5429     if format_dict['precision'] is not None:
       
  5430         format_dict['precision'] = int(format_dict['precision'])
       
  5431 
       
  5432     # if format type is 'g' or 'G' then a precision of 0 makes little
       
  5433     # sense; convert it to 1.  Same if format type is unspecified.
       
  5434     if format_dict['precision'] == 0:
       
  5435         if format_dict['type'] in 'gG' or format_dict['type'] is None:
       
  5436             format_dict['precision'] = 1
       
  5437 
       
  5438     # record whether return type should be str or unicode
       
  5439     format_dict['unicode'] = isinstance(format_spec, unicode)
       
  5440 
       
  5441     return format_dict
       
  5442 
       
  5443 def _format_align(body, spec_dict):
       
  5444     """Given an unpadded, non-aligned numeric string, add padding and
       
  5445     aligment to conform with the given format specifier dictionary (as
       
  5446     output from parse_format_specifier).
       
  5447 
       
  5448     It's assumed that if body is negative then it starts with '-'.
       
  5449     Any leading sign ('-' or '+') is stripped from the body before
       
  5450     applying the alignment and padding rules, and replaced in the
       
  5451     appropriate position.
       
  5452 
       
  5453     """
       
  5454     # figure out the sign; we only examine the first character, so if
       
  5455     # body has leading whitespace the results may be surprising.
       
  5456     if len(body) > 0 and body[0] in '-+':
       
  5457         sign = body[0]
       
  5458         body = body[1:]
       
  5459     else:
       
  5460         sign = ''
       
  5461 
       
  5462     if sign != '-':
       
  5463         if spec_dict['sign'] in ' +':
       
  5464             sign = spec_dict['sign']
       
  5465         else:
       
  5466             sign = ''
       
  5467 
       
  5468     # how much extra space do we have to play with?
       
  5469     minimumwidth = spec_dict['minimumwidth']
       
  5470     fill = spec_dict['fill']
       
  5471     padding = fill*(max(minimumwidth - (len(sign+body)), 0))
       
  5472 
       
  5473     align = spec_dict['align']
       
  5474     if align == '<':
       
  5475         result = padding + sign + body
       
  5476     elif align == '>':
       
  5477         result = sign + body + padding
       
  5478     elif align == '=':
       
  5479         result = sign + padding + body
       
  5480     else: #align == '^'
       
  5481         half = len(padding)//2
       
  5482         result = padding[:half] + sign + body + padding[half:]
       
  5483 
       
  5484     # make sure that result is unicode if necessary
       
  5485     if spec_dict['unicode']:
       
  5486         result = unicode(result)
       
  5487 
       
  5488     return result
       
  5489 
       
  5490 ##### Useful Constants (internal use only) ################################
       
  5491 
       
  5492 # Reusable defaults
       
  5493 Inf = Decimal('Inf')
       
  5494 negInf = Decimal('-Inf')
       
  5495 NaN = Decimal('NaN')
       
  5496 Dec_0 = Decimal(0)
       
  5497 Dec_p1 = Decimal(1)
       
  5498 Dec_n1 = Decimal(-1)
       
  5499 
       
  5500 # Infsign[sign] is infinity w/ that sign
       
  5501 Infsign = (Inf, negInf)
       
  5502 
       
  5503 
       
  5504 
       
  5505 if __name__ == '__main__':
       
  5506     import doctest, sys
       
  5507     doctest.testmod(sys.modules[__name__])