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