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