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