decimal.py revision f4da77765f8581e31620e9f49c68028e57b0ae85
1d2d19ea51fa3575a8d014a69a9b835c335728817Christoph Bumiller# Copyright (c) 2004 Python Software Foundation.
2d2d19ea51fa3575a8d014a69a9b835c335728817Christoph Bumiller# All rights reserved.
3d2d19ea51fa3575a8d014a69a9b835c335728817Christoph Bumiller
4d2d19ea51fa3575a8d014a69a9b835c335728817Christoph Bumiller# Written by Eric Price <eprice at tjhsst.edu>
5d2d19ea51fa3575a8d014a69a9b835c335728817Christoph Bumiller#    and Facundo Batista <facundo at taniquetil.com.ar>
6d2d19ea51fa3575a8d014a69a9b835c335728817Christoph Bumiller#    and Raymond Hettinger <python at rcn.com>
7d2d19ea51fa3575a8d014a69a9b835c335728817Christoph Bumiller#    and Aahz <aahz at pobox.com>
8d2d19ea51fa3575a8d014a69a9b835c335728817Christoph Bumiller#    and Tim Peters
9d2d19ea51fa3575a8d014a69a9b835c335728817Christoph Bumiller
10d2d19ea51fa3575a8d014a69a9b835c335728817Christoph Bumiller# This module is currently Py2.3 compatible and should be kept that way
11d2d19ea51fa3575a8d014a69a9b835c335728817Christoph Bumiller# unless a major compelling advantage arises.  IOW, 2.3 compatibility is
12d2d19ea51fa3575a8d014a69a9b835c335728817Christoph Bumiller# strongly preferred, but not guaranteed.
13d2d19ea51fa3575a8d014a69a9b835c335728817Christoph Bumiller
14d2d19ea51fa3575a8d014a69a9b835c335728817Christoph Bumiller# Also, this module should be kept in sync with the latest updates of
15d2d19ea51fa3575a8d014a69a9b835c335728817Christoph Bumiller# the IBM specification as it evolves.  Those updates will be treated
16d2d19ea51fa3575a8d014a69a9b835c335728817Christoph Bumiller# as bug fixes (deviation from the spec is a compatibility, usability
17d2d19ea51fa3575a8d014a69a9b835c335728817Christoph Bumiller# bug) and will be backported.  At this point the spec is stabilizing
18d2d19ea51fa3575a8d014a69a9b835c335728817Christoph Bumiller# and the updates are becoming fewer, smaller, and less significant.
19d2d19ea51fa3575a8d014a69a9b835c335728817Christoph Bumiller
20d2d19ea51fa3575a8d014a69a9b835c335728817Christoph Bumiller"""
21d2d19ea51fa3575a8d014a69a9b835c335728817Christoph BumillerThis is a Py2.3 implementation of decimal floating point arithmetic based on
2257594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerthe General Decimal Arithmetic Specification:
2357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
2457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    www2.hursley.ibm.com/decimal/decarith.html
2557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
2657594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerand IEEE standard 854-1987:
2757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
2857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
298cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerez
308cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco JerezDecimal floating point has finite precision with arbitrarily large bounds.
318cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerez
3257594065c30feec9376be9b2132659f7d87362eeChristoph BumillerThe purpose of this module is to support arithmetic using familiar
3357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller"schoolhouse" rules and to avoid some of the tricky representation
3457594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerissues associated with binary floating point.  The package is especially
3557594065c30feec9376be9b2132659f7d87362eeChristoph Bumilleruseful for financial applications or for contexts where users have
3657594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerexpectations that are at odds with binary floating point (for instance,
3757594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerin binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
3857594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerof the expected Decimal('0.00') returned by decimal floating point).
3957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
4057594065c30feec9376be9b2132659f7d87362eeChristoph BumillerHere are some examples of using the decimal module:
4157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
4257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> from decimal import *
4357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> setcontext(ExtendedContext)
4457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> Decimal(0)
4557594065c30feec9376be9b2132659f7d87362eeChristoph BumillerDecimal('0')
4657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> Decimal('1')
4757594065c30feec9376be9b2132659f7d87362eeChristoph BumillerDecimal('1')
48d6d1f0e4a25c9fbefce7485d77617855a8ea956aFrancisco Jerez>>> Decimal('-.0123')
4957594065c30feec9376be9b2132659f7d87362eeChristoph BumillerDecimal('-0.0123')
5057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> Decimal(123456)
5157594065c30feec9376be9b2132659f7d87362eeChristoph BumillerDecimal('123456')
5257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> Decimal('123.45e12345678901234567890')
5357594065c30feec9376be9b2132659f7d87362eeChristoph BumillerDecimal('1.2345E+12345678901234567892')
5457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> Decimal('1.33') + Decimal('1.27')
5557594065c30feec9376be9b2132659f7d87362eeChristoph BumillerDecimal('2.60')
5657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
5757594065c30feec9376be9b2132659f7d87362eeChristoph BumillerDecimal('-2.20')
5857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> dig = Decimal(1)
5957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> print dig / Decimal(3)
6057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller0.333333333
6157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> getcontext().prec = 18
6257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> print dig / Decimal(3)
6357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller0.333333333333333333
6457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> print dig.sqrt()
6557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller1
6657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> print Decimal(3).sqrt()
6757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller1.73205080756887729
6857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> print Decimal(3) ** 123
6957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller4.85192780976896427E+58
7057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> inf = Decimal(1) / Decimal(0)
7157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> print inf
7257594065c30feec9376be9b2132659f7d87362eeChristoph BumillerInfinity
7357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> neginf = Decimal(-1) / Decimal(0)
7457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> print neginf
7557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller-Infinity
7657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> print neginf + inf
7757594065c30feec9376be9b2132659f7d87362eeChristoph BumillerNaN
7857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> print neginf * inf
7957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller-Infinity
8057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> print dig / 0
8157594065c30feec9376be9b2132659f7d87362eeChristoph BumillerInfinity
8257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> getcontext().traps[DivisionByZero] = 1
8357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> print dig / 0
8457594065c30feec9376be9b2132659f7d87362eeChristoph BumillerTraceback (most recent call last):
8557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller  ...
8657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller  ...
8757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller  ...
8857594065c30feec9376be9b2132659f7d87362eeChristoph BumillerDivisionByZero: x / 0
8957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> c = Context()
9057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> c.traps[InvalidOperation] = 0
9157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> print c.flags[InvalidOperation]
9257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller0
9357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> c.divide(Decimal(0), Decimal(0))
9457594065c30feec9376be9b2132659f7d87362eeChristoph BumillerDecimal('NaN')
9557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> c.traps[InvalidOperation] = 1
9657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> print c.flags[InvalidOperation]
9757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller1
9857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> c.flags[InvalidOperation] = 0
9957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> print c.flags[InvalidOperation]
10057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller0
10157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> print c.divide(Decimal(0), Decimal(0))
10257594065c30feec9376be9b2132659f7d87362eeChristoph BumillerTraceback (most recent call last):
10357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller  ...
10457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller  ...
10557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller  ...
10657594065c30feec9376be9b2132659f7d87362eeChristoph BumillerInvalidOperation: 0 / 0
10757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> print c.flags[InvalidOperation]
10857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller1
10957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> c.flags[InvalidOperation] = 0
11057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> c.traps[InvalidOperation] = 0
11157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> print c.divide(Decimal(0), Decimal(0))
11257594065c30feec9376be9b2132659f7d87362eeChristoph BumillerNaN
11357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>> print c.flags[InvalidOperation]
11457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller1
11557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller>>>
11657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller"""
11757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
11857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller__all__ = [
11957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    # Two major classes
12057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    'Decimal', 'Context',
12157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
12257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    # Contexts
12357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    'DefaultContext', 'BasicContext', 'ExtendedContext',
12457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
12557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    # Exceptions
12657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
12757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
12857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
12957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    # Constants for use in setting up contexts
13057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
13157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
13257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
13357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    # Functions for manipulating contexts
134e44089b2f79aa2dcaacf348911433d1e21235c0cChristoph Bumiller    'setcontext', 'getcontext', 'localcontext'
13557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller]
13657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
13757594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerimport copy as _copy
13800fe442253744c4c4e7e68da44d6983da053968bChristoph Bumiller
13900fe442253744c4c4e7e68da44d6983da053968bChristoph Bumillertry:
14057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    from collections import namedtuple as _namedtuple
14157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
14257594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerexcept ImportError:
14357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    DecimalTuple = lambda *args: args
14457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
1450e4e0ca6df52ddecd1bb2fe9a427549d1a82b9f9Christoph Bumiller# Rounding
146322bc7ed68ed92233c97168c036d0aa50c11a20eChristoph BumillerROUND_DOWN = 'ROUND_DOWN'
147e44089b2f79aa2dcaacf348911433d1e21235c0cChristoph BumillerROUND_HALF_UP = 'ROUND_HALF_UP'
14800fe442253744c4c4e7e68da44d6983da053968bChristoph BumillerROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
14957594065c30feec9376be9b2132659f7d87362eeChristoph BumillerROUND_CEILING = 'ROUND_CEILING'
15057594065c30feec9376be9b2132659f7d87362eeChristoph BumillerROUND_FLOOR = 'ROUND_FLOOR'
15157594065c30feec9376be9b2132659f7d87362eeChristoph BumillerROUND_UP = 'ROUND_UP'
15257594065c30feec9376be9b2132659f7d87362eeChristoph BumillerROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
15357594065c30feec9376be9b2132659f7d87362eeChristoph BumillerROUND_05UP = 'ROUND_05UP'
15457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
15557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller# Errors
15657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
15757594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerclass DecimalException(ArithmeticError):
15857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """Base exception class.
15957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
16057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    Used exceptions derive from this.
16157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    If an exception derives from another exception besides this (such as
16257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
16357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    called if the others are present.  This isn't actually used for
16457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    anything, though.
16557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
16657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    handle  -- Called when context._raise_error is called and the
16757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller               trap_enabler is set.  First argument is self, second is the
16857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller               context.  More arguments can be given, those being after
16957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller               the explanation in _raise_error (For example,
17057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller               context._raise_error(NewError, '(-x)!', self._sign) would
17157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller               call NewError().handle(context, self._sign).)
17257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
17357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    To define a new exception, it should be sufficient to have it derive
17457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    from DecimalException.
17557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """
17657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def handle(self, context, *args):
17757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        pass
17857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
17957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
18057594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerclass Clamped(DecimalException):
18157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """Exponent of a 0 changed to fit bounds.
18257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
18357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    This occurs and signals clamped if the exponent of a result has been
18457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    altered in order to fit the constraints of a specific concrete
18557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    representation.  This may occur when the exponent of a zero result would
18657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    be outside the bounds of a representation, or when a large normal
18757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    number would have an encoded exponent that cannot be represented.  In
18857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    this latter case, the exponent is reduced to fit and the corresponding
18957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    number of zero digits are appended to the coefficient ("fold-down").
19057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """
19157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
19257594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerclass InvalidOperation(DecimalException):
19357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """An invalid operation was performed.
19457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
19557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    Various bad things cause this:
19657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
19757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    Something creates a signaling NaN
19857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    -INF + INF
19957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    0 * (+-)INF
20057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    (+-)INF / (+-)INF
20157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    x % 0
20257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    (+-)INF % x
20357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    x._rescale( non-integer )
20457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    sqrt(-x) , x > 0
20557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    0 ** 0
20657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    x ** (non-integer)
20757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    x ** (+-)INF
20857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    An operand is invalid
20957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
21057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    The result of the operation after these is a quiet positive NaN,
21157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    except when the cause is a signaling NaN, in which case the result is
21257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    also a quiet NaN, but with the original sign, and an optional
21357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    diagnostic information.
21457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """
21557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def handle(self, context, *args):
21657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if args:
21757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
21857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return ans._fix_nan(context)
21957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return NaN
22057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
22157594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerclass ConversionSyntax(InvalidOperation):
22257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """Trying to convert badly formed string.
22357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
22457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    This occurs and signals invalid-operation if an string is being
22557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    converted to a number and it does not conform to the numeric string
22657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    syntax.  The result is [0,qNaN].
22757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """
228e43a3a66a9d8a99021d76ff4d07dec7b8cfd62caChristoph Bumiller    def handle(self, context, *args):
22957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return NaN
23057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
23157594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerclass DivisionByZero(DecimalException, ZeroDivisionError):
23257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """Division by 0.
23357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
23457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    This occurs and signals division-by-zero if division of a finite number
23557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    by zero was attempted (during a divide-integer or divide operation, or a
23657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    power operation with negative right-hand operand), and the dividend was
23757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    not zero.
23857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
23957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    The result of the operation is [sign,inf], where sign is the exclusive
24057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    or of the signs of the operands for divide, or is 1 for an odd power of
24157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    -0, for power.
24257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """
24357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
24457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def handle(self, context, sign, *args):
24557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return Infsign[sign]
24657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
24757594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerclass DivisionImpossible(InvalidOperation):
24857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """Cannot perform the division adequately.
24957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
25057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    This occurs and signals invalid-operation if the integer result of a
25157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    divide-integer or remainder operation had too many digits (would be
25257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    longer than precision).  The result is [0,qNaN].
25357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """
25457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
25557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def handle(self, context, *args):
25657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return NaN
25757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
25857594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerclass DivisionUndefined(InvalidOperation, ZeroDivisionError):
25957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """Undefined result of division.
26057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
26157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    This occurs and signals invalid-operation if division by zero was
26257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    attempted (during a divide-integer, divide, or remainder operation), and
26357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    the dividend is also zero.  The result is [0,qNaN].
26457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """
26557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
26657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def handle(self, context, *args):
26757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return NaN
26857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
26957594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerclass Inexact(DecimalException):
27057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """Had to round, losing information.
27157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
27257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    This occurs and signals inexact whenever the result of an operation is
27357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    not exact (that is, it needed to be rounded and any discarded digits
27457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    were non-zero), or if an overflow or underflow condition occurs.  The
27557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    result in all cases is unchanged.
27657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
27757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    The inexact signal may be tested (or trapped) to determine if a given
27857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    operation (or sequence of operations) was inexact.
27957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """
28057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
28157594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerclass InvalidContext(InvalidOperation):
28257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """Invalid context.  Unknown rounding, for example.
28357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
28457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    This occurs and signals invalid-operation if an invalid context was
28557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    detected during an operation.  This can occur if contexts are not checked
28657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    on creation and either the precision exceeds the capability of the
28757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    underlying concrete representation or an unknown or unsupported rounding
28857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    was specified.  These aspects of the context need only be checked when
28957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    the values are required to be used.  The result is [0,qNaN].
29057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """
29157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
29257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def handle(self, context, *args):
29357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return NaN
29457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
29557594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerclass Rounded(DecimalException):
29657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """Number got rounded (not  necessarily changed during rounding).
29757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
29857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    This occurs and signals rounded whenever the result of an operation is
29957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    rounded (that is, some zero or non-zero digits were discarded from the
30057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    coefficient), or if an overflow or underflow condition occurs.  The
30157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    result in all cases is unchanged.
30257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
30357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    The rounded signal may be tested (or trapped) to determine if a given
30457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    operation (or sequence of operations) caused a loss of precision.
30557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """
30657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
30757594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerclass Subnormal(DecimalException):
30857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """Exponent < Emin before rounding.
30957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
31057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    This occurs and signals subnormal whenever the result of a conversion or
31157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    operation is subnormal (that is, its adjusted exponent is less than
31257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    Emin, before any rounding).  The result in all cases is unchanged.
31357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
31457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    The subnormal signal may be tested (or trapped) to determine if a given
31557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    or operation (or sequence of operations) yielded a subnormal result.
31657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """
31757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
31857594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerclass Overflow(Inexact, Rounded):
31957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """Numerical overflow.
32057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
32157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    This occurs and signals overflow if the adjusted exponent of a result
32257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    (from a conversion or from an operation that is not an attempt to divide
32357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    by zero), after rounding, would be greater than the largest value that
32457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    can be handled by the implementation (the value Emax).
32557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
32657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    The result depends on the rounding mode:
32757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
32857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    For round-half-up and round-half-even (and for round-half-down and
32957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    round-up, if implemented), the result of the operation is [sign,inf],
330e43a3a66a9d8a99021d76ff4d07dec7b8cfd62caChristoph Bumiller    where sign is the sign of the intermediate result.  For round-down, the
33157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    result is the largest finite number that can be represented in the
33257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    current precision, with the sign of the intermediate result.  For
33357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    round-ceiling, the result is the same as for round-down if the sign of
33457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    the intermediate result is 1, or is [0,inf] otherwise.  For round-floor,
33557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    the result is the same as for round-down if the sign of the intermediate
33657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    result is 0, or is [1,inf] otherwise.  In all cases, Inexact and Rounded
33757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    will also be raised.
33857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """
33957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
34057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def handle(self, context, sign, *args):
34157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
34257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                                ROUND_HALF_DOWN, ROUND_UP):
34357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return Infsign[sign]
34457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if sign == 0:
34557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if context.rounding == ROUND_CEILING:
34657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return Infsign[sign]
34757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return _dec_from_triple(sign, '9'*context.prec,
34857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                            context.Emax-context.prec+1)
34957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if sign == 1:
35057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if context.rounding == ROUND_FLOOR:
35157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return Infsign[sign]
35257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return _dec_from_triple(sign, '9'*context.prec,
35357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                             context.Emax-context.prec+1)
35457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
35557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
35657594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerclass Underflow(Inexact, Rounded, Subnormal):
35757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """Numerical underflow with result rounded to 0.
35857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
35957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    This occurs and signals underflow if a result is inexact and the
36057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    adjusted exponent of the result would be smaller (more negative) than
36157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    the smallest value that can be handled by the implementation (the value
36257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    Emin).  That is, the result is both inexact and subnormal.
36357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
36457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    The result after an underflow will be a subnormal number rounded, if
36557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    necessary, so that its exponent is not less than Etiny.  This may result
36614d5f975a65c57830077dabf2f95261afbc51773Francisco Jerez    in 0 with the sign of the intermediate result and an exponent of Etiny.
36757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
36857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    In all cases, Inexact, Rounded, and Subnormal will also be raised.
36957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """
37057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
37157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller# List of public traps and flags
37257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
37357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller           Underflow, InvalidOperation, Subnormal]
37457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
37557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller# Map conditions (per the spec) to signals
37657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller_condition_map = {ConversionSyntax:InvalidOperation,
37757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                  DivisionImpossible:InvalidOperation,
37857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                  DivisionUndefined:InvalidOperation,
37914d5f975a65c57830077dabf2f95261afbc51773Francisco Jerez                  InvalidContext:InvalidOperation}
38057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
38157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller##### Context Functions ##################################################
38257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
38357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller# The getcontext() and setcontext() function manage access to a thread-local
38457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller# current context.  Py2.4 offers direct support for thread locals.  If that
38557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller# is not available, use threading.currentThread() which is slower but will
38657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller# work for older Pythons.  If threads are not part of the build, create a
38757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller# mock threading object with threading.local() returning the module namespace.
38857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
38957594065c30feec9376be9b2132659f7d87362eeChristoph Bumillertry:
39057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    import threading
39157594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerexcept ImportError:
39214d5f975a65c57830077dabf2f95261afbc51773Francisco Jerez    # Python was compiled without threads; create a mock object instead
3938cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerez    import sys
39457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    class MockThreading(object):
39557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        def local(self, sys=sys):
39657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return sys.modules[__name__]
39757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    threading = MockThreading()
39857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    del sys, MockThreading
39957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
40057594065c30feec9376be9b2132659f7d87362eeChristoph Bumillertry:
40157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    threading.local
40257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
40357594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerexcept AttributeError:
40457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
40557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    # To fix reloading, force it to create a new context
40657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    # Old contexts have different exceptions in their dicts, making problems.
40757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    if hasattr(threading.currentThread(), '__decimal_context__'):
40857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        del threading.currentThread().__decimal_context__
40957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
41057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def setcontext(context):
41157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """Set this thread's context to context."""
41257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if context in (DefaultContext, BasicContext, ExtendedContext):
413d6d1f0e4a25c9fbefce7485d77617855a8ea956aFrancisco Jerez            context = context.copy()
41457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            context.clear_flags()
41557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        threading.currentThread().__decimal_context__ = context
41657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
4179362d4bc0a03860ec386156cf499e855a9c2d2a5Christoph Bumiller    def getcontext():
41857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """Returns this thread's context.
41957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
42057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        If this thread does not yet have a context, returns
42157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        a new context and sets this thread's context.
42257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        New contexts are copies of DefaultContext.
42357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """
42457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        try:
42557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return threading.currentThread().__decimal_context__
42657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        except AttributeError:
42757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            context = Context()
42857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            threading.currentThread().__decimal_context__ = context
42957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return context
43014d5f975a65c57830077dabf2f95261afbc51773Francisco Jerez
4318cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerezelse:
43257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
43357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    local = threading.local()
43457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    if hasattr(local, '__decimal_context__'):
43557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        del local.__decimal_context__
43657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
43757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def getcontext(_local=local):
43857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """Returns this thread's context.
43914d5f975a65c57830077dabf2f95261afbc51773Francisco Jerez
44014d5f975a65c57830077dabf2f95261afbc51773Francisco Jerez        If this thread does not yet have a context, returns
44157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        a new context and sets this thread's context.
44257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        New contexts are copies of DefaultContext.
44357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """
44457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        try:
44557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return _local.__decimal_context__
44657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        except AttributeError:
44757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            context = Context()
44857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            _local.__decimal_context__ = context
44957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return context
45057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
45157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def setcontext(context, _local=local):
45257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """Set this thread's context to context."""
4538cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerez        if context in (DefaultContext, BasicContext, ExtendedContext):
45457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            context = context.copy()
45557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            context.clear_flags()
45657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        _local.__decimal_context__ = context
45757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
45857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    del threading, local        # Don't contaminate the namespace
45957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
46057594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerdef localcontext(ctx=None):
461da28ba00d84f59650bf180769d9d9a1609eb6164Francisco Jerez    """Return a context manager for a copy of the supplied context
46257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
463a05e6a3fa28168d58a13cfb07f7a664e84b925aeFrancisco Jerez    Uses a copy of the current context if no context is specified
46457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    The returned context manager creates a local decimal context
46557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    in a with statement:
46657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        def sin(x):
46757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller             with localcontext() as ctx:
46857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                 ctx.prec += 2
469a765d7880f80d01be261a5d1f4b356a2b6fcfaadChristoph Bumiller                 # Rest of sin calculation algorithm
47057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                 # uses a precision 2 greater than normal
4719362d4bc0a03860ec386156cf499e855a9c2d2a5Christoph Bumiller             return +s  # Convert result to normal precision
4729362d4bc0a03860ec386156cf499e855a9c2d2a5Christoph Bumiller
47357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller         def sin(x):
47457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller             with localcontext(ExtendedContext):
47557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                 # Rest of sin calculation algorithm
4768cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerez                 # uses the Extended Context from the
47757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                 # General Decimal Arithmetic Specification
47857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller             return +s  # Convert result to normal context
47957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
48057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """
48157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    # The string below can't be included in the docstring until Python 2.6
48257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    # as the doctest module doesn't understand __future__ statements
48357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """
48457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    >>> from __future__ import with_statement
48557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    >>> print getcontext().prec
48657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    28
48757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    >>> with localcontext():
4888cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerez    ...     ctx = getcontext()
4898cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerez    ...     ctx.prec += 2
4908cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerez    ...     print ctx.prec
4918cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerez    ...
4928cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerez    30
4938cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerez    >>> with localcontext(ExtendedContext):
49457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    ...     print getcontext().prec
49557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    ...
49657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    9
49757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    >>> print getcontext().prec
49857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    28
49957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """
50057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    if ctx is None: ctx = getcontext()
50157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    return _ContextManager(ctx)
50257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
50357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
50457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller##### Decimal class #######################################################
50557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
50657594065c30feec9376be9b2132659f7d87362eeChristoph Bumillerclass Decimal(object):
50757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    """Floating point class for decimal arithmetic."""
508da28ba00d84f59650bf180769d9d9a1609eb6164Francisco Jerez
50957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    __slots__ = ('_exp','_int','_sign', '_is_special')
510a765d7880f80d01be261a5d1f4b356a2b6fcfaadChristoph Bumiller    # Generally, the value of the Decimal instance is given by
511a765d7880f80d01be261a5d1f4b356a2b6fcfaadChristoph Bumiller    #  (-1)**_sign * _int * 10**_exp
512a05e6a3fa28168d58a13cfb07f7a664e84b925aeFrancisco Jerez    # Special values are signified by _is_special == True
51357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
51457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    # We're immutable, so use __new__ not __init__
51557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def __new__(cls, value="0", context=None):
51657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """Create a decimal point instance.
517e43a3a66a9d8a99021d76ff4d07dec7b8cfd62caChristoph Bumiller
518e43a3a66a9d8a99021d76ff4d07dec7b8cfd62caChristoph Bumiller        >>> Decimal('3.14')              # string input
519e43a3a66a9d8a99021d76ff4d07dec7b8cfd62caChristoph Bumiller        Decimal('3.14')
520e43a3a66a9d8a99021d76ff4d07dec7b8cfd62caChristoph Bumiller        >>> Decimal((0, (3, 1, 4), -2))  # tuple (sign, digit_tuple, exponent)
521e43a3a66a9d8a99021d76ff4d07dec7b8cfd62caChristoph Bumiller        Decimal('3.14')
52257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        >>> Decimal(314)                 # int or long
52357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        Decimal('314')
52457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        >>> Decimal(Decimal(314))        # another decimal instance
52557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        Decimal('314')
52657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        >>> Decimal('  3.14  \\n')        # leading and trailing whitespace okay
52757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        Decimal('3.14')
528da28ba00d84f59650bf180769d9d9a1609eb6164Francisco Jerez        """
52957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
530a05e6a3fa28168d58a13cfb07f7a664e84b925aeFrancisco Jerez        # Note that the coefficient, self._int, is actually stored as
53157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # a string rather than as a tuple of digits.  This speeds up
53257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # the "digits to integer" and "integer to digits" conversions
53357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # that are used in almost every arithmetic operation on
534a765d7880f80d01be261a5d1f4b356a2b6fcfaadChristoph Bumiller        # Decimals.  This is an internal detail: the as_tuple function
535a765d7880f80d01be261a5d1f4b356a2b6fcfaadChristoph Bumiller        # and the Decimal constructor still deal with tuples of
53657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # digits.
53757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
53857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        self = object.__new__(cls)
53957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
54057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # From a string
54157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # REs insist on real strings, so we can too.
54257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if isinstance(value, basestring):
54357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            m = _parser(value.strip())
54457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if m is None:
54557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                if context is None:
54657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                    context = getcontext()
54757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return context._raise_error(ConversionSyntax,
54857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                                "Invalid literal for Decimal: %r" % value)
54957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
55057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if m.group('sign') == "-":
55157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                self._sign = 1
55257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            else:
55357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                self._sign = 0
55457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            intpart = m.group('int')
55557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if intpart is not None:
55657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                # finite number
55757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                fracpart = m.group('frac')
55857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                exp = int(m.group('exp') or '0')
55957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                if fracpart is not None:
560d6d1f0e4a25c9fbefce7485d77617855a8ea956aFrancisco Jerez                    self._int = (intpart+fracpart).lstrip('0') or '0'
56157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                    self._exp = exp - len(fracpart)
56257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                else:
56357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                    self._int = intpart.lstrip('0') or '0'
56457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                    self._exp = exp
56557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                self._is_special = False
566da28ba00d84f59650bf180769d9d9a1609eb6164Francisco Jerez            else:
56757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                diag = m.group('diag')
568784848a94d621b11020838fc058fc04a7fc57aa9Francisco Jerez                if diag is not None:
569784848a94d621b11020838fc058fc04a7fc57aa9Francisco Jerez                    # NaN
57057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                    self._int = diag.lstrip('0')
57157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                    if m.group('signal'):
57257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                        self._exp = 'N'
57357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                    else:
57457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                        self._exp = 'n'
57557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                else:
57657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                    # infinity
57757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                    self._int = '0'
57857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                    self._exp = 'F'
57957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                self._is_special = True
58057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return self
58157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
58257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # From an integer
58357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if isinstance(value, (int,long)):
58457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if value >= 0:
585d6d1f0e4a25c9fbefce7485d77617855a8ea956aFrancisco Jerez                self._sign = 0
586d6d1f0e4a25c9fbefce7485d77617855a8ea956aFrancisco Jerez            else:
58757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                self._sign = 1
58857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            self._exp = 0
58957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            self._int = str(abs(value))
59057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            self._is_special = False
59157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return self
59257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
59357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # From another decimal
59457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if isinstance(value, Decimal):
59557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            self._exp  = value._exp
59657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            self._sign = value._sign
59757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            self._int  = value._int
59857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            self._is_special  = value._is_special
599a05e6a3fa28168d58a13cfb07f7a664e84b925aeFrancisco Jerez            return self
600a05e6a3fa28168d58a13cfb07f7a664e84b925aeFrancisco Jerez
60157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # From an internal working value
6028cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerez        if isinstance(value, _WorkRep):
6038cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerez            self._sign = value.sign
6048cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerez            self._int = str(value.int)
60557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            self._exp = int(value.exp)
60657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            self._is_special = False
60757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return self
6089362d4bc0a03860ec386156cf499e855a9c2d2a5Christoph Bumiller
6099362d4bc0a03860ec386156cf499e855a9c2d2a5Christoph Bumiller        # tuple/list conversion (possibly from as_tuple())
6109362d4bc0a03860ec386156cf499e855a9c2d2a5Christoph Bumiller        if isinstance(value, (list,tuple)):
6119362d4bc0a03860ec386156cf499e855a9c2d2a5Christoph Bumiller            if len(value) != 3:
6129362d4bc0a03860ec386156cf499e855a9c2d2a5Christoph Bumiller                raise ValueError('Invalid tuple size in creation of Decimal '
6139362d4bc0a03860ec386156cf499e855a9c2d2a5Christoph Bumiller                                 'from list or tuple.  The list or tuple '
6149362d4bc0a03860ec386156cf499e855a9c2d2a5Christoph Bumiller                                 'should have exactly three elements.')
61557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            # process sign.  The isinstance test rejects floats
61657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
6178cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerez                raise ValueError("Invalid sign.  The first value in the tuple "
6188cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerez                                 "should be an integer; either 0 for a "
6199362d4bc0a03860ec386156cf499e855a9c2d2a5Christoph Bumiller                                 "positive number or 1 for a negative number.")
6208cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerez            self._sign = value[0]
6218cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerez            if value[2] == 'F':
6228cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerez                # infinity: value[1] is ignored
6239362d4bc0a03860ec386156cf499e855a9c2d2a5Christoph Bumiller                self._int = '0'
6248cc2eca5df0116aa7fb8233a9ab6ad1c9e4203cdFrancisco Jerez                self._exp = value[2]
62557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                self._is_special = True
626e43a3a66a9d8a99021d76ff4d07dec7b8cfd62caChristoph Bumiller            else:
62757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                # process and validate the digits in value[1]
62857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                digits = []
62957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                for digit in value[1]:
63057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                    if isinstance(digit, (int, long)) and 0 <= digit <= 9:
631ca1fc2b86400e3fc9dd0517863e22721b5e91c77Christoph Bumiller                        # skip leading zeros
63257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                        if digits or digit != 0:
63356cf2da02226aee6b7476675c0e05ac7c218756eChristoph Bumiller                            digits.append(digit)
63456cf2da02226aee6b7476675c0e05ac7c218756eChristoph Bumiller                    else:
63556cf2da02226aee6b7476675c0e05ac7c218756eChristoph Bumiller                        raise ValueError("The second value in the tuple must "
6369362d4bc0a03860ec386156cf499e855a9c2d2a5Christoph Bumiller                                         "be composed of integers in the range "
637e43a3a66a9d8a99021d76ff4d07dec7b8cfd62caChristoph Bumiller                                         "0 through 9.")
6389362d4bc0a03860ec386156cf499e855a9c2d2a5Christoph Bumiller                if value[2] in ('n', 'N'):
639e43a3a66a9d8a99021d76ff4d07dec7b8cfd62caChristoph Bumiller                    # NaN: digits form the diagnostic
64057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                    self._int = ''.join(map(str, digits))
64157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                    self._exp = value[2]
64257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                    self._is_special = True
64357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                elif isinstance(value[2], (int, long)):
64457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                    # finite number: digits give the coefficient
64557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                    self._int = ''.join(map(str, digits or [0]))
64657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                    self._exp = value[2]
64757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                    self._is_special = False
64857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                else:
64957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                    raise ValueError("The third value in the tuple must "
65057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                                     "be an integer, or one of the "
65157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                                     "strings 'F', 'n', 'N'.")
65257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return self
65357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
65457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if isinstance(value, float):
65557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            raise TypeError("Cannot convert float to Decimal.  " +
65657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                            "First convert the float to a string")
65757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
65857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        raise TypeError("Cannot convert %r to Decimal" % value)
65957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
66057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def _isnan(self):
66157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """Returns whether the number is not actually one.
66257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
66357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        0 if a number
66457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        1 if NaN
66557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        2 if sNaN
66657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """
66757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if self._is_special:
66857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            exp = self._exp
66957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if exp == 'n':
67057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return 1
67157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            elif exp == 'N':
67257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return 2
67357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return 0
67457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
67557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def _isinfinity(self):
67657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """Returns whether the number is infinite
67757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
67857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        0 if finite or not a number
67957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        1 if +INF
68057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        -1 if -INF
68157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """
68257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if self._exp == 'F':
68357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if self._sign:
68457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return -1
68557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return 1
68657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return 0
68757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
68857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def _check_nans(self, other=None, context=None):
68957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """Returns whether the number is not actually one.
69057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
69157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if self, other are sNaN, signal
69257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if self, other are NaN return nan
69357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return 0
69457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
69557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        Done before operations.
69657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """
69757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
69857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        self_is_nan = self._isnan()
69957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if other is None:
70057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            other_is_nan = False
70157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        else:
70257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            other_is_nan = other._isnan()
70357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
70457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if self_is_nan or other_is_nan:
7059362d4bc0a03860ec386156cf499e855a9c2d2a5Christoph Bumiller            if context is None:
7069362d4bc0a03860ec386156cf499e855a9c2d2a5Christoph Bumiller                context = getcontext()
7079362d4bc0a03860ec386156cf499e855a9c2d2a5Christoph Bumiller
7089362d4bc0a03860ec386156cf499e855a9c2d2a5Christoph Bumiller            if self_is_nan == 2:
70957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return context._raise_error(InvalidOperation, 'sNaN',
71057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                                        self)
71157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if other_is_nan == 2:
71257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return context._raise_error(InvalidOperation, 'sNaN',
71357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                                        other)
71457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if self_is_nan:
71557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return self._fix_nan(context)
71657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
71757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return other._fix_nan(context)
71857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return 0
71957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
72057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def _compare_check_nans(self, other, context):
72157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """Version of _check_nans used for the signaling comparisons
72257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        compare_signal, __le__, __lt__, __ge__, __gt__.
72357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
72457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        Signal InvalidOperation if either self or other is a (quiet
72557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        or signaling) NaN.  Signaling NaNs take precedence over quiet
72657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        NaNs.
72757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
72857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        Return 0 if neither operand is a NaN.
72957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
73057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """
73157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if context is None:
73257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            context = getcontext()
73357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
73457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if self._is_special or other._is_special:
73557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if self.is_snan():
73657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return context._raise_error(InvalidOperation,
73757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                                            'comparison involving sNaN',
73857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                                            self)
73957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            elif other.is_snan():
74057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return context._raise_error(InvalidOperation,
74157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                                            'comparison involving sNaN',
74257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                                            other)
74357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            elif self.is_qnan():
74457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return context._raise_error(InvalidOperation,
74557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                                            'comparison involving NaN',
74657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                                            self)
74757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            elif other.is_qnan():
74857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return context._raise_error(InvalidOperation,
74957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                                            'comparison involving NaN',
75057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                                            other)
75157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return 0
75257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
75357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def __nonzero__(self):
75457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """Return True if self is nonzero; otherwise return False.
75557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
75657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        NaNs and infinities are considered nonzero.
75757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """
75857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return self._is_special or self._int != '0'
75957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
76057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def _cmp(self, other):
76157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """Compare the two non-NaN decimal instances self and other.
76257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
76357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        Returns -1 if self < other, 0 if self == other and 1
76457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if self > other.  This routine is for internal use only."""
76557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
76657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if self._is_special or other._is_special:
76757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return cmp(self._isinfinity(), other._isinfinity())
76857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
76957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # check for zeros;  note that cmp(0, -0) should return 0
77057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if not self:
77157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if not other:
77257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return 0
77357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            else:
77457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return -((-1)**other._sign)
77557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if not other:
776a05e6a3fa28168d58a13cfb07f7a664e84b925aeFrancisco Jerez            return (-1)**self._sign
777a05e6a3fa28168d58a13cfb07f7a664e84b925aeFrancisco Jerez
77857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # If different signs, neg one is less
77957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if other._sign < self._sign:
78057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return -1
78157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if self._sign < other._sign:
78257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return 1
78357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
78457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        self_adjusted = self.adjusted()
78557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        other_adjusted = other.adjusted()
78657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if self_adjusted == other_adjusted:
78757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            self_padded = self._int + '0'*(self._exp - other._exp)
78857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            other_padded = other._int + '0'*(other._exp - self._exp)
78957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return cmp(self_padded, other_padded) * (-1)**self._sign
79057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        elif self_adjusted > other_adjusted:
79157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return (-1)**self._sign
79257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        else: # self_adjusted < other_adjusted
79357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return -((-1)**self._sign)
79457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
79557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    # Note: The Decimal standard doesn't cover rich comparisons for
79657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    # Decimals.  In particular, the specification is silent on the
79757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    # subject of what should happen for a comparison involving a NaN.
79857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    # We take the following approach:
79957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    #
80057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    #   == comparisons involving a NaN always return False
80157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    #   != comparisons involving a NaN always return True
80257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    #   <, >, <= and >= comparisons involving a (quiet or signaling)
8039c930639d9f6d713ccfd16b390a41a9f584f348cChristoph Bumiller    #      NaN signal InvalidOperation, and return False if the
80457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    #      InvalidOperation is not trapped.
80557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    #
80657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    # This behavior is designed to conform as closely as possible to
80757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    # that specified by IEEE 754.
80857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
80957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def __eq__(self, other):
81057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        other = _convert_other(other)
81157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if other is NotImplemented:
81257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return other
81357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if self.is_nan() or other.is_nan():
81457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return False
81557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return self._cmp(other) == 0
81657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
81757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def __ne__(self, other):
81857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        other = _convert_other(other)
81957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if other is NotImplemented:
820a05e6a3fa28168d58a13cfb07f7a664e84b925aeFrancisco Jerez            return other
821a05e6a3fa28168d58a13cfb07f7a664e84b925aeFrancisco Jerez        if self.is_nan() or other.is_nan():
82257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return True
82357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return self._cmp(other) != 0
82457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
82557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def __lt__(self, other, context=None):
82657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        other = _convert_other(other)
82757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if other is NotImplemented:
82857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return other
82957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        ans = self._compare_check_nans(other, context)
83057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if ans:
83157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return False
83257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return self._cmp(other) < 0
8339bb36d54a2c69ebdc9d1c9c4c71945060de8c860Francisco Jerez
83457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def __le__(self, other, context=None):
835784848a94d621b11020838fc058fc04a7fc57aa9Francisco Jerez        other = _convert_other(other)
836784848a94d621b11020838fc058fc04a7fc57aa9Francisco Jerez        if other is NotImplemented:
837784848a94d621b11020838fc058fc04a7fc57aa9Francisco Jerez            return other
83857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        ans = self._compare_check_nans(other, context)
83957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if ans:
84057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return False
84157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return self._cmp(other) <= 0
84257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
84357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def __gt__(self, other, context=None):
84457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        other = _convert_other(other)
84557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if other is NotImplemented:
84657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return other
84757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        ans = self._compare_check_nans(other, context)
84857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if ans:
84957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return False
85057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return self._cmp(other) > 0
85157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
85257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def __ge__(self, other, context=None):
85357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        other = _convert_other(other)
85457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if other is NotImplemented:
85557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return other
85657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        ans = self._compare_check_nans(other, context)
857784848a94d621b11020838fc058fc04a7fc57aa9Francisco Jerez        if ans:
858784848a94d621b11020838fc058fc04a7fc57aa9Francisco Jerez            return False
85957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return self._cmp(other) >= 0
86057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
86157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def compare(self, other, context=None):
86257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """Compares one to another.
86357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
86457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        -1 => a < b
86557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        0  => a = b
86657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        1  => a > b
86757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        NaN => one is NaN
86857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        Like __cmp__, but returns Decimal instances.
86957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """
87057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        other = _convert_other(other, raiseit=True)
87157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
87257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # Compare(NaN, NaN) = NaN
87357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if (self._is_special or other and other._is_special):
87457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            ans = self._check_nans(other, context)
87557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if ans:
87657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return ans
87757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
87857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return Decimal(self._cmp(other))
87957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
88057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def __hash__(self):
88157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """x.__hash__() <==> hash(x)"""
88257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # Decimal integers must hash the same as the ints
88357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        #
88457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # The hash of a nonspecial noninteger Decimal must depend only
88557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # on the value of that Decimal, and not on its representation.
88657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
88757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if self._is_special:
888c04d6d95e0efb8eea4d788d8d7b629209a3afaeaChristoph Bumiller            if self._isnan():
889c04d6d95e0efb8eea4d788d8d7b629209a3afaeaChristoph Bumiller                raise TypeError('Cannot hash a NaN value.')
890c04d6d95e0efb8eea4d788d8d7b629209a3afaeaChristoph Bumiller            return hash(str(self))
891c04d6d95e0efb8eea4d788d8d7b629209a3afaeaChristoph Bumiller        if not self:
89257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return 0
89357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if self._isinteger():
89457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            op = _WorkRep(self.to_integral_value())
89557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            # to make computation feasible for Decimals with large
89657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            # exponent, we use the fact that hash(n) == hash(m) for
89757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            # any two nonzero integers n and m such that (i) n and m
89857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            # have the same sign, and (ii) n is congruent to m modulo
89957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            # 2**64-1.  So we can replace hash((-1)**s*c*10**e) with
90057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            # hash((-1)**s*c*pow(10, e, 2**64-1).
90157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
90257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # The value of a nonzero nonspecial Decimal instance is
9033e9150cd961b2399e402e940400deae11ec7852fFrancisco Jerez        # faithfully represented by the triple consisting of its sign,
90457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # its adjusted exponent, and its coefficient with trailing
90557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # zeros removed.
90657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return hash((self._sign,
90757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                     self._exp+len(self._int),
90857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                     self._int.rstrip('0')))
90957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
91057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def as_tuple(self):
91157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """Represents the number as a triple tuple.
91257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
91357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        To show the internals exactly as they are.
91457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """
91557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
91657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
91757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def __repr__(self):
91857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """Represents the number as an instance of Decimal."""
91957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # Invariant:  eval(repr(d)) == d
92057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return "Decimal('%s')" % str(self)
92157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
92257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def __str__(self, eng=False, context=None):
92357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """Return string representation of the number in scientific notation.
92457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
925c04d6d95e0efb8eea4d788d8d7b629209a3afaeaChristoph Bumiller        Captures all of the information in the underlying representation.
926c04d6d95e0efb8eea4d788d8d7b629209a3afaeaChristoph Bumiller        """
92757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
92857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        sign = ['', '-'][self._sign]
92957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if self._is_special:
93057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if self._exp == 'F':
93157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return sign + 'Infinity'
93298116cc3dc3fc2cd84990cc2c968f05fe2978b4aFrancisco Jerez            elif self._exp == 'n':
93357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return sign + 'NaN' + self._int
93457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            else: # self._exp == 'N'
935d32ebb8c304725fa6bb7ec2d3d40ce828c713917Francisco Jerez                return sign + 'sNaN' + self._int
936d32ebb8c304725fa6bb7ec2d3d40ce828c713917Francisco Jerez
93757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # number of digits of self._int to left of decimal point
93857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        leftdigits = self._exp + len(self._int)
93957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
94098116cc3dc3fc2cd84990cc2c968f05fe2978b4aFrancisco Jerez        # dotplace is number of digits of self._int to the left of the
94157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # decimal point in the mantissa of the output string (that is,
94257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        # after adjusting the exponent)
94357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if self._exp <= 0 and leftdigits > -6:
94457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            # no exponent required
94557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            dotplace = leftdigits
94657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        elif not eng:
94757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            # usual scientific notation: 1 digit on left of the point
94857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            dotplace = 1
94957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        elif self._int == '0':
95057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            # engineering notation, zero
95157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            dotplace = (leftdigits + 1) % 3 - 1
95257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        else:
95357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            # engineering notation, nonzero
95457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            dotplace = (leftdigits - 1) % 3 + 1
95557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
95657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if dotplace <= 0:
957898b0981b6c90d2f1e446a532b6ac3cbbb49747dFrancisco Jerez            intpart = '0'
9583e9150cd961b2399e402e940400deae11ec7852fFrancisco Jerez            fracpart = '.' + '0'*(-dotplace) + self._int
95957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        elif dotplace >= len(self._int):
96057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            intpart = self._int+'0'*(dotplace-len(self._int))
96157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            fracpart = ''
962a3dd45e1c27e4e55dadb9467c2ea428f58083ac1Francisco Jerez        else:
963a3dd45e1c27e4e55dadb9467c2ea428f58083ac1Francisco Jerez            intpart = self._int[:dotplace]
964a3dd45e1c27e4e55dadb9467c2ea428f58083ac1Francisco Jerez            fracpart = '.' + self._int[dotplace:]
965a3dd45e1c27e4e55dadb9467c2ea428f58083ac1Francisco Jerez        if leftdigits == dotplace:
96657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            exp = ''
96757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        else:
96857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if context is None:
96957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                context = getcontext()
97057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
97157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
97257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return sign + intpart + fracpart + exp
97357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
97457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def to_eng_string(self, context=None):
97557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """Convert to engineering-type string.
97657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
97757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        Engineering notation has an exponent which is a multiple of 3, so there
97857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        are up to 3 digits left of the decimal place.
97957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
980e43a3a66a9d8a99021d76ff4d07dec7b8cfd62caChristoph Bumiller        Same rules for when in exponential and when as a value as in __str__.
981e43a3a66a9d8a99021d76ff4d07dec7b8cfd62caChristoph Bumiller        """
982e43a3a66a9d8a99021d76ff4d07dec7b8cfd62caChristoph Bumiller        return self.__str__(eng=True, context=context)
983e43a3a66a9d8a99021d76ff4d07dec7b8cfd62caChristoph Bumiller
984e43a3a66a9d8a99021d76ff4d07dec7b8cfd62caChristoph Bumiller    def __neg__(self, context=None):
98557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """Returns a copy with the sign switched.
98657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
98757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        Rounds, if it has reason.
98857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """
98957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if self._is_special:
99057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            ans = self._check_nans(context=context)
9913e9150cd961b2399e402e940400deae11ec7852fFrancisco Jerez            if ans:
99257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return ans
99357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
99498116cc3dc3fc2cd84990cc2c968f05fe2978b4aFrancisco Jerez        if not self:
99557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            # -Decimal('0') is Decimal('0'), not Decimal('-0')
99657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            ans = self.copy_abs()
99757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        else:
99857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            ans = self.copy_negate()
99957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
100057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if context is None:
100157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            context = getcontext()
100257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return ans._fix(context)
100357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
100457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def __pos__(self, context=None):
100557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """Returns a copy, unless it is a sNaN.
100657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
100757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        Rounds the number (if more then precision digits)
100857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """
100957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if self._is_special:
101057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            ans = self._check_nans(context=context)
101157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if ans:
101257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return ans
101357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
101457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if not self:
101557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            # + (-0) = 0
101657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            ans = self.copy_abs()
101757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        else:
101857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            ans = Decimal(self)
101957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
102057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if context is None:
102157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            context = getcontext()
102257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return ans._fix(context)
102357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
102457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def __abs__(self, round=True, context=None):
102557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """Returns the absolute value of self.
102657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
102757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        If the keyword argument 'round' is false, do not round.  The
10285e4b2a1a47ca9a173f6419ed2f12c9fba80e757cFrancisco Jerez        expression self.__abs__(round=False) is equivalent to
102957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        self.copy_abs().
103057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """
103157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if not round:
103257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return self.copy_abs()
103357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
103457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if self._is_special:
103557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            ans = self._check_nans(context=context)
103657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if ans:
103757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return ans
103857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
103957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if self._sign:
104057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            ans = self.__neg__(context=context)
104157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        else:
104298116cc3dc3fc2cd84990cc2c968f05fe2978b4aFrancisco Jerez            ans = self.__pos__(context=context)
104398116cc3dc3fc2cd84990cc2c968f05fe2978b4aFrancisco Jerez
104457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        return ans
104557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
104657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller    def __add__(self, other, context=None):
104757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """Returns self + other.
104857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
104957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        -INF + INF (or the reverse) cause InvalidOperation errors.
105057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        """
105157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        other = _convert_other(other)
105257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if other is NotImplemented:
105357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return other
105457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
105557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if context is None:
1056e43a3a66a9d8a99021d76ff4d07dec7b8cfd62caChristoph Bumiller            context = getcontext()
105757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
105857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if self._is_special or other._is_special:
105957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            ans = self._check_nans(other, context)
106057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if ans:
106157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return ans
106257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
106357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if self._isinfinity():
106457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                # If both INF, same sign => same as both, opposite => error.
106557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                if self._sign != other._sign and other._isinfinity():
106657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                    return context._raise_error(InvalidOperation, '-INF + INF')
106757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return Decimal(self)
106857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if other._isinfinity():
1069322bc7ed68ed92233c97168c036d0aa50c11a20eChristoph Bumiller                return Decimal(other)  # Can't both be infinity here
1070322bc7ed68ed92233c97168c036d0aa50c11a20eChristoph Bumiller
1071322bc7ed68ed92233c97168c036d0aa50c11a20eChristoph Bumiller        exp = min(self._exp, other._exp)
107257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        negativezero = 0
107357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if context.rounding == ROUND_FLOOR and self._sign != other._sign:
107457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            # If the answer is 0, the sign should be negative, in this case.
107557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            negativezero = 1
107657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
107757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if not self and not other:
107857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            sign = min(self._sign, other._sign)
107957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if negativezero:
108057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                sign = 1
108157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            ans = _dec_from_triple(sign, '0', exp)
108257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            ans = ans._fix(context)
108357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return ans
108457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if not self:
108557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            exp = max(exp, other._exp - context.prec-1)
108657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            ans = other._rescale(exp, context.rounding)
108757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            ans = ans._fix(context)
108857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return ans
108957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if not other:
109057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            exp = max(exp, self._exp - context.prec-1)
109157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            ans = self._rescale(exp, context.rounding)
109257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            ans = ans._fix(context)
109357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            return ans
109457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
109557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        op1 = _WorkRep(self)
109657594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        op2 = _WorkRep(other)
109757594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        op1, op2 = _normalize(op1, op2, context.prec)
109857594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller
109957594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        result = _WorkRep()
110057594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller        if op1.sign != op2.sign:
110157594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            # Equal and opposite
110257594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller            if op1.int == op2.int:
110357594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                ans = _dec_from_triple(negativezero, '0', exp)
110457594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                ans = ans._fix(context)
110557594065c30feec9376be9b2132659f7d87362eeChristoph Bumiller                return ans
1106            if op1.int < op2.int:
1107                op1, op2 = op2, op1
1108                # OK, now abs(op1) > abs(op2)
1109            if op1.sign == 1:
1110                result.sign = 1
1111                op1.sign, op2.sign = op2.sign, op1.sign
1112            else:
1113                result.sign = 0
1114                # So we know the sign, and op1 > 0.
1115        elif op1.sign == 1:
1116            result.sign = 1
1117            op1.sign, op2.sign = (0, 0)
1118        else:
1119            result.sign = 0
1120        # Now, op1 > abs(op2) > 0
1121
1122        if op2.sign == 0:
1123            result.int = op1.int + op2.int
1124        else:
1125            result.int = op1.int - op2.int
1126
1127        result.exp = op1.exp
1128        ans = Decimal(result)
1129        ans = ans._fix(context)
1130        return ans
1131
1132    __radd__ = __add__
1133
1134    def __sub__(self, other, context=None):
1135        """Return self - other"""
1136        other = _convert_other(other)
1137        if other is NotImplemented:
1138            return other
1139
1140        if self._is_special or other._is_special:
1141            ans = self._check_nans(other, context=context)
1142            if ans:
1143                return ans
1144
1145        # self - other is computed as self + other.copy_negate()
1146        return self.__add__(other.copy_negate(), context=context)
1147
1148    def __rsub__(self, other, context=None):
1149        """Return other - self"""
1150        other = _convert_other(other)
1151        if other is NotImplemented:
1152            return other
1153
1154        return other.__sub__(self, context=context)
1155
1156    def __mul__(self, other, context=None):
1157        """Return self * other.
1158
1159        (+-) INF * 0 (or its reverse) raise InvalidOperation.
1160        """
1161        other = _convert_other(other)
1162        if other is NotImplemented:
1163            return other
1164
1165        if context is None:
1166            context = getcontext()
1167
1168        resultsign = self._sign ^ other._sign
1169
1170        if self._is_special or other._is_special:
1171            ans = self._check_nans(other, context)
1172            if ans:
1173                return ans
1174
1175            if self._isinfinity():
1176                if not other:
1177                    return context._raise_error(InvalidOperation, '(+-)INF * 0')
1178                return Infsign[resultsign]
1179
1180            if other._isinfinity():
1181                if not self:
1182                    return context._raise_error(InvalidOperation, '0 * (+-)INF')
1183                return Infsign[resultsign]
1184
1185        resultexp = self._exp + other._exp
1186
1187        # Special case for multiplying by zero
1188        if not self or not other:
1189            ans = _dec_from_triple(resultsign, '0', resultexp)
1190            # Fixing in case the exponent is out of bounds
1191            ans = ans._fix(context)
1192            return ans
1193
1194        # Special case for multiplying by power of 10
1195        if self._int == '1':
1196            ans = _dec_from_triple(resultsign, other._int, resultexp)
1197            ans = ans._fix(context)
1198            return ans
1199        if other._int == '1':
1200            ans = _dec_from_triple(resultsign, self._int, resultexp)
1201            ans = ans._fix(context)
1202            return ans
1203
1204        op1 = _WorkRep(self)
1205        op2 = _WorkRep(other)
1206
1207        ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
1208        ans = ans._fix(context)
1209
1210        return ans
1211    __rmul__ = __mul__
1212
1213    def __div__(self, other, context=None):
1214        """Return self / other."""
1215        other = _convert_other(other)
1216        if other is NotImplemented:
1217            return NotImplemented
1218
1219        if context is None:
1220            context = getcontext()
1221
1222        sign = self._sign ^ other._sign
1223
1224        if self._is_special or other._is_special:
1225            ans = self._check_nans(other, context)
1226            if ans:
1227                return ans
1228
1229            if self._isinfinity() and other._isinfinity():
1230                return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
1231
1232            if self._isinfinity():
1233                return Infsign[sign]
1234
1235            if other._isinfinity():
1236                context._raise_error(Clamped, 'Division by infinity')
1237                return _dec_from_triple(sign, '0', context.Etiny())
1238
1239        # Special cases for zeroes
1240        if not other:
1241            if not self:
1242                return context._raise_error(DivisionUndefined, '0 / 0')
1243            return context._raise_error(DivisionByZero, 'x / 0', sign)
1244
1245        if not self:
1246            exp = self._exp - other._exp
1247            coeff = 0
1248        else:
1249            # OK, so neither = 0, INF or NaN
1250            shift = len(other._int) - len(self._int) + context.prec + 1
1251            exp = self._exp - other._exp - shift
1252            op1 = _WorkRep(self)
1253            op2 = _WorkRep(other)
1254            if shift >= 0:
1255                coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1256            else:
1257                coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1258            if remainder:
1259                # result is not exact; adjust to ensure correct rounding
1260                if coeff % 5 == 0:
1261                    coeff += 1
1262            else:
1263                # result is exact; get as close to ideal exponent as possible
1264                ideal_exp = self._exp - other._exp
1265                while exp < ideal_exp and coeff % 10 == 0:
1266                    coeff //= 10
1267                    exp += 1
1268
1269        ans = _dec_from_triple(sign, str(coeff), exp)
1270        return ans._fix(context)
1271
1272    __truediv__ = __div__
1273
1274    def _divide(self, other, context):
1275        """Return (self // other, self % other), to context.prec precision.
1276
1277        Assumes that neither self nor other is a NaN, that self is not
1278        infinite and that other is nonzero.
1279        """
1280        sign = self._sign ^ other._sign
1281        if other._isinfinity():
1282            ideal_exp = self._exp
1283        else:
1284            ideal_exp = min(self._exp, other._exp)
1285
1286        expdiff = self.adjusted() - other.adjusted()
1287        if not self or other._isinfinity() or expdiff <= -2:
1288            return (_dec_from_triple(sign, '0', 0),
1289                    self._rescale(ideal_exp, context.rounding))
1290        if expdiff <= context.prec:
1291            op1 = _WorkRep(self)
1292            op2 = _WorkRep(other)
1293            if op1.exp >= op2.exp:
1294                op1.int *= 10**(op1.exp - op2.exp)
1295            else:
1296                op2.int *= 10**(op2.exp - op1.exp)
1297            q, r = divmod(op1.int, op2.int)
1298            if q < 10**context.prec:
1299                return (_dec_from_triple(sign, str(q), 0),
1300                        _dec_from_triple(self._sign, str(r), ideal_exp))
1301
1302        # Here the quotient is too large to be representable
1303        ans = context._raise_error(DivisionImpossible,
1304                                   'quotient too large in //, % or divmod')
1305        return ans, ans
1306
1307    def __rdiv__(self, other, context=None):
1308        """Swaps self/other and returns __div__."""
1309        other = _convert_other(other)
1310        if other is NotImplemented:
1311            return other
1312        return other.__div__(self, context=context)
1313    __rtruediv__ = __rdiv__
1314
1315    def __divmod__(self, other, context=None):
1316        """
1317        Return (self // other, self % other)
1318        """
1319        other = _convert_other(other)
1320        if other is NotImplemented:
1321            return other
1322
1323        if context is None:
1324            context = getcontext()
1325
1326        ans = self._check_nans(other, context)
1327        if ans:
1328            return (ans, ans)
1329
1330        sign = self._sign ^ other._sign
1331        if self._isinfinity():
1332            if other._isinfinity():
1333                ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1334                return ans, ans
1335            else:
1336                return (Infsign[sign],
1337                        context._raise_error(InvalidOperation, 'INF % x'))
1338
1339        if not other:
1340            if not self:
1341                ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1342                return ans, ans
1343            else:
1344                return (context._raise_error(DivisionByZero, 'x // 0', sign),
1345                        context._raise_error(InvalidOperation, 'x % 0'))
1346
1347        quotient, remainder = self._divide(other, context)
1348        remainder = remainder._fix(context)
1349        return quotient, remainder
1350
1351    def __rdivmod__(self, other, context=None):
1352        """Swaps self/other and returns __divmod__."""
1353        other = _convert_other(other)
1354        if other is NotImplemented:
1355            return other
1356        return other.__divmod__(self, context=context)
1357
1358    def __mod__(self, other, context=None):
1359        """
1360        self % other
1361        """
1362        other = _convert_other(other)
1363        if other is NotImplemented:
1364            return other
1365
1366        if context is None:
1367            context = getcontext()
1368
1369        ans = self._check_nans(other, context)
1370        if ans:
1371            return ans
1372
1373        if self._isinfinity():
1374            return context._raise_error(InvalidOperation, 'INF % x')
1375        elif not other:
1376            if self:
1377                return context._raise_error(InvalidOperation, 'x % 0')
1378            else:
1379                return context._raise_error(DivisionUndefined, '0 % 0')
1380
1381        remainder = self._divide(other, context)[1]
1382        remainder = remainder._fix(context)
1383        return remainder
1384
1385    def __rmod__(self, other, context=None):
1386        """Swaps self/other and returns __mod__."""
1387        other = _convert_other(other)
1388        if other is NotImplemented:
1389            return other
1390        return other.__mod__(self, context=context)
1391
1392    def remainder_near(self, other, context=None):
1393        """
1394        Remainder nearest to 0-  abs(remainder-near) <= other/2
1395        """
1396        if context is None:
1397            context = getcontext()
1398
1399        other = _convert_other(other, raiseit=True)
1400
1401        ans = self._check_nans(other, context)
1402        if ans:
1403            return ans
1404
1405        # self == +/-infinity -> InvalidOperation
1406        if self._isinfinity():
1407            return context._raise_error(InvalidOperation,
1408                                        'remainder_near(infinity, x)')
1409
1410        # other == 0 -> either InvalidOperation or DivisionUndefined
1411        if not other:
1412            if self:
1413                return context._raise_error(InvalidOperation,
1414                                            'remainder_near(x, 0)')
1415            else:
1416                return context._raise_error(DivisionUndefined,
1417                                            'remainder_near(0, 0)')
1418
1419        # other = +/-infinity -> remainder = self
1420        if other._isinfinity():
1421            ans = Decimal(self)
1422            return ans._fix(context)
1423
1424        # self = 0 -> remainder = self, with ideal exponent
1425        ideal_exponent = min(self._exp, other._exp)
1426        if not self:
1427            ans = _dec_from_triple(self._sign, '0', ideal_exponent)
1428            return ans._fix(context)
1429
1430        # catch most cases of large or small quotient
1431        expdiff = self.adjusted() - other.adjusted()
1432        if expdiff >= context.prec + 1:
1433            # expdiff >= prec+1 => abs(self/other) > 10**prec
1434            return context._raise_error(DivisionImpossible)
1435        if expdiff <= -2:
1436            # expdiff <= -2 => abs(self/other) < 0.1
1437            ans = self._rescale(ideal_exponent, context.rounding)
1438            return ans._fix(context)
1439
1440        # adjust both arguments to have the same exponent, then divide
1441        op1 = _WorkRep(self)
1442        op2 = _WorkRep(other)
1443        if op1.exp >= op2.exp:
1444            op1.int *= 10**(op1.exp - op2.exp)
1445        else:
1446            op2.int *= 10**(op2.exp - op1.exp)
1447        q, r = divmod(op1.int, op2.int)
1448        # remainder is r*10**ideal_exponent; other is +/-op2.int *
1449        # 10**ideal_exponent.   Apply correction to ensure that
1450        # abs(remainder) <= abs(other)/2
1451        if 2*r + (q&1) > op2.int:
1452            r -= op2.int
1453            q += 1
1454
1455        if q >= 10**context.prec:
1456            return context._raise_error(DivisionImpossible)
1457
1458        # result has same sign as self unless r is negative
1459        sign = self._sign
1460        if r < 0:
1461            sign = 1-sign
1462            r = -r
1463
1464        ans = _dec_from_triple(sign, str(r), ideal_exponent)
1465        return ans._fix(context)
1466
1467    def __floordiv__(self, other, context=None):
1468        """self // other"""
1469        other = _convert_other(other)
1470        if other is NotImplemented:
1471            return other
1472
1473        if context is None:
1474            context = getcontext()
1475
1476        ans = self._check_nans(other, context)
1477        if ans:
1478            return ans
1479
1480        if self._isinfinity():
1481            if other._isinfinity():
1482                return context._raise_error(InvalidOperation, 'INF // INF')
1483            else:
1484                return Infsign[self._sign ^ other._sign]
1485
1486        if not other:
1487            if self:
1488                return context._raise_error(DivisionByZero, 'x // 0',
1489                                            self._sign ^ other._sign)
1490            else:
1491                return context._raise_error(DivisionUndefined, '0 // 0')
1492
1493        return self._divide(other, context)[0]
1494
1495    def __rfloordiv__(self, other, context=None):
1496        """Swaps self/other and returns __floordiv__."""
1497        other = _convert_other(other)
1498        if other is NotImplemented:
1499            return other
1500        return other.__floordiv__(self, context=context)
1501
1502    def __float__(self):
1503        """Float representation."""
1504        return float(str(self))
1505
1506    def __int__(self):
1507        """Converts self to an int, truncating if necessary."""
1508        if self._is_special:
1509            if self._isnan():
1510                context = getcontext()
1511                return context._raise_error(InvalidContext)
1512            elif self._isinfinity():
1513                raise OverflowError("Cannot convert infinity to long")
1514        s = (-1)**self._sign
1515        if self._exp >= 0:
1516            return s*int(self._int)*10**self._exp
1517        else:
1518            return s*int(self._int[:self._exp] or '0')
1519
1520    __trunc__ = __int__
1521
1522    @property
1523    def real(self):
1524        return self
1525
1526    @property
1527    def imag(self):
1528        return Decimal(0)
1529
1530    def conjugate(self):
1531        return self
1532
1533    def __complex__(self):
1534        return complex(float(self))
1535
1536    def __long__(self):
1537        """Converts to a long.
1538
1539        Equivalent to long(int(self))
1540        """
1541        return long(self.__int__())
1542
1543    def _fix_nan(self, context):
1544        """Decapitate the payload of a NaN to fit the context"""
1545        payload = self._int
1546
1547        # maximum length of payload is precision if _clamp=0,
1548        # precision-1 if _clamp=1.
1549        max_payload_len = context.prec - context._clamp
1550        if len(payload) > max_payload_len:
1551            payload = payload[len(payload)-max_payload_len:].lstrip('0')
1552            return _dec_from_triple(self._sign, payload, self._exp, True)
1553        return Decimal(self)
1554
1555    def _fix(self, context):
1556        """Round if it is necessary to keep self within prec precision.
1557
1558        Rounds and fixes the exponent.  Does not raise on a sNaN.
1559
1560        Arguments:
1561        self - Decimal instance
1562        context - context used.
1563        """
1564
1565        if self._is_special:
1566            if self._isnan():
1567                # decapitate payload if necessary
1568                return self._fix_nan(context)
1569            else:
1570                # self is +/-Infinity; return unaltered
1571                return Decimal(self)
1572
1573        # if self is zero then exponent should be between Etiny and
1574        # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1575        Etiny = context.Etiny()
1576        Etop = context.Etop()
1577        if not self:
1578            exp_max = [context.Emax, Etop][context._clamp]
1579            new_exp = min(max(self._exp, Etiny), exp_max)
1580            if new_exp != self._exp:
1581                context._raise_error(Clamped)
1582                return _dec_from_triple(self._sign, '0', new_exp)
1583            else:
1584                return Decimal(self)
1585
1586        # exp_min is the smallest allowable exponent of the result,
1587        # equal to max(self.adjusted()-context.prec+1, Etiny)
1588        exp_min = len(self._int) + self._exp - context.prec
1589        if exp_min > Etop:
1590            # overflow: exp_min > Etop iff self.adjusted() > Emax
1591            context._raise_error(Inexact)
1592            context._raise_error(Rounded)
1593            return context._raise_error(Overflow, 'above Emax', self._sign)
1594        self_is_subnormal = exp_min < Etiny
1595        if self_is_subnormal:
1596            context._raise_error(Subnormal)
1597            exp_min = Etiny
1598
1599        # round if self has too many digits
1600        if self._exp < exp_min:
1601            context._raise_error(Rounded)
1602            digits = len(self._int) + self._exp - exp_min
1603            if digits < 0:
1604                self = _dec_from_triple(self._sign, '1', exp_min-1)
1605                digits = 0
1606            this_function = getattr(self, self._pick_rounding_function[context.rounding])
1607            changed = this_function(digits)
1608            coeff = self._int[:digits] or '0'
1609            if changed == 1:
1610                coeff = str(int(coeff)+1)
1611            ans = _dec_from_triple(self._sign, coeff, exp_min)
1612
1613            if changed:
1614                context._raise_error(Inexact)
1615                if self_is_subnormal:
1616                    context._raise_error(Underflow)
1617                    if not ans:
1618                        # raise Clamped on underflow to 0
1619                        context._raise_error(Clamped)
1620                elif len(ans._int) == context.prec+1:
1621                    # we get here only if rescaling rounds the
1622                    # cofficient up to exactly 10**context.prec
1623                    if ans._exp < Etop:
1624                        ans = _dec_from_triple(ans._sign,
1625                                                   ans._int[:-1], ans._exp+1)
1626                    else:
1627                        # Inexact and Rounded have already been raised
1628                        ans = context._raise_error(Overflow, 'above Emax',
1629                                                   self._sign)
1630            return ans
1631
1632        # fold down if _clamp == 1 and self has too few digits
1633        if context._clamp == 1 and self._exp > Etop:
1634            context._raise_error(Clamped)
1635            self_padded = self._int + '0'*(self._exp - Etop)
1636            return _dec_from_triple(self._sign, self_padded, Etop)
1637
1638        # here self was representable to begin with; return unchanged
1639        return Decimal(self)
1640
1641    _pick_rounding_function = {}
1642
1643    # for each of the rounding functions below:
1644    #   self is a finite, nonzero Decimal
1645    #   prec is an integer satisfying 0 <= prec < len(self._int)
1646    #
1647    # each function returns either -1, 0, or 1, as follows:
1648    #   1 indicates that self should be rounded up (away from zero)
1649    #   0 indicates that self should be truncated, and that all the
1650    #     digits to be truncated are zeros (so the value is unchanged)
1651    #  -1 indicates that there are nonzero digits to be truncated
1652
1653    def _round_down(self, prec):
1654        """Also known as round-towards-0, truncate."""
1655        if _all_zeros(self._int, prec):
1656            return 0
1657        else:
1658            return -1
1659
1660    def _round_up(self, prec):
1661        """Rounds away from 0."""
1662        return -self._round_down(prec)
1663
1664    def _round_half_up(self, prec):
1665        """Rounds 5 up (away from 0)"""
1666        if self._int[prec] in '56789':
1667            return 1
1668        elif _all_zeros(self._int, prec):
1669            return 0
1670        else:
1671            return -1
1672
1673    def _round_half_down(self, prec):
1674        """Round 5 down"""
1675        if _exact_half(self._int, prec):
1676            return -1
1677        else:
1678            return self._round_half_up(prec)
1679
1680    def _round_half_even(self, prec):
1681        """Round 5 to even, rest to nearest."""
1682        if _exact_half(self._int, prec) and \
1683                (prec == 0 or self._int[prec-1] in '02468'):
1684            return -1
1685        else:
1686            return self._round_half_up(prec)
1687
1688    def _round_ceiling(self, prec):
1689        """Rounds up (not away from 0 if negative.)"""
1690        if self._sign:
1691            return self._round_down(prec)
1692        else:
1693            return -self._round_down(prec)
1694
1695    def _round_floor(self, prec):
1696        """Rounds down (not towards 0 if negative)"""
1697        if not self._sign:
1698            return self._round_down(prec)
1699        else:
1700            return -self._round_down(prec)
1701
1702    def _round_05up(self, prec):
1703        """Round down unless digit prec-1 is 0 or 5."""
1704        if prec and self._int[prec-1] not in '05':
1705            return self._round_down(prec)
1706        else:
1707            return -self._round_down(prec)
1708
1709    def fma(self, other, third, context=None):
1710        """Fused multiply-add.
1711
1712        Returns self*other+third with no rounding of the intermediate
1713        product self*other.
1714
1715        self and other are multiplied together, with no rounding of
1716        the result.  The third operand is then added to the result,
1717        and a single final rounding is performed.
1718        """
1719
1720        other = _convert_other(other, raiseit=True)
1721
1722        # compute product; raise InvalidOperation if either operand is
1723        # a signaling NaN or if the product is zero times infinity.
1724        if self._is_special or other._is_special:
1725            if context is None:
1726                context = getcontext()
1727            if self._exp == 'N':
1728                return context._raise_error(InvalidOperation, 'sNaN', self)
1729            if other._exp == 'N':
1730                return context._raise_error(InvalidOperation, 'sNaN', other)
1731            if self._exp == 'n':
1732                product = self
1733            elif other._exp == 'n':
1734                product = other
1735            elif self._exp == 'F':
1736                if not other:
1737                    return context._raise_error(InvalidOperation,
1738                                                'INF * 0 in fma')
1739                product = Infsign[self._sign ^ other._sign]
1740            elif other._exp == 'F':
1741                if not self:
1742                    return context._raise_error(InvalidOperation,
1743                                                '0 * INF in fma')
1744                product = Infsign[self._sign ^ other._sign]
1745        else:
1746            product = _dec_from_triple(self._sign ^ other._sign,
1747                                       str(int(self._int) * int(other._int)),
1748                                       self._exp + other._exp)
1749
1750        third = _convert_other(third, raiseit=True)
1751        return product.__add__(third, context)
1752
1753    def _power_modulo(self, other, modulo, context=None):
1754        """Three argument version of __pow__"""
1755
1756        # if can't convert other and modulo to Decimal, raise
1757        # TypeError; there's no point returning NotImplemented (no
1758        # equivalent of __rpow__ for three argument pow)
1759        other = _convert_other(other, raiseit=True)
1760        modulo = _convert_other(modulo, raiseit=True)
1761
1762        if context is None:
1763            context = getcontext()
1764
1765        # deal with NaNs: if there are any sNaNs then first one wins,
1766        # (i.e. behaviour for NaNs is identical to that of fma)
1767        self_is_nan = self._isnan()
1768        other_is_nan = other._isnan()
1769        modulo_is_nan = modulo._isnan()
1770        if self_is_nan or other_is_nan or modulo_is_nan:
1771            if self_is_nan == 2:
1772                return context._raise_error(InvalidOperation, 'sNaN',
1773                                        self)
1774            if other_is_nan == 2:
1775                return context._raise_error(InvalidOperation, 'sNaN',
1776                                        other)
1777            if modulo_is_nan == 2:
1778                return context._raise_error(InvalidOperation, 'sNaN',
1779                                        modulo)
1780            if self_is_nan:
1781                return self._fix_nan(context)
1782            if other_is_nan:
1783                return other._fix_nan(context)
1784            return modulo._fix_nan(context)
1785
1786        # check inputs: we apply same restrictions as Python's pow()
1787        if not (self._isinteger() and
1788                other._isinteger() and
1789                modulo._isinteger()):
1790            return context._raise_error(InvalidOperation,
1791                                        'pow() 3rd argument not allowed '
1792                                        'unless all arguments are integers')
1793        if other < 0:
1794            return context._raise_error(InvalidOperation,
1795                                        'pow() 2nd argument cannot be '
1796                                        'negative when 3rd argument specified')
1797        if not modulo:
1798            return context._raise_error(InvalidOperation,
1799                                        'pow() 3rd argument cannot be 0')
1800
1801        # additional restriction for decimal: the modulus must be less
1802        # than 10**prec in absolute value
1803        if modulo.adjusted() >= context.prec:
1804            return context._raise_error(InvalidOperation,
1805                                        'insufficient precision: pow() 3rd '
1806                                        'argument must not have more than '
1807                                        'precision digits')
1808
1809        # define 0**0 == NaN, for consistency with two-argument pow
1810        # (even though it hurts!)
1811        if not other and not self:
1812            return context._raise_error(InvalidOperation,
1813                                        'at least one of pow() 1st argument '
1814                                        'and 2nd argument must be nonzero ;'
1815                                        '0**0 is not defined')
1816
1817        # compute sign of result
1818        if other._iseven():
1819            sign = 0
1820        else:
1821            sign = self._sign
1822
1823        # convert modulo to a Python integer, and self and other to
1824        # Decimal integers (i.e. force their exponents to be >= 0)
1825        modulo = abs(int(modulo))
1826        base = _WorkRep(self.to_integral_value())
1827        exponent = _WorkRep(other.to_integral_value())
1828
1829        # compute result using integer pow()
1830        base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1831        for i in xrange(exponent.exp):
1832            base = pow(base, 10, modulo)
1833        base = pow(base, exponent.int, modulo)
1834
1835        return _dec_from_triple(sign, str(base), 0)
1836
1837    def _power_exact(self, other, p):
1838        """Attempt to compute self**other exactly.
1839
1840        Given Decimals self and other and an integer p, attempt to
1841        compute an exact result for the power self**other, with p
1842        digits of precision.  Return None if self**other is not
1843        exactly representable in p digits.
1844
1845        Assumes that elimination of special cases has already been
1846        performed: self and other must both be nonspecial; self must
1847        be positive and not numerically equal to 1; other must be
1848        nonzero.  For efficiency, other._exp should not be too large,
1849        so that 10**abs(other._exp) is a feasible calculation."""
1850
1851        # In the comments below, we write x for the value of self and
1852        # y for the value of other.  Write x = xc*10**xe and y =
1853        # yc*10**ye.
1854
1855        # The main purpose of this method is to identify the *failure*
1856        # of x**y to be exactly representable with as little effort as
1857        # possible.  So we look for cheap and easy tests that
1858        # eliminate the possibility of x**y being exact.  Only if all
1859        # these tests are passed do we go on to actually compute x**y.
1860
1861        # Here's the main idea.  First normalize both x and y.  We
1862        # express y as a rational m/n, with m and n relatively prime
1863        # and n>0.  Then for x**y to be exactly representable (at
1864        # *any* precision), xc must be the nth power of a positive
1865        # integer and xe must be divisible by n.  If m is negative
1866        # then additionally xc must be a power of either 2 or 5, hence
1867        # a power of 2**n or 5**n.
1868        #
1869        # There's a limit to how small |y| can be: if y=m/n as above
1870        # then:
1871        #
1872        #  (1) if xc != 1 then for the result to be representable we
1873        #      need xc**(1/n) >= 2, and hence also xc**|y| >= 2.  So
1874        #      if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1875        #      2**(1/|y|), hence xc**|y| < 2 and the result is not
1876        #      representable.
1877        #
1878        #  (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1.  Hence if
1879        #      |y| < 1/|xe| then the result is not representable.
1880        #
1881        # Note that since x is not equal to 1, at least one of (1) and
1882        # (2) must apply.  Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1883        # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1884        #
1885        # There's also a limit to how large y can be, at least if it's
1886        # positive: the normalized result will have coefficient xc**y,
1887        # so if it's representable then xc**y < 10**p, and y <
1888        # p/log10(xc).  Hence if y*log10(xc) >= p then the result is
1889        # not exactly representable.
1890
1891        # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1892        # so |y| < 1/xe and the result is not representable.
1893        # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1894        # < 1/nbits(xc).
1895
1896        x = _WorkRep(self)
1897        xc, xe = x.int, x.exp
1898        while xc % 10 == 0:
1899            xc //= 10
1900            xe += 1
1901
1902        y = _WorkRep(other)
1903        yc, ye = y.int, y.exp
1904        while yc % 10 == 0:
1905            yc //= 10
1906            ye += 1
1907
1908        # case where xc == 1: result is 10**(xe*y), with xe*y
1909        # required to be an integer
1910        if xc == 1:
1911            if ye >= 0:
1912                exponent = xe*yc*10**ye
1913            else:
1914                exponent, remainder = divmod(xe*yc, 10**-ye)
1915                if remainder:
1916                    return None
1917            if y.sign == 1:
1918                exponent = -exponent
1919            # if other is a nonnegative integer, use ideal exponent
1920            if other._isinteger() and other._sign == 0:
1921                ideal_exponent = self._exp*int(other)
1922                zeros = min(exponent-ideal_exponent, p-1)
1923            else:
1924                zeros = 0
1925            return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
1926
1927        # case where y is negative: xc must be either a power
1928        # of 2 or a power of 5.
1929        if y.sign == 1:
1930            last_digit = xc % 10
1931            if last_digit in (2,4,6,8):
1932                # quick test for power of 2
1933                if xc & -xc != xc:
1934                    return None
1935                # now xc is a power of 2; e is its exponent
1936                e = _nbits(xc)-1
1937                # find e*y and xe*y; both must be integers
1938                if ye >= 0:
1939                    y_as_int = yc*10**ye
1940                    e = e*y_as_int
1941                    xe = xe*y_as_int
1942                else:
1943                    ten_pow = 10**-ye
1944                    e, remainder = divmod(e*yc, ten_pow)
1945                    if remainder:
1946                        return None
1947                    xe, remainder = divmod(xe*yc, ten_pow)
1948                    if remainder:
1949                        return None
1950
1951                if e*65 >= p*93: # 93/65 > log(10)/log(5)
1952                    return None
1953                xc = 5**e
1954
1955            elif last_digit == 5:
1956                # e >= log_5(xc) if xc is a power of 5; we have
1957                # equality all the way up to xc=5**2658
1958                e = _nbits(xc)*28//65
1959                xc, remainder = divmod(5**e, xc)
1960                if remainder:
1961                    return None
1962                while xc % 5 == 0:
1963                    xc //= 5
1964                    e -= 1
1965                if ye >= 0:
1966                    y_as_integer = yc*10**ye
1967                    e = e*y_as_integer
1968                    xe = xe*y_as_integer
1969                else:
1970                    ten_pow = 10**-ye
1971                    e, remainder = divmod(e*yc, ten_pow)
1972                    if remainder:
1973                        return None
1974                    xe, remainder = divmod(xe*yc, ten_pow)
1975                    if remainder:
1976                        return None
1977                if e*3 >= p*10: # 10/3 > log(10)/log(2)
1978                    return None
1979                xc = 2**e
1980            else:
1981                return None
1982
1983            if xc >= 10**p:
1984                return None
1985            xe = -e-xe
1986            return _dec_from_triple(0, str(xc), xe)
1987
1988        # now y is positive; find m and n such that y = m/n
1989        if ye >= 0:
1990            m, n = yc*10**ye, 1
1991        else:
1992            if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1993                return None
1994            xc_bits = _nbits(xc)
1995            if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1996                return None
1997            m, n = yc, 10**(-ye)
1998            while m % 2 == n % 2 == 0:
1999                m //= 2
2000                n //= 2
2001            while m % 5 == n % 5 == 0:
2002                m //= 5
2003                n //= 5
2004
2005        # compute nth root of xc*10**xe
2006        if n > 1:
2007            # if 1 < xc < 2**n then xc isn't an nth power
2008            if xc != 1 and xc_bits <= n:
2009                return None
2010
2011            xe, rem = divmod(xe, n)
2012            if rem != 0:
2013                return None
2014
2015            # compute nth root of xc using Newton's method
2016            a = 1L << -(-_nbits(xc)//n) # initial estimate
2017            while True:
2018                q, r = divmod(xc, a**(n-1))
2019                if a <= q:
2020                    break
2021                else:
2022                    a = (a*(n-1) + q)//n
2023            if not (a == q and r == 0):
2024                return None
2025            xc = a
2026
2027        # now xc*10**xe is the nth root of the original xc*10**xe
2028        # compute mth power of xc*10**xe
2029
2030        # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2031        # 10**p and the result is not representable.
2032        if xc > 1 and m > p*100//_log10_lb(xc):
2033            return None
2034        xc = xc**m
2035        xe *= m
2036        if xc > 10**p:
2037            return None
2038
2039        # by this point the result *is* exactly representable
2040        # adjust the exponent to get as close as possible to the ideal
2041        # exponent, if necessary
2042        str_xc = str(xc)
2043        if other._isinteger() and other._sign == 0:
2044            ideal_exponent = self._exp*int(other)
2045            zeros = min(xe-ideal_exponent, p-len(str_xc))
2046        else:
2047            zeros = 0
2048        return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
2049
2050    def __pow__(self, other, modulo=None, context=None):
2051        """Return self ** other [ % modulo].
2052
2053        With two arguments, compute self**other.
2054
2055        With three arguments, compute (self**other) % modulo.  For the
2056        three argument form, the following restrictions on the
2057        arguments hold:
2058
2059         - all three arguments must be integral
2060         - other must be nonnegative
2061         - either self or other (or both) must be nonzero
2062         - modulo must be nonzero and must have at most p digits,
2063           where p is the context precision.
2064
2065        If any of these restrictions is violated the InvalidOperation
2066        flag is raised.
2067
2068        The result of pow(self, other, modulo) is identical to the
2069        result that would be obtained by computing (self**other) %
2070        modulo with unbounded precision, but is computed more
2071        efficiently.  It is always exact.
2072        """
2073
2074        if modulo is not None:
2075            return self._power_modulo(other, modulo, context)
2076
2077        other = _convert_other(other)
2078        if other is NotImplemented:
2079            return other
2080
2081        if context is None:
2082            context = getcontext()
2083
2084        # either argument is a NaN => result is NaN
2085        ans = self._check_nans(other, context)
2086        if ans:
2087            return ans
2088
2089        # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2090        if not other:
2091            if not self:
2092                return context._raise_error(InvalidOperation, '0 ** 0')
2093            else:
2094                return Dec_p1
2095
2096        # result has sign 1 iff self._sign is 1 and other is an odd integer
2097        result_sign = 0
2098        if self._sign == 1:
2099            if other._isinteger():
2100                if not other._iseven():
2101                    result_sign = 1
2102            else:
2103                # -ve**noninteger = NaN
2104                # (-0)**noninteger = 0**noninteger
2105                if self:
2106                    return context._raise_error(InvalidOperation,
2107                        'x ** y with x negative and y not an integer')
2108            # negate self, without doing any unwanted rounding
2109            self = self.copy_negate()
2110
2111        # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2112        if not self:
2113            if other._sign == 0:
2114                return _dec_from_triple(result_sign, '0', 0)
2115            else:
2116                return Infsign[result_sign]
2117
2118        # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
2119        if self._isinfinity():
2120            if other._sign == 0:
2121                return Infsign[result_sign]
2122            else:
2123                return _dec_from_triple(result_sign, '0', 0)
2124
2125        # 1**other = 1, but the choice of exponent and the flags
2126        # depend on the exponent of self, and on whether other is a
2127        # positive integer, a negative integer, or neither
2128        if self == Dec_p1:
2129            if other._isinteger():
2130                # exp = max(self._exp*max(int(other), 0),
2131                # 1-context.prec) but evaluating int(other) directly
2132                # is dangerous until we know other is small (other
2133                # could be 1e999999999)
2134                if other._sign == 1:
2135                    multiplier = 0
2136                elif other > context.prec:
2137                    multiplier = context.prec
2138                else:
2139                    multiplier = int(other)
2140
2141                exp = self._exp * multiplier
2142                if exp < 1-context.prec:
2143                    exp = 1-context.prec
2144                    context._raise_error(Rounded)
2145            else:
2146                context._raise_error(Inexact)
2147                context._raise_error(Rounded)
2148                exp = 1-context.prec
2149
2150            return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
2151
2152        # compute adjusted exponent of self
2153        self_adj = self.adjusted()
2154
2155        # self ** infinity is infinity if self > 1, 0 if self < 1
2156        # self ** -infinity is infinity if self < 1, 0 if self > 1
2157        if other._isinfinity():
2158            if (other._sign == 0) == (self_adj < 0):
2159                return _dec_from_triple(result_sign, '0', 0)
2160            else:
2161                return Infsign[result_sign]
2162
2163        # from here on, the result always goes through the call
2164        # to _fix at the end of this function.
2165        ans = None
2166
2167        # crude test to catch cases of extreme overflow/underflow.  If
2168        # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2169        # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2170        # self**other >= 10**(Emax+1), so overflow occurs.  The test
2171        # for underflow is similar.
2172        bound = self._log10_exp_bound() + other.adjusted()
2173        if (self_adj >= 0) == (other._sign == 0):
2174            # self > 1 and other +ve, or self < 1 and other -ve
2175            # possibility of overflow
2176            if bound >= len(str(context.Emax)):
2177                ans = _dec_from_triple(result_sign, '1', context.Emax+1)
2178        else:
2179            # self > 1 and other -ve, or self < 1 and other +ve
2180            # possibility of underflow to 0
2181            Etiny = context.Etiny()
2182            if bound >= len(str(-Etiny)):
2183                ans = _dec_from_triple(result_sign, '1', Etiny-1)
2184
2185        # try for an exact result with precision +1
2186        if ans is None:
2187            ans = self._power_exact(other, context.prec + 1)
2188            if ans is not None and result_sign == 1:
2189                ans = _dec_from_triple(1, ans._int, ans._exp)
2190
2191        # usual case: inexact result, x**y computed directly as exp(y*log(x))
2192        if ans is None:
2193            p = context.prec
2194            x = _WorkRep(self)
2195            xc, xe = x.int, x.exp
2196            y = _WorkRep(other)
2197            yc, ye = y.int, y.exp
2198            if y.sign == 1:
2199                yc = -yc
2200
2201            # compute correctly rounded result:  start with precision +3,
2202            # then increase precision until result is unambiguously roundable
2203            extra = 3
2204            while True:
2205                coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2206                if coeff % (5*10**(len(str(coeff))-p-1)):
2207                    break
2208                extra += 3
2209
2210            ans = _dec_from_triple(result_sign, str(coeff), exp)
2211
2212        # the specification says that for non-integer other we need to
2213        # raise Inexact, even when the result is actually exact.  In
2214        # the same way, we need to raise Underflow here if the result
2215        # is subnormal.  (The call to _fix will take care of raising
2216        # Rounded and Subnormal, as usual.)
2217        if not other._isinteger():
2218            context._raise_error(Inexact)
2219            # pad with zeros up to length context.prec+1 if necessary
2220            if len(ans._int) <= context.prec:
2221                expdiff = context.prec+1 - len(ans._int)
2222                ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2223                                       ans._exp-expdiff)
2224            if ans.adjusted() < context.Emin:
2225                context._raise_error(Underflow)
2226
2227        # unlike exp, ln and log10, the power function respects the
2228        # rounding mode; no need to use ROUND_HALF_EVEN here
2229        ans = ans._fix(context)
2230        return ans
2231
2232    def __rpow__(self, other, context=None):
2233        """Swaps self/other and returns __pow__."""
2234        other = _convert_other(other)
2235        if other is NotImplemented:
2236            return other
2237        return other.__pow__(self, context=context)
2238
2239    def normalize(self, context=None):
2240        """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
2241
2242        if context is None:
2243            context = getcontext()
2244
2245        if self._is_special:
2246            ans = self._check_nans(context=context)
2247            if ans:
2248                return ans
2249
2250        dup = self._fix(context)
2251        if dup._isinfinity():
2252            return dup
2253
2254        if not dup:
2255            return _dec_from_triple(dup._sign, '0', 0)
2256        exp_max = [context.Emax, context.Etop()][context._clamp]
2257        end = len(dup._int)
2258        exp = dup._exp
2259        while dup._int[end-1] == '0' and exp < exp_max:
2260            exp += 1
2261            end -= 1
2262        return _dec_from_triple(dup._sign, dup._int[:end], exp)
2263
2264    def quantize(self, exp, rounding=None, context=None, watchexp=True):
2265        """Quantize self so its exponent is the same as that of exp.
2266
2267        Similar to self._rescale(exp._exp) but with error checking.
2268        """
2269        exp = _convert_other(exp, raiseit=True)
2270
2271        if context is None:
2272            context = getcontext()
2273        if rounding is None:
2274            rounding = context.rounding
2275
2276        if self._is_special or exp._is_special:
2277            ans = self._check_nans(exp, context)
2278            if ans:
2279                return ans
2280
2281            if exp._isinfinity() or self._isinfinity():
2282                if exp._isinfinity() and self._isinfinity():
2283                    return Decimal(self)  # if both are inf, it is OK
2284                return context._raise_error(InvalidOperation,
2285                                        'quantize with one INF')
2286
2287        # if we're not watching exponents, do a simple rescale
2288        if not watchexp:
2289            ans = self._rescale(exp._exp, rounding)
2290            # raise Inexact and Rounded where appropriate
2291            if ans._exp > self._exp:
2292                context._raise_error(Rounded)
2293                if ans != self:
2294                    context._raise_error(Inexact)
2295            return ans
2296
2297        # exp._exp should be between Etiny and Emax
2298        if not (context.Etiny() <= exp._exp <= context.Emax):
2299            return context._raise_error(InvalidOperation,
2300                   'target exponent out of bounds in quantize')
2301
2302        if not self:
2303            ans = _dec_from_triple(self._sign, '0', exp._exp)
2304            return ans._fix(context)
2305
2306        self_adjusted = self.adjusted()
2307        if self_adjusted > context.Emax:
2308            return context._raise_error(InvalidOperation,
2309                                        'exponent of quantize result too large for current context')
2310        if self_adjusted - exp._exp + 1 > context.prec:
2311            return context._raise_error(InvalidOperation,
2312                                        'quantize result has too many digits for current context')
2313
2314        ans = self._rescale(exp._exp, rounding)
2315        if ans.adjusted() > context.Emax:
2316            return context._raise_error(InvalidOperation,
2317                                        'exponent of quantize result too large for current context')
2318        if len(ans._int) > context.prec:
2319            return context._raise_error(InvalidOperation,
2320                                        'quantize result has too many digits for current context')
2321
2322        # raise appropriate flags
2323        if ans._exp > self._exp:
2324            context._raise_error(Rounded)
2325            if ans != self:
2326                context._raise_error(Inexact)
2327        if ans and ans.adjusted() < context.Emin:
2328            context._raise_error(Subnormal)
2329
2330        # call to fix takes care of any necessary folddown
2331        ans = ans._fix(context)
2332        return ans
2333
2334    def same_quantum(self, other):
2335        """Return True if self and other have the same exponent; otherwise
2336        return False.
2337
2338        If either operand is a special value, the following rules are used:
2339           * return True if both operands are infinities
2340           * return True if both operands are NaNs
2341           * otherwise, return False.
2342        """
2343        other = _convert_other(other, raiseit=True)
2344        if self._is_special or other._is_special:
2345            return (self.is_nan() and other.is_nan() or
2346                    self.is_infinite() and other.is_infinite())
2347        return self._exp == other._exp
2348
2349    def _rescale(self, exp, rounding):
2350        """Rescale self so that the exponent is exp, either by padding with zeros
2351        or by truncating digits, using the given rounding mode.
2352
2353        Specials are returned without change.  This operation is
2354        quiet: it raises no flags, and uses no information from the
2355        context.
2356
2357        exp = exp to scale to (an integer)
2358        rounding = rounding mode
2359        """
2360        if self._is_special:
2361            return Decimal(self)
2362        if not self:
2363            return _dec_from_triple(self._sign, '0', exp)
2364
2365        if self._exp >= exp:
2366            # pad answer with zeros if necessary
2367            return _dec_from_triple(self._sign,
2368                                        self._int + '0'*(self._exp - exp), exp)
2369
2370        # too many digits; round and lose data.  If self.adjusted() <
2371        # exp-1, replace self by 10**(exp-1) before rounding
2372        digits = len(self._int) + self._exp - exp
2373        if digits < 0:
2374            self = _dec_from_triple(self._sign, '1', exp-1)
2375            digits = 0
2376        this_function = getattr(self, self._pick_rounding_function[rounding])
2377        changed = this_function(digits)
2378        coeff = self._int[:digits] or '0'
2379        if changed == 1:
2380            coeff = str(int(coeff)+1)
2381        return _dec_from_triple(self._sign, coeff, exp)
2382
2383    def _round(self, places, rounding):
2384        """Round a nonzero, nonspecial Decimal to a fixed number of
2385        significant figures, using the given rounding mode.
2386
2387        Infinities, NaNs and zeros are returned unaltered.
2388
2389        This operation is quiet: it raises no flags, and uses no
2390        information from the context.
2391
2392        """
2393        if places <= 0:
2394            raise ValueError("argument should be at least 1 in _round")
2395        if self._is_special or not self:
2396            return Decimal(self)
2397        ans = self._rescale(self.adjusted()+1-places, rounding)
2398        # it can happen that the rescale alters the adjusted exponent;
2399        # for example when rounding 99.97 to 3 significant figures.
2400        # When this happens we end up with an extra 0 at the end of
2401        # the number; a second rescale fixes this.
2402        if ans.adjusted() != self.adjusted():
2403            ans = ans._rescale(ans.adjusted()+1-places, rounding)
2404        return ans
2405
2406    def to_integral_exact(self, rounding=None, context=None):
2407        """Rounds to a nearby integer.
2408
2409        If no rounding mode is specified, take the rounding mode from
2410        the context.  This method raises the Rounded and Inexact flags
2411        when appropriate.
2412
2413        See also: to_integral_value, which does exactly the same as
2414        this method except that it doesn't raise Inexact or Rounded.
2415        """
2416        if self._is_special:
2417            ans = self._check_nans(context=context)
2418            if ans:
2419                return ans
2420            return Decimal(self)
2421        if self._exp >= 0:
2422            return Decimal(self)
2423        if not self:
2424            return _dec_from_triple(self._sign, '0', 0)
2425        if context is None:
2426            context = getcontext()
2427        if rounding is None:
2428            rounding = context.rounding
2429        context._raise_error(Rounded)
2430        ans = self._rescale(0, rounding)
2431        if ans != self:
2432            context._raise_error(Inexact)
2433        return ans
2434
2435    def to_integral_value(self, rounding=None, context=None):
2436        """Rounds to the nearest integer, without raising inexact, rounded."""
2437        if context is None:
2438            context = getcontext()
2439        if rounding is None:
2440            rounding = context.rounding
2441        if self._is_special:
2442            ans = self._check_nans(context=context)
2443            if ans:
2444                return ans
2445            return Decimal(self)
2446        if self._exp >= 0:
2447            return Decimal(self)
2448        else:
2449            return self._rescale(0, rounding)
2450
2451    # the method name changed, but we provide also the old one, for compatibility
2452    to_integral = to_integral_value
2453
2454    def sqrt(self, context=None):
2455        """Return the square root of self."""
2456        if self._is_special:
2457            ans = self._check_nans(context=context)
2458            if ans:
2459                return ans
2460
2461            if self._isinfinity() and self._sign == 0:
2462                return Decimal(self)
2463
2464        if not self:
2465            # exponent = self._exp // 2.  sqrt(-0) = -0
2466            ans = _dec_from_triple(self._sign, '0', self._exp // 2)
2467            return ans._fix(context)
2468
2469        if context is None:
2470            context = getcontext()
2471
2472        if self._sign == 1:
2473            return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2474
2475        # At this point self represents a positive number.  Let p be
2476        # the desired precision and express self in the form c*100**e
2477        # with c a positive real number and e an integer, c and e
2478        # being chosen so that 100**(p-1) <= c < 100**p.  Then the
2479        # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2480        # <= sqrt(c) < 10**p, so the closest representable Decimal at
2481        # precision p is n*10**e where n = round_half_even(sqrt(c)),
2482        # the closest integer to sqrt(c) with the even integer chosen
2483        # in the case of a tie.
2484        #
2485        # To ensure correct rounding in all cases, we use the
2486        # following trick: we compute the square root to an extra
2487        # place (precision p+1 instead of precision p), rounding down.
2488        # Then, if the result is inexact and its last digit is 0 or 5,
2489        # we increase the last digit to 1 or 6 respectively; if it's
2490        # exact we leave the last digit alone.  Now the final round to
2491        # p places (or fewer in the case of underflow) will round
2492        # correctly and raise the appropriate flags.
2493
2494        # use an extra digit of precision
2495        prec = context.prec+1
2496
2497        # write argument in the form c*100**e where e = self._exp//2
2498        # is the 'ideal' exponent, to be used if the square root is
2499        # exactly representable.  l is the number of 'digits' of c in
2500        # base 100, so that 100**(l-1) <= c < 100**l.
2501        op = _WorkRep(self)
2502        e = op.exp >> 1
2503        if op.exp & 1:
2504            c = op.int * 10
2505            l = (len(self._int) >> 1) + 1
2506        else:
2507            c = op.int
2508            l = len(self._int)+1 >> 1
2509
2510        # rescale so that c has exactly prec base 100 'digits'
2511        shift = prec-l
2512        if shift >= 0:
2513            c *= 100**shift
2514            exact = True
2515        else:
2516            c, remainder = divmod(c, 100**-shift)
2517            exact = not remainder
2518        e -= shift
2519
2520        # find n = floor(sqrt(c)) using Newton's method
2521        n = 10**prec
2522        while True:
2523            q = c//n
2524            if n <= q:
2525                break
2526            else:
2527                n = n + q >> 1
2528        exact = exact and n*n == c
2529
2530        if exact:
2531            # result is exact; rescale to use ideal exponent e
2532            if shift >= 0:
2533                # assert n % 10**shift == 0
2534                n //= 10**shift
2535            else:
2536                n *= 10**-shift
2537            e += shift
2538        else:
2539            # result is not exact; fix last digit as described above
2540            if n % 5 == 0:
2541                n += 1
2542
2543        ans = _dec_from_triple(0, str(n), e)
2544
2545        # round, and fit to current context
2546        context = context._shallow_copy()
2547        rounding = context._set_rounding(ROUND_HALF_EVEN)
2548        ans = ans._fix(context)
2549        context.rounding = rounding
2550
2551        return ans
2552
2553    def max(self, other, context=None):
2554        """Returns the larger value.
2555
2556        Like max(self, other) except if one is not a number, returns
2557        NaN (and signals if one is sNaN).  Also rounds.
2558        """
2559        other = _convert_other(other, raiseit=True)
2560
2561        if context is None:
2562            context = getcontext()
2563
2564        if self._is_special or other._is_special:
2565            # If one operand is a quiet NaN and the other is number, then the
2566            # number is always returned
2567            sn = self._isnan()
2568            on = other._isnan()
2569            if sn or on:
2570                if on == 1 and sn != 2:
2571                    return self._fix_nan(context)
2572                if sn == 1 and on != 2:
2573                    return other._fix_nan(context)
2574                return self._check_nans(other, context)
2575
2576        c = self._cmp(other)
2577        if c == 0:
2578            # If both operands are finite and equal in numerical value
2579            # then an ordering is applied:
2580            #
2581            # If the signs differ then max returns the operand with the
2582            # positive sign and min returns the operand with the negative sign
2583            #
2584            # If the signs are the same then the exponent is used to select
2585            # the result.  This is exactly the ordering used in compare_total.
2586            c = self.compare_total(other)
2587
2588        if c == -1:
2589            ans = other
2590        else:
2591            ans = self
2592
2593        return ans._fix(context)
2594
2595    def min(self, other, context=None):
2596        """Returns the smaller value.
2597
2598        Like min(self, other) except if one is not a number, returns
2599        NaN (and signals if one is sNaN).  Also rounds.
2600        """
2601        other = _convert_other(other, raiseit=True)
2602
2603        if context is None:
2604            context = getcontext()
2605
2606        if self._is_special or other._is_special:
2607            # If one operand is a quiet NaN and the other is number, then the
2608            # number is always returned
2609            sn = self._isnan()
2610            on = other._isnan()
2611            if sn or on:
2612                if on == 1 and sn != 2:
2613                    return self._fix_nan(context)
2614                if sn == 1 and on != 2:
2615                    return other._fix_nan(context)
2616                return self._check_nans(other, context)
2617
2618        c = self._cmp(other)
2619        if c == 0:
2620            c = self.compare_total(other)
2621
2622        if c == -1:
2623            ans = self
2624        else:
2625            ans = other
2626
2627        return ans._fix(context)
2628
2629    def _isinteger(self):
2630        """Returns whether self is an integer"""
2631        if self._is_special:
2632            return False
2633        if self._exp >= 0:
2634            return True
2635        rest = self._int[self._exp:]
2636        return rest == '0'*len(rest)
2637
2638    def _iseven(self):
2639        """Returns True if self is even.  Assumes self is an integer."""
2640        if not self or self._exp > 0:
2641            return True
2642        return self._int[-1+self._exp] in '02468'
2643
2644    def adjusted(self):
2645        """Return the adjusted exponent of self"""
2646        try:
2647            return self._exp + len(self._int) - 1
2648        # If NaN or Infinity, self._exp is string
2649        except TypeError:
2650            return 0
2651
2652    def canonical(self, context=None):
2653        """Returns the same Decimal object.
2654
2655        As we do not have different encodings for the same number, the
2656        received object already is in its canonical form.
2657        """
2658        return self
2659
2660    def compare_signal(self, other, context=None):
2661        """Compares self to the other operand numerically.
2662
2663        It's pretty much like compare(), but all NaNs signal, with signaling
2664        NaNs taking precedence over quiet NaNs.
2665        """
2666        other = _convert_other(other, raiseit = True)
2667        ans = self._compare_check_nans(other, context)
2668        if ans:
2669            return ans
2670        return self.compare(other, context=context)
2671
2672    def compare_total(self, other):
2673        """Compares self to other using the abstract representations.
2674
2675        This is not like the standard compare, which use their numerical
2676        value. Note that a total ordering is defined for all possible abstract
2677        representations.
2678        """
2679        # if one is negative and the other is positive, it's easy
2680        if self._sign and not other._sign:
2681            return Dec_n1
2682        if not self._sign and other._sign:
2683            return Dec_p1
2684        sign = self._sign
2685
2686        # let's handle both NaN types
2687        self_nan = self._isnan()
2688        other_nan = other._isnan()
2689        if self_nan or other_nan:
2690            if self_nan == other_nan:
2691                if self._int < other._int:
2692                    if sign:
2693                        return Dec_p1
2694                    else:
2695                        return Dec_n1
2696                if self._int > other._int:
2697                    if sign:
2698                        return Dec_n1
2699                    else:
2700                        return Dec_p1
2701                return Dec_0
2702
2703            if sign:
2704                if self_nan == 1:
2705                    return Dec_n1
2706                if other_nan == 1:
2707                    return Dec_p1
2708                if self_nan == 2:
2709                    return Dec_n1
2710                if other_nan == 2:
2711                    return Dec_p1
2712            else:
2713                if self_nan == 1:
2714                    return Dec_p1
2715                if other_nan == 1:
2716                    return Dec_n1
2717                if self_nan == 2:
2718                    return Dec_p1
2719                if other_nan == 2:
2720                    return Dec_n1
2721
2722        if self < other:
2723            return Dec_n1
2724        if self > other:
2725            return Dec_p1
2726
2727        if self._exp < other._exp:
2728            if sign:
2729                return Dec_p1
2730            else:
2731                return Dec_n1
2732        if self._exp > other._exp:
2733            if sign:
2734                return Dec_n1
2735            else:
2736                return Dec_p1
2737        return Dec_0
2738
2739
2740    def compare_total_mag(self, other):
2741        """Compares self to other using abstract repr., ignoring sign.
2742
2743        Like compare_total, but with operand's sign ignored and assumed to be 0.
2744        """
2745        s = self.copy_abs()
2746        o = other.copy_abs()
2747        return s.compare_total(o)
2748
2749    def copy_abs(self):
2750        """Returns a copy with the sign set to 0. """
2751        return _dec_from_triple(0, self._int, self._exp, self._is_special)
2752
2753    def copy_negate(self):
2754        """Returns a copy with the sign inverted."""
2755        if self._sign:
2756            return _dec_from_triple(0, self._int, self._exp, self._is_special)
2757        else:
2758            return _dec_from_triple(1, self._int, self._exp, self._is_special)
2759
2760    def copy_sign(self, other):
2761        """Returns self with the sign of other."""
2762        return _dec_from_triple(other._sign, self._int,
2763                                self._exp, self._is_special)
2764
2765    def exp(self, context=None):
2766        """Returns e ** self."""
2767
2768        if context is None:
2769            context = getcontext()
2770
2771        # exp(NaN) = NaN
2772        ans = self._check_nans(context=context)
2773        if ans:
2774            return ans
2775
2776        # exp(-Infinity) = 0
2777        if self._isinfinity() == -1:
2778            return Dec_0
2779
2780        # exp(0) = 1
2781        if not self:
2782            return Dec_p1
2783
2784        # exp(Infinity) = Infinity
2785        if self._isinfinity() == 1:
2786            return Decimal(self)
2787
2788        # the result is now guaranteed to be inexact (the true
2789        # mathematical result is transcendental). There's no need to
2790        # raise Rounded and Inexact here---they'll always be raised as
2791        # a result of the call to _fix.
2792        p = context.prec
2793        adj = self.adjusted()
2794
2795        # we only need to do any computation for quite a small range
2796        # of adjusted exponents---for example, -29 <= adj <= 10 for
2797        # the default context.  For smaller exponent the result is
2798        # indistinguishable from 1 at the given precision, while for
2799        # larger exponent the result either overflows or underflows.
2800        if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2801            # overflow
2802            ans = _dec_from_triple(0, '1', context.Emax+1)
2803        elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2804            # underflow to 0
2805            ans = _dec_from_triple(0, '1', context.Etiny()-1)
2806        elif self._sign == 0 and adj < -p:
2807            # p+1 digits; final round will raise correct flags
2808            ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
2809        elif self._sign == 1 and adj < -p-1:
2810            # p+1 digits; final round will raise correct flags
2811            ans = _dec_from_triple(0, '9'*(p+1), -p-1)
2812        # general case
2813        else:
2814            op = _WorkRep(self)
2815            c, e = op.int, op.exp
2816            if op.sign == 1:
2817                c = -c
2818
2819            # compute correctly rounded result: increase precision by
2820            # 3 digits at a time until we get an unambiguously
2821            # roundable result
2822            extra = 3
2823            while True:
2824                coeff, exp = _dexp(c, e, p+extra)
2825                if coeff % (5*10**(len(str(coeff))-p-1)):
2826                    break
2827                extra += 3
2828
2829            ans = _dec_from_triple(0, str(coeff), exp)
2830
2831        # at this stage, ans should round correctly with *any*
2832        # rounding mode, not just with ROUND_HALF_EVEN
2833        context = context._shallow_copy()
2834        rounding = context._set_rounding(ROUND_HALF_EVEN)
2835        ans = ans._fix(context)
2836        context.rounding = rounding
2837
2838        return ans
2839
2840    def is_canonical(self):
2841        """Return True if self is canonical; otherwise return False.
2842
2843        Currently, the encoding of a Decimal instance is always
2844        canonical, so this method returns True for any Decimal.
2845        """
2846        return True
2847
2848    def is_finite(self):
2849        """Return True if self is finite; otherwise return False.
2850
2851        A Decimal instance is considered finite if it is neither
2852        infinite nor a NaN.
2853        """
2854        return not self._is_special
2855
2856    def is_infinite(self):
2857        """Return True if self is infinite; otherwise return False."""
2858        return self._exp == 'F'
2859
2860    def is_nan(self):
2861        """Return True if self is a qNaN or sNaN; otherwise return False."""
2862        return self._exp in ('n', 'N')
2863
2864    def is_normal(self, context=None):
2865        """Return True if self is a normal number; otherwise return False."""
2866        if self._is_special or not self:
2867            return False
2868        if context is None:
2869            context = getcontext()
2870        return context.Emin <= self.adjusted() <= context.Emax
2871
2872    def is_qnan(self):
2873        """Return True if self is a quiet NaN; otherwise return False."""
2874        return self._exp == 'n'
2875
2876    def is_signed(self):
2877        """Return True if self is negative; otherwise return False."""
2878        return self._sign == 1
2879
2880    def is_snan(self):
2881        """Return True if self is a signaling NaN; otherwise return False."""
2882        return self._exp == 'N'
2883
2884    def is_subnormal(self, context=None):
2885        """Return True if self is subnormal; otherwise return False."""
2886        if self._is_special or not self:
2887            return False
2888        if context is None:
2889            context = getcontext()
2890        return self.adjusted() < context.Emin
2891
2892    def is_zero(self):
2893        """Return True if self is a zero; otherwise return False."""
2894        return not self._is_special and self._int == '0'
2895
2896    def _ln_exp_bound(self):
2897        """Compute a lower bound for the adjusted exponent of self.ln().
2898        In other words, compute r such that self.ln() >= 10**r.  Assumes
2899        that self is finite and positive and that self != 1.
2900        """
2901
2902        # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2903        adj = self._exp + len(self._int) - 1
2904        if adj >= 1:
2905            # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2906            return len(str(adj*23//10)) - 1
2907        if adj <= -2:
2908            # argument <= 0.1
2909            return len(str((-1-adj)*23//10)) - 1
2910        op = _WorkRep(self)
2911        c, e = op.int, op.exp
2912        if adj == 0:
2913            # 1 < self < 10
2914            num = str(c-10**-e)
2915            den = str(c)
2916            return len(num) - len(den) - (num < den)
2917        # adj == -1, 0.1 <= self < 1
2918        return e + len(str(10**-e - c)) - 1
2919
2920
2921    def ln(self, context=None):
2922        """Returns the natural (base e) logarithm of self."""
2923
2924        if context is None:
2925            context = getcontext()
2926
2927        # ln(NaN) = NaN
2928        ans = self._check_nans(context=context)
2929        if ans:
2930            return ans
2931
2932        # ln(0.0) == -Infinity
2933        if not self:
2934            return negInf
2935
2936        # ln(Infinity) = Infinity
2937        if self._isinfinity() == 1:
2938            return Inf
2939
2940        # ln(1.0) == 0.0
2941        if self == Dec_p1:
2942            return Dec_0
2943
2944        # ln(negative) raises InvalidOperation
2945        if self._sign == 1:
2946            return context._raise_error(InvalidOperation,
2947                                        'ln of a negative value')
2948
2949        # result is irrational, so necessarily inexact
2950        op = _WorkRep(self)
2951        c, e = op.int, op.exp
2952        p = context.prec
2953
2954        # correctly rounded result: repeatedly increase precision by 3
2955        # until we get an unambiguously roundable result
2956        places = p - self._ln_exp_bound() + 2 # at least p+3 places
2957        while True:
2958            coeff = _dlog(c, e, places)
2959            # assert len(str(abs(coeff)))-p >= 1
2960            if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2961                break
2962            places += 3
2963        ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
2964
2965        context = context._shallow_copy()
2966        rounding = context._set_rounding(ROUND_HALF_EVEN)
2967        ans = ans._fix(context)
2968        context.rounding = rounding
2969        return ans
2970
2971    def _log10_exp_bound(self):
2972        """Compute a lower bound for the adjusted exponent of self.log10().
2973        In other words, find r such that self.log10() >= 10**r.
2974        Assumes that self is finite and positive and that self != 1.
2975        """
2976
2977        # For x >= 10 or x < 0.1 we only need a bound on the integer
2978        # part of log10(self), and this comes directly from the
2979        # exponent of x.  For 0.1 <= x <= 10 we use the inequalities
2980        # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2981        # (1-1/x)/2.31 > 0.  If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2982
2983        adj = self._exp + len(self._int) - 1
2984        if adj >= 1:
2985            # self >= 10
2986            return len(str(adj))-1
2987        if adj <= -2:
2988            # self < 0.1
2989            return len(str(-1-adj))-1
2990        op = _WorkRep(self)
2991        c, e = op.int, op.exp
2992        if adj == 0:
2993            # 1 < self < 10
2994            num = str(c-10**-e)
2995            den = str(231*c)
2996            return len(num) - len(den) - (num < den) + 2
2997        # adj == -1, 0.1 <= self < 1
2998        num = str(10**-e-c)
2999        return len(num) + e - (num < "231") - 1
3000
3001    def log10(self, context=None):
3002        """Returns the base 10 logarithm of self."""
3003
3004        if context is None:
3005            context = getcontext()
3006
3007        # log10(NaN) = NaN
3008        ans = self._check_nans(context=context)
3009        if ans:
3010            return ans
3011
3012        # log10(0.0) == -Infinity
3013        if not self:
3014            return negInf
3015
3016        # log10(Infinity) = Infinity
3017        if self._isinfinity() == 1:
3018            return Inf
3019
3020        # log10(negative or -Infinity) raises InvalidOperation
3021        if self._sign == 1:
3022            return context._raise_error(InvalidOperation,
3023                                        'log10 of a negative value')
3024
3025        # log10(10**n) = n
3026        if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
3027            # answer may need rounding
3028            ans = Decimal(self._exp + len(self._int) - 1)
3029        else:
3030            # result is irrational, so necessarily inexact
3031            op = _WorkRep(self)
3032            c, e = op.int, op.exp
3033            p = context.prec
3034
3035            # correctly rounded result: repeatedly increase precision
3036            # until result is unambiguously roundable
3037            places = p-self._log10_exp_bound()+2
3038            while True:
3039                coeff = _dlog10(c, e, places)
3040                # assert len(str(abs(coeff)))-p >= 1
3041                if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3042                    break
3043                places += 3
3044            ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
3045
3046        context = context._shallow_copy()
3047        rounding = context._set_rounding(ROUND_HALF_EVEN)
3048        ans = ans._fix(context)
3049        context.rounding = rounding
3050        return ans
3051
3052    def logb(self, context=None):
3053        """ Returns the exponent of the magnitude of self's MSD.
3054
3055        The result is the integer which is the exponent of the magnitude
3056        of the most significant digit of self (as though it were truncated
3057        to a single digit while maintaining the value of that digit and
3058        without limiting the resulting exponent).
3059        """
3060        # logb(NaN) = NaN
3061        ans = self._check_nans(context=context)
3062        if ans:
3063            return ans
3064
3065        if context is None:
3066            context = getcontext()
3067
3068        # logb(+/-Inf) = +Inf
3069        if self._isinfinity():
3070            return Inf
3071
3072        # logb(0) = -Inf, DivisionByZero
3073        if not self:
3074            return context._raise_error(DivisionByZero, 'logb(0)', 1)
3075
3076        # otherwise, simply return the adjusted exponent of self, as a
3077        # Decimal.  Note that no attempt is made to fit the result
3078        # into the current context.
3079        return Decimal(self.adjusted())
3080
3081    def _islogical(self):
3082        """Return True if self is a logical operand.
3083
3084        For being logical, it must be a finite number with a sign of 0,
3085        an exponent of 0, and a coefficient whose digits must all be
3086        either 0 or 1.
3087        """
3088        if self._sign != 0 or self._exp != 0:
3089            return False
3090        for dig in self._int:
3091            if dig not in '01':
3092                return False
3093        return True
3094
3095    def _fill_logical(self, context, opa, opb):
3096        dif = context.prec - len(opa)
3097        if dif > 0:
3098            opa = '0'*dif + opa
3099        elif dif < 0:
3100            opa = opa[-context.prec:]
3101        dif = context.prec - len(opb)
3102        if dif > 0:
3103            opb = '0'*dif + opb
3104        elif dif < 0:
3105            opb = opb[-context.prec:]
3106        return opa, opb
3107
3108    def logical_and(self, other, context=None):
3109        """Applies an 'and' operation between self and other's digits."""
3110        if context is None:
3111            context = getcontext()
3112        if not self._islogical() or not other._islogical():
3113            return context._raise_error(InvalidOperation)
3114
3115        # fill to context.prec
3116        (opa, opb) = self._fill_logical(context, self._int, other._int)
3117
3118        # make the operation, and clean starting zeroes
3119        result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3120        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3121
3122    def logical_invert(self, context=None):
3123        """Invert all its digits."""
3124        if context is None:
3125            context = getcontext()
3126        return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3127                                context)
3128
3129    def logical_or(self, other, context=None):
3130        """Applies an 'or' operation between self and other's digits."""
3131        if context is None:
3132            context = getcontext()
3133        if not self._islogical() or not other._islogical():
3134            return context._raise_error(InvalidOperation)
3135
3136        # fill to context.prec
3137        (opa, opb) = self._fill_logical(context, self._int, other._int)
3138
3139        # make the operation, and clean starting zeroes
3140        result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3141        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3142
3143    def logical_xor(self, other, context=None):
3144        """Applies an 'xor' operation between self and other's digits."""
3145        if context is None:
3146            context = getcontext()
3147        if not self._islogical() or not other._islogical():
3148            return context._raise_error(InvalidOperation)
3149
3150        # fill to context.prec
3151        (opa, opb) = self._fill_logical(context, self._int, other._int)
3152
3153        # make the operation, and clean starting zeroes
3154        result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3155        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3156
3157    def max_mag(self, other, context=None):
3158        """Compares the values numerically with their sign ignored."""
3159        other = _convert_other(other, raiseit=True)
3160
3161        if context is None:
3162            context = getcontext()
3163
3164        if self._is_special or other._is_special:
3165            # If one operand is a quiet NaN and the other is number, then the
3166            # number is always returned
3167            sn = self._isnan()
3168            on = other._isnan()
3169            if sn or on:
3170                if on == 1 and sn != 2:
3171                    return self._fix_nan(context)
3172                if sn == 1 and on != 2:
3173                    return other._fix_nan(context)
3174                return self._check_nans(other, context)
3175
3176        c = self.copy_abs()._cmp(other.copy_abs())
3177        if c == 0:
3178            c = self.compare_total(other)
3179
3180        if c == -1:
3181            ans = other
3182        else:
3183            ans = self
3184
3185        return ans._fix(context)
3186
3187    def min_mag(self, other, context=None):
3188        """Compares the values numerically with their sign ignored."""
3189        other = _convert_other(other, raiseit=True)
3190
3191        if context is None:
3192            context = getcontext()
3193
3194        if self._is_special or other._is_special:
3195            # If one operand is a quiet NaN and the other is number, then the
3196            # number is always returned
3197            sn = self._isnan()
3198            on = other._isnan()
3199            if sn or on:
3200                if on == 1 and sn != 2:
3201                    return self._fix_nan(context)
3202                if sn == 1 and on != 2:
3203                    return other._fix_nan(context)
3204                return self._check_nans(other, context)
3205
3206        c = self.copy_abs()._cmp(other.copy_abs())
3207        if c == 0:
3208            c = self.compare_total(other)
3209
3210        if c == -1:
3211            ans = self
3212        else:
3213            ans = other
3214
3215        return ans._fix(context)
3216
3217    def next_minus(self, context=None):
3218        """Returns the largest representable number smaller than itself."""
3219        if context is None:
3220            context = getcontext()
3221
3222        ans = self._check_nans(context=context)
3223        if ans:
3224            return ans
3225
3226        if self._isinfinity() == -1:
3227            return negInf
3228        if self._isinfinity() == 1:
3229            return _dec_from_triple(0, '9'*context.prec, context.Etop())
3230
3231        context = context.copy()
3232        context._set_rounding(ROUND_FLOOR)
3233        context._ignore_all_flags()
3234        new_self = self._fix(context)
3235        if new_self != self:
3236            return new_self
3237        return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3238                            context)
3239
3240    def next_plus(self, context=None):
3241        """Returns the smallest representable number larger than itself."""
3242        if context is None:
3243            context = getcontext()
3244
3245        ans = self._check_nans(context=context)
3246        if ans:
3247            return ans
3248
3249        if self._isinfinity() == 1:
3250            return Inf
3251        if self._isinfinity() == -1:
3252            return _dec_from_triple(1, '9'*context.prec, context.Etop())
3253
3254        context = context.copy()
3255        context._set_rounding(ROUND_CEILING)
3256        context._ignore_all_flags()
3257        new_self = self._fix(context)
3258        if new_self != self:
3259            return new_self
3260        return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3261                            context)
3262
3263    def next_toward(self, other, context=None):
3264        """Returns the number closest to self, in the direction towards other.
3265
3266        The result is the closest representable number to self
3267        (excluding self) that is in the direction towards other,
3268        unless both have the same value.  If the two operands are
3269        numerically equal, then the result is a copy of self with the
3270        sign set to be the same as the sign of other.
3271        """
3272        other = _convert_other(other, raiseit=True)
3273
3274        if context is None:
3275            context = getcontext()
3276
3277        ans = self._check_nans(other, context)
3278        if ans:
3279            return ans
3280
3281        comparison = self._cmp(other)
3282        if comparison == 0:
3283            return self.copy_sign(other)
3284
3285        if comparison == -1:
3286            ans = self.next_plus(context)
3287        else: # comparison == 1
3288            ans = self.next_minus(context)
3289
3290        # decide which flags to raise using value of ans
3291        if ans._isinfinity():
3292            context._raise_error(Overflow,
3293                                 'Infinite result from next_toward',
3294                                 ans._sign)
3295            context._raise_error(Rounded)
3296            context._raise_error(Inexact)
3297        elif ans.adjusted() < context.Emin:
3298            context._raise_error(Underflow)
3299            context._raise_error(Subnormal)
3300            context._raise_error(Rounded)
3301            context._raise_error(Inexact)
3302            # if precision == 1 then we don't raise Clamped for a
3303            # result 0E-Etiny.
3304            if not ans:
3305                context._raise_error(Clamped)
3306
3307        return ans
3308
3309    def number_class(self, context=None):
3310        """Returns an indication of the class of self.
3311
3312        The class is one of the following strings:
3313          sNaN
3314          NaN
3315          -Infinity
3316          -Normal
3317          -Subnormal
3318          -Zero
3319          +Zero
3320          +Subnormal
3321          +Normal
3322          +Infinity
3323        """
3324        if self.is_snan():
3325            return "sNaN"
3326        if self.is_qnan():
3327            return "NaN"
3328        inf = self._isinfinity()
3329        if inf == 1:
3330            return "+Infinity"
3331        if inf == -1:
3332            return "-Infinity"
3333        if self.is_zero():
3334            if self._sign:
3335                return "-Zero"
3336            else:
3337                return "+Zero"
3338        if context is None:
3339            context = getcontext()
3340        if self.is_subnormal(context=context):
3341            if self._sign:
3342                return "-Subnormal"
3343            else:
3344                return "+Subnormal"
3345        # just a normal, regular, boring number, :)
3346        if self._sign:
3347            return "-Normal"
3348        else:
3349            return "+Normal"
3350
3351    def radix(self):
3352        """Just returns 10, as this is Decimal, :)"""
3353        return Decimal(10)
3354
3355    def rotate(self, other, context=None):
3356        """Returns a rotated copy of self, value-of-other times."""
3357        if context is None:
3358            context = getcontext()
3359
3360        ans = self._check_nans(other, context)
3361        if ans:
3362            return ans
3363
3364        if other._exp != 0:
3365            return context._raise_error(InvalidOperation)
3366        if not (-context.prec <= int(other) <= context.prec):
3367            return context._raise_error(InvalidOperation)
3368
3369        if self._isinfinity():
3370            return Decimal(self)
3371
3372        # get values, pad if necessary
3373        torot = int(other)
3374        rotdig = self._int
3375        topad = context.prec - len(rotdig)
3376        if topad:
3377            rotdig = '0'*topad + rotdig
3378
3379        # let's rotate!
3380        rotated = rotdig[torot:] + rotdig[:torot]
3381        return _dec_from_triple(self._sign,
3382                                rotated.lstrip('0') or '0', self._exp)
3383
3384    def scaleb (self, other, context=None):
3385        """Returns self operand after adding the second value to its exp."""
3386        if context is None:
3387            context = getcontext()
3388
3389        ans = self._check_nans(other, context)
3390        if ans:
3391            return ans
3392
3393        if other._exp != 0:
3394            return context._raise_error(InvalidOperation)
3395        liminf = -2 * (context.Emax + context.prec)
3396        limsup =  2 * (context.Emax + context.prec)
3397        if not (liminf <= int(other) <= limsup):
3398            return context._raise_error(InvalidOperation)
3399
3400        if self._isinfinity():
3401            return Decimal(self)
3402
3403        d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
3404        d = d._fix(context)
3405        return d
3406
3407    def shift(self, other, context=None):
3408        """Returns a shifted copy of self, value-of-other times."""
3409        if context is None:
3410            context = getcontext()
3411
3412        ans = self._check_nans(other, context)
3413        if ans:
3414            return ans
3415
3416        if other._exp != 0:
3417            return context._raise_error(InvalidOperation)
3418        if not (-context.prec <= int(other) <= context.prec):
3419            return context._raise_error(InvalidOperation)
3420
3421        if self._isinfinity():
3422            return Decimal(self)
3423
3424        # get values, pad if necessary
3425        torot = int(other)
3426        if not torot:
3427            return Decimal(self)
3428        rotdig = self._int
3429        topad = context.prec - len(rotdig)
3430        if topad:
3431            rotdig = '0'*topad + rotdig
3432
3433        # let's shift!
3434        if torot < 0:
3435            rotated = rotdig[:torot]
3436        else:
3437            rotated = rotdig + '0'*torot
3438            rotated = rotated[-context.prec:]
3439
3440        return _dec_from_triple(self._sign,
3441                                    rotated.lstrip('0') or '0', self._exp)
3442
3443    # Support for pickling, copy, and deepcopy
3444    def __reduce__(self):
3445        return (self.__class__, (str(self),))
3446
3447    def __copy__(self):
3448        if type(self) == Decimal:
3449            return self     # I'm immutable; therefore I am my own clone
3450        return self.__class__(str(self))
3451
3452    def __deepcopy__(self, memo):
3453        if type(self) == Decimal:
3454            return self     # My components are also immutable
3455        return self.__class__(str(self))
3456
3457    # PEP 3101 support.  See also _parse_format_specifier and _format_align
3458    def __format__(self, specifier, context=None):
3459        """Format a Decimal instance according to the given specifier.
3460
3461        The specifier should be a standard format specifier, with the
3462        form described in PEP 3101.  Formatting types 'e', 'E', 'f',
3463        'F', 'g', 'G', and '%' are supported.  If the formatting type
3464        is omitted it defaults to 'g' or 'G', depending on the value
3465        of context.capitals.
3466
3467        At this time the 'n' format specifier type (which is supposed
3468        to use the current locale) is not supported.
3469        """
3470
3471        # Note: PEP 3101 says that if the type is not present then
3472        # there should be at least one digit after the decimal point.
3473        # We take the liberty of ignoring this requirement for
3474        # Decimal---it's presumably there to make sure that
3475        # format(float, '') behaves similarly to str(float).
3476        if context is None:
3477            context = getcontext()
3478
3479        spec = _parse_format_specifier(specifier)
3480
3481        # special values don't care about the type or precision...
3482        if self._is_special:
3483            return _format_align(str(self), spec)
3484
3485        # a type of None defaults to 'g' or 'G', depending on context
3486        # if type is '%', adjust exponent of self accordingly
3487        if spec['type'] is None:
3488            spec['type'] = ['g', 'G'][context.capitals]
3489        elif spec['type'] == '%':
3490            self = _dec_from_triple(self._sign, self._int, self._exp+2)
3491
3492        # round if necessary, taking rounding mode from the context
3493        rounding = context.rounding
3494        precision = spec['precision']
3495        if precision is not None:
3496            if spec['type'] in 'eE':
3497                self = self._round(precision+1, rounding)
3498            elif spec['type'] in 'gG':
3499                if len(self._int) > precision:
3500                    self = self._round(precision, rounding)
3501            elif spec['type'] in 'fF%':
3502                self = self._rescale(-precision, rounding)
3503        # special case: zeros with a positive exponent can't be
3504        # represented in fixed point; rescale them to 0e0.
3505        elif not self and self._exp > 0 and spec['type'] in 'fF%':
3506            self = self._rescale(0, rounding)
3507
3508        # figure out placement of the decimal point
3509        leftdigits = self._exp + len(self._int)
3510        if spec['type'] in 'fF%':
3511            dotplace = leftdigits
3512        elif spec['type'] in 'eE':
3513            if not self and precision is not None:
3514                dotplace = 1 - precision
3515            else:
3516                dotplace = 1
3517        elif spec['type'] in 'gG':
3518            if self._exp <= 0 and leftdigits > -6:
3519                dotplace = leftdigits
3520            else:
3521                dotplace = 1
3522
3523        # figure out main part of numeric string...
3524        if dotplace <= 0:
3525            num = '0.' + '0'*(-dotplace) + self._int
3526        elif dotplace >= len(self._int):
3527            # make sure we're not padding a '0' with extra zeros on the right
3528            assert dotplace==len(self._int) or self._int != '0'
3529            num = self._int + '0'*(dotplace-len(self._int))
3530        else:
3531            num = self._int[:dotplace] + '.' + self._int[dotplace:]
3532
3533        # ...then the trailing exponent, or trailing '%'
3534        if leftdigits != dotplace or spec['type'] in 'eE':
3535            echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
3536            num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
3537        elif spec['type'] == '%':
3538            num = num + '%'
3539
3540        # add sign
3541        if self._sign == 1:
3542            num = '-' + num
3543        return _format_align(num, spec)
3544
3545
3546def _dec_from_triple(sign, coefficient, exponent, special=False):
3547    """Create a decimal instance directly, without any validation,
3548    normalization (e.g. removal of leading zeros) or argument
3549    conversion.
3550
3551    This function is for *internal use only*.
3552    """
3553
3554    self = object.__new__(Decimal)
3555    self._sign = sign
3556    self._int = coefficient
3557    self._exp = exponent
3558    self._is_special = special
3559
3560    return self
3561
3562##### Context class #######################################################
3563
3564
3565# get rounding method function:
3566rounding_functions = [name for name in Decimal.__dict__.keys()
3567                                    if name.startswith('_round_')]
3568for name in rounding_functions:
3569    # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
3570    globalname = name[1:].upper()
3571    val = globals()[globalname]
3572    Decimal._pick_rounding_function[val] = name
3573
3574del name, val, globalname, rounding_functions
3575
3576class _ContextManager(object):
3577    """Context manager class to support localcontext().
3578
3579      Sets a copy of the supplied context in __enter__() and restores
3580      the previous decimal context in __exit__()
3581    """
3582    def __init__(self, new_context):
3583        self.new_context = new_context.copy()
3584    def __enter__(self):
3585        self.saved_context = getcontext()
3586        setcontext(self.new_context)
3587        return self.new_context
3588    def __exit__(self, t, v, tb):
3589        setcontext(self.saved_context)
3590
3591class Context(object):
3592    """Contains the context for a Decimal instance.
3593
3594    Contains:
3595    prec - precision (for use in rounding, division, square roots..)
3596    rounding - rounding type (how you round)
3597    traps - If traps[exception] = 1, then the exception is
3598                    raised when it is caused.  Otherwise, a value is
3599                    substituted in.
3600    flags  - When an exception is caused, flags[exception] is incremented.
3601             (Whether or not the trap_enabler is set)
3602             Should be reset by user of Decimal instance.
3603    Emin -   Minimum exponent
3604    Emax -   Maximum exponent
3605    capitals -      If 1, 1*10^1 is printed as 1E+1.
3606                    If 0, printed as 1e1
3607    _clamp - If 1, change exponents if too high (Default 0)
3608    """
3609
3610    def __init__(self, prec=None, rounding=None,
3611                 traps=None, flags=None,
3612                 Emin=None, Emax=None,
3613                 capitals=None, _clamp=0,
3614                 _ignored_flags=None):
3615        if flags is None:
3616            flags = []
3617        if _ignored_flags is None:
3618            _ignored_flags = []
3619        if not isinstance(flags, dict):
3620            flags = dict([(s,s in flags) for s in _signals])
3621            del s
3622        if traps is not None and not isinstance(traps, dict):
3623            traps = dict([(s,s in traps) for s in _signals])
3624            del s
3625        for name, val in locals().items():
3626            if val is None:
3627                setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
3628            else:
3629                setattr(self, name, val)
3630        del self.self
3631
3632    def __repr__(self):
3633        """Show the current context."""
3634        s = []
3635        s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3636                 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3637                 % vars(self))
3638        names = [f.__name__ for f, v in self.flags.items() if v]
3639        s.append('flags=[' + ', '.join(names) + ']')
3640        names = [t.__name__ for t, v in self.traps.items() if v]
3641        s.append('traps=[' + ', '.join(names) + ']')
3642        return ', '.join(s) + ')'
3643
3644    def clear_flags(self):
3645        """Reset all flags to zero"""
3646        for flag in self.flags:
3647            self.flags[flag] = 0
3648
3649    def _shallow_copy(self):
3650        """Returns a shallow copy from self."""
3651        nc = Context(self.prec, self.rounding, self.traps,
3652                     self.flags, self.Emin, self.Emax,
3653                     self.capitals, self._clamp, self._ignored_flags)
3654        return nc
3655
3656    def copy(self):
3657        """Returns a deep copy from self."""
3658        nc = Context(self.prec, self.rounding, self.traps.copy(),
3659                     self.flags.copy(), self.Emin, self.Emax,
3660                     self.capitals, self._clamp, self._ignored_flags)
3661        return nc
3662    __copy__ = copy
3663
3664    def _raise_error(self, condition, explanation = None, *args):
3665        """Handles an error
3666
3667        If the flag is in _ignored_flags, returns the default response.
3668        Otherwise, it increments the flag, then, if the corresponding
3669        trap_enabler is set, it reaises the exception.  Otherwise, it returns
3670        the default value after incrementing the flag.
3671        """
3672        error = _condition_map.get(condition, condition)
3673        if error in self._ignored_flags:
3674            # Don't touch the flag
3675            return error().handle(self, *args)
3676
3677        self.flags[error] += 1
3678        if not self.traps[error]:
3679            # The errors define how to handle themselves.
3680            return condition().handle(self, *args)
3681
3682        # Errors should only be risked on copies of the context
3683        # self._ignored_flags = []
3684        raise error, explanation
3685
3686    def _ignore_all_flags(self):
3687        """Ignore all flags, if they are raised"""
3688        return self._ignore_flags(*_signals)
3689
3690    def _ignore_flags(self, *flags):
3691        """Ignore the flags, if they are raised"""
3692        # Do not mutate-- This way, copies of a context leave the original
3693        # alone.
3694        self._ignored_flags = (self._ignored_flags + list(flags))
3695        return list(flags)
3696
3697    def _regard_flags(self, *flags):
3698        """Stop ignoring the flags, if they are raised"""
3699        if flags and isinstance(flags[0], (tuple,list)):
3700            flags = flags[0]
3701        for flag in flags:
3702            self._ignored_flags.remove(flag)
3703
3704    def __hash__(self):
3705        """A Context cannot be hashed."""
3706        # We inherit object.__hash__, so we must deny this explicitly
3707        raise TypeError("Cannot hash a Context.")
3708
3709    def Etiny(self):
3710        """Returns Etiny (= Emin - prec + 1)"""
3711        return int(self.Emin - self.prec + 1)
3712
3713    def Etop(self):
3714        """Returns maximum exponent (= Emax - prec + 1)"""
3715        return int(self.Emax - self.prec + 1)
3716
3717    def _set_rounding(self, type):
3718        """Sets the rounding type.
3719
3720        Sets the rounding type, and returns the current (previous)
3721        rounding type.  Often used like:
3722
3723        context = context.copy()
3724        # so you don't change the calling context
3725        # if an error occurs in the middle.
3726        rounding = context._set_rounding(ROUND_UP)
3727        val = self.__sub__(other, context=context)
3728        context._set_rounding(rounding)
3729
3730        This will make it round up for that operation.
3731        """
3732        rounding = self.rounding
3733        self.rounding= type
3734        return rounding
3735
3736    def create_decimal(self, num='0'):
3737        """Creates a new Decimal instance but using self as context.
3738
3739        This method implements the to-number operation of the
3740        IBM Decimal specification."""
3741
3742        if isinstance(num, basestring) and num != num.strip():
3743            return self._raise_error(ConversionSyntax,
3744                                     "no trailing or leading whitespace is "
3745                                     "permitted.")
3746
3747        d = Decimal(num, context=self)
3748        if d._isnan() and len(d._int) > self.prec - self._clamp:
3749            return self._raise_error(ConversionSyntax,
3750                                     "diagnostic info too long in NaN")
3751        return d._fix(self)
3752
3753    # Methods
3754    def abs(self, a):
3755        """Returns the absolute value of the operand.
3756
3757        If the operand is negative, the result is the same as using the minus
3758        operation on the operand.  Otherwise, the result is the same as using
3759        the plus operation on the operand.
3760
3761        >>> ExtendedContext.abs(Decimal('2.1'))
3762        Decimal('2.1')
3763        >>> ExtendedContext.abs(Decimal('-100'))
3764        Decimal('100')
3765        >>> ExtendedContext.abs(Decimal('101.5'))
3766        Decimal('101.5')
3767        >>> ExtendedContext.abs(Decimal('-101.5'))
3768        Decimal('101.5')
3769        """
3770        return a.__abs__(context=self)
3771
3772    def add(self, a, b):
3773        """Return the sum of the two operands.
3774
3775        >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
3776        Decimal('19.00')
3777        >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
3778        Decimal('1.02E+4')
3779        """
3780        return a.__add__(b, context=self)
3781
3782    def _apply(self, a):
3783        return str(a._fix(self))
3784
3785    def canonical(self, a):
3786        """Returns the same Decimal object.
3787
3788        As we do not have different encodings for the same number, the
3789        received object already is in its canonical form.
3790
3791        >>> ExtendedContext.canonical(Decimal('2.50'))
3792        Decimal('2.50')
3793        """
3794        return a.canonical(context=self)
3795
3796    def compare(self, a, b):
3797        """Compares values numerically.
3798
3799        If the signs of the operands differ, a value representing each operand
3800        ('-1' if the operand is less than zero, '0' if the operand is zero or
3801        negative zero, or '1' if the operand is greater than zero) is used in
3802        place of that operand for the comparison instead of the actual
3803        operand.
3804
3805        The comparison is then effected by subtracting the second operand from
3806        the first and then returning a value according to the result of the
3807        subtraction: '-1' if the result is less than zero, '0' if the result is
3808        zero or negative zero, or '1' if the result is greater than zero.
3809
3810        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
3811        Decimal('-1')
3812        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
3813        Decimal('0')
3814        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
3815        Decimal('0')
3816        >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
3817        Decimal('1')
3818        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
3819        Decimal('1')
3820        >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
3821        Decimal('-1')
3822        """
3823        return a.compare(b, context=self)
3824
3825    def compare_signal(self, a, b):
3826        """Compares the values of the two operands numerically.
3827
3828        It's pretty much like compare(), but all NaNs signal, with signaling
3829        NaNs taking precedence over quiet NaNs.
3830
3831        >>> c = ExtendedContext
3832        >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3833        Decimal('-1')
3834        >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3835        Decimal('0')
3836        >>> c.flags[InvalidOperation] = 0
3837        >>> print c.flags[InvalidOperation]
3838        0
3839        >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3840        Decimal('NaN')
3841        >>> print c.flags[InvalidOperation]
3842        1
3843        >>> c.flags[InvalidOperation] = 0
3844        >>> print c.flags[InvalidOperation]
3845        0
3846        >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3847        Decimal('NaN')
3848        >>> print c.flags[InvalidOperation]
3849        1
3850        """
3851        return a.compare_signal(b, context=self)
3852
3853    def compare_total(self, a, b):
3854        """Compares two operands using their abstract representation.
3855
3856        This is not like the standard compare, which use their numerical
3857        value. Note that a total ordering is defined for all possible abstract
3858        representations.
3859
3860        >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3861        Decimal('-1')
3862        >>> ExtendedContext.compare_total(Decimal('-127'),  Decimal('12'))
3863        Decimal('-1')
3864        >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3865        Decimal('-1')
3866        >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3867        Decimal('0')
3868        >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('12.300'))
3869        Decimal('1')
3870        >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('NaN'))
3871        Decimal('-1')
3872        """
3873        return a.compare_total(b)
3874
3875    def compare_total_mag(self, a, b):
3876        """Compares two operands using their abstract representation ignoring sign.
3877
3878        Like compare_total, but with operand's sign ignored and assumed to be 0.
3879        """
3880        return a.compare_total_mag(b)
3881
3882    def copy_abs(self, a):
3883        """Returns a copy of the operand with the sign set to 0.
3884
3885        >>> ExtendedContext.copy_abs(Decimal('2.1'))
3886        Decimal('2.1')
3887        >>> ExtendedContext.copy_abs(Decimal('-100'))
3888        Decimal('100')
3889        """
3890        return a.copy_abs()
3891
3892    def copy_decimal(self, a):
3893        """Returns a copy of the decimal objet.
3894
3895        >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3896        Decimal('2.1')
3897        >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3898        Decimal('-1.00')
3899        """
3900        return Decimal(a)
3901
3902    def copy_negate(self, a):
3903        """Returns a copy of the operand with the sign inverted.
3904
3905        >>> ExtendedContext.copy_negate(Decimal('101.5'))
3906        Decimal('-101.5')
3907        >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3908        Decimal('101.5')
3909        """
3910        return a.copy_negate()
3911
3912    def copy_sign(self, a, b):
3913        """Copies the second operand's sign to the first one.
3914
3915        In detail, it returns a copy of the first operand with the sign
3916        equal to the sign of the second operand.
3917
3918        >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3919        Decimal('1.50')
3920        >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3921        Decimal('1.50')
3922        >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3923        Decimal('-1.50')
3924        >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3925        Decimal('-1.50')
3926        """
3927        return a.copy_sign(b)
3928
3929    def divide(self, a, b):
3930        """Decimal division in a specified context.
3931
3932        >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
3933        Decimal('0.333333333')
3934        >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
3935        Decimal('0.666666667')
3936        >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
3937        Decimal('2.5')
3938        >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
3939        Decimal('0.1')
3940        >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
3941        Decimal('1')
3942        >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
3943        Decimal('4.00')
3944        >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
3945        Decimal('1.20')
3946        >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
3947        Decimal('10')
3948        >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
3949        Decimal('1000')
3950        >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
3951        Decimal('1.20E+6')
3952        """
3953        return a.__div__(b, context=self)
3954
3955    def divide_int(self, a, b):
3956        """Divides two numbers and returns the integer part of the result.
3957
3958        >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
3959        Decimal('0')
3960        >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
3961        Decimal('3')
3962        >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
3963        Decimal('3')
3964        """
3965        return a.__floordiv__(b, context=self)
3966
3967    def divmod(self, a, b):
3968        return a.__divmod__(b, context=self)
3969
3970    def exp(self, a):
3971        """Returns e ** a.
3972
3973        >>> c = ExtendedContext.copy()
3974        >>> c.Emin = -999
3975        >>> c.Emax = 999
3976        >>> c.exp(Decimal('-Infinity'))
3977        Decimal('0')
3978        >>> c.exp(Decimal('-1'))
3979        Decimal('0.367879441')
3980        >>> c.exp(Decimal('0'))
3981        Decimal('1')
3982        >>> c.exp(Decimal('1'))
3983        Decimal('2.71828183')
3984        >>> c.exp(Decimal('0.693147181'))
3985        Decimal('2.00000000')
3986        >>> c.exp(Decimal('+Infinity'))
3987        Decimal('Infinity')
3988        """
3989        return a.exp(context=self)
3990
3991    def fma(self, a, b, c):
3992        """Returns a multiplied by b, plus c.
3993
3994        The first two operands are multiplied together, using multiply,
3995        the third operand is then added to the result of that
3996        multiplication, using add, all with only one final rounding.
3997
3998        >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3999        Decimal('22')
4000        >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
4001        Decimal('-8')
4002        >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
4003        Decimal('1.38435736E+12')
4004        """
4005        return a.fma(b, c, context=self)
4006
4007    def is_canonical(self, a):
4008        """Return True if the operand is canonical; otherwise return False.
4009
4010        Currently, the encoding of a Decimal instance is always
4011        canonical, so this method returns True for any Decimal.
4012
4013        >>> ExtendedContext.is_canonical(Decimal('2.50'))
4014        True
4015        """
4016        return a.is_canonical()
4017
4018    def is_finite(self, a):
4019        """Return True if the operand is finite; otherwise return False.
4020
4021        A Decimal instance is considered finite if it is neither
4022        infinite nor a NaN.
4023
4024        >>> ExtendedContext.is_finite(Decimal('2.50'))
4025        True
4026        >>> ExtendedContext.is_finite(Decimal('-0.3'))
4027        True
4028        >>> ExtendedContext.is_finite(Decimal('0'))
4029        True
4030        >>> ExtendedContext.is_finite(Decimal('Inf'))
4031        False
4032        >>> ExtendedContext.is_finite(Decimal('NaN'))
4033        False
4034        """
4035        return a.is_finite()
4036
4037    def is_infinite(self, a):
4038        """Return True if the operand is infinite; otherwise return False.
4039
4040        >>> ExtendedContext.is_infinite(Decimal('2.50'))
4041        False
4042        >>> ExtendedContext.is_infinite(Decimal('-Inf'))
4043        True
4044        >>> ExtendedContext.is_infinite(Decimal('NaN'))
4045        False
4046        """
4047        return a.is_infinite()
4048
4049    def is_nan(self, a):
4050        """Return True if the operand is a qNaN or sNaN;
4051        otherwise return False.
4052
4053        >>> ExtendedContext.is_nan(Decimal('2.50'))
4054        False
4055        >>> ExtendedContext.is_nan(Decimal('NaN'))
4056        True
4057        >>> ExtendedContext.is_nan(Decimal('-sNaN'))
4058        True
4059        """
4060        return a.is_nan()
4061
4062    def is_normal(self, a):
4063        """Return True if the operand is a normal number;
4064        otherwise return False.
4065
4066        >>> c = ExtendedContext.copy()
4067        >>> c.Emin = -999
4068        >>> c.Emax = 999
4069        >>> c.is_normal(Decimal('2.50'))
4070        True
4071        >>> c.is_normal(Decimal('0.1E-999'))
4072        False
4073        >>> c.is_normal(Decimal('0.00'))
4074        False
4075        >>> c.is_normal(Decimal('-Inf'))
4076        False
4077        >>> c.is_normal(Decimal('NaN'))
4078        False
4079        """
4080        return a.is_normal(context=self)
4081
4082    def is_qnan(self, a):
4083        """Return True if the operand is a quiet NaN; otherwise return False.
4084
4085        >>> ExtendedContext.is_qnan(Decimal('2.50'))
4086        False
4087        >>> ExtendedContext.is_qnan(Decimal('NaN'))
4088        True
4089        >>> ExtendedContext.is_qnan(Decimal('sNaN'))
4090        False
4091        """
4092        return a.is_qnan()
4093
4094    def is_signed(self, a):
4095        """Return True if the operand is negative; otherwise return False.
4096
4097        >>> ExtendedContext.is_signed(Decimal('2.50'))
4098        False
4099        >>> ExtendedContext.is_signed(Decimal('-12'))
4100        True
4101        >>> ExtendedContext.is_signed(Decimal('-0'))
4102        True
4103        """
4104        return a.is_signed()
4105
4106    def is_snan(self, a):
4107        """Return True if the operand is a signaling NaN;
4108        otherwise return False.
4109
4110        >>> ExtendedContext.is_snan(Decimal('2.50'))
4111        False
4112        >>> ExtendedContext.is_snan(Decimal('NaN'))
4113        False
4114        >>> ExtendedContext.is_snan(Decimal('sNaN'))
4115        True
4116        """
4117        return a.is_snan()
4118
4119    def is_subnormal(self, a):
4120        """Return True if the operand is subnormal; otherwise return False.
4121
4122        >>> c = ExtendedContext.copy()
4123        >>> c.Emin = -999
4124        >>> c.Emax = 999
4125        >>> c.is_subnormal(Decimal('2.50'))
4126        False
4127        >>> c.is_subnormal(Decimal('0.1E-999'))
4128        True
4129        >>> c.is_subnormal(Decimal('0.00'))
4130        False
4131        >>> c.is_subnormal(Decimal('-Inf'))
4132        False
4133        >>> c.is_subnormal(Decimal('NaN'))
4134        False
4135        """
4136        return a.is_subnormal(context=self)
4137
4138    def is_zero(self, a):
4139        """Return True if the operand is a zero; otherwise return False.
4140
4141        >>> ExtendedContext.is_zero(Decimal('0'))
4142        True
4143        >>> ExtendedContext.is_zero(Decimal('2.50'))
4144        False
4145        >>> ExtendedContext.is_zero(Decimal('-0E+2'))
4146        True
4147        """
4148        return a.is_zero()
4149
4150    def ln(self, a):
4151        """Returns the natural (base e) logarithm of the operand.
4152
4153        >>> c = ExtendedContext.copy()
4154        >>> c.Emin = -999
4155        >>> c.Emax = 999
4156        >>> c.ln(Decimal('0'))
4157        Decimal('-Infinity')
4158        >>> c.ln(Decimal('1.000'))
4159        Decimal('0')
4160        >>> c.ln(Decimal('2.71828183'))
4161        Decimal('1.00000000')
4162        >>> c.ln(Decimal('10'))
4163        Decimal('2.30258509')
4164        >>> c.ln(Decimal('+Infinity'))
4165        Decimal('Infinity')
4166        """
4167        return a.ln(context=self)
4168
4169    def log10(self, a):
4170        """Returns the base 10 logarithm of the operand.
4171
4172        >>> c = ExtendedContext.copy()
4173        >>> c.Emin = -999
4174        >>> c.Emax = 999
4175        >>> c.log10(Decimal('0'))
4176        Decimal('-Infinity')
4177        >>> c.log10(Decimal('0.001'))
4178        Decimal('-3')
4179        >>> c.log10(Decimal('1.000'))
4180        Decimal('0')
4181        >>> c.log10(Decimal('2'))
4182        Decimal('0.301029996')
4183        >>> c.log10(Decimal('10'))
4184        Decimal('1')
4185        >>> c.log10(Decimal('70'))
4186        Decimal('1.84509804')
4187        >>> c.log10(Decimal('+Infinity'))
4188        Decimal('Infinity')
4189        """
4190        return a.log10(context=self)
4191
4192    def logb(self, a):
4193        """ Returns the exponent of the magnitude of the operand's MSD.
4194
4195        The result is the integer which is the exponent of the magnitude
4196        of the most significant digit of the operand (as though the
4197        operand were truncated to a single digit while maintaining the
4198        value of that digit and without limiting the resulting exponent).
4199
4200        >>> ExtendedContext.logb(Decimal('250'))
4201        Decimal('2')
4202        >>> ExtendedContext.logb(Decimal('2.50'))
4203        Decimal('0')
4204        >>> ExtendedContext.logb(Decimal('0.03'))
4205        Decimal('-2')
4206        >>> ExtendedContext.logb(Decimal('0'))
4207        Decimal('-Infinity')
4208        """
4209        return a.logb(context=self)
4210
4211    def logical_and(self, a, b):
4212        """Applies the logical operation 'and' between each operand's digits.
4213
4214        The operands must be both logical numbers.
4215
4216        >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4217        Decimal('0')
4218        >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4219        Decimal('0')
4220        >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4221        Decimal('0')
4222        >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4223        Decimal('1')
4224        >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4225        Decimal('1000')
4226        >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4227        Decimal('10')
4228        """
4229        return a.logical_and(b, context=self)
4230
4231    def logical_invert(self, a):
4232        """Invert all the digits in the operand.
4233
4234        The operand must be a logical number.
4235
4236        >>> ExtendedContext.logical_invert(Decimal('0'))
4237        Decimal('111111111')
4238        >>> ExtendedContext.logical_invert(Decimal('1'))
4239        Decimal('111111110')
4240        >>> ExtendedContext.logical_invert(Decimal('111111111'))
4241        Decimal('0')
4242        >>> ExtendedContext.logical_invert(Decimal('101010101'))
4243        Decimal('10101010')
4244        """
4245        return a.logical_invert(context=self)
4246
4247    def logical_or(self, a, b):
4248        """Applies the logical operation 'or' between each operand's digits.
4249
4250        The operands must be both logical numbers.
4251
4252        >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4253        Decimal('0')
4254        >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4255        Decimal('1')
4256        >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4257        Decimal('1')
4258        >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4259        Decimal('1')
4260        >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4261        Decimal('1110')
4262        >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4263        Decimal('1110')
4264        """
4265        return a.logical_or(b, context=self)
4266
4267    def logical_xor(self, a, b):
4268        """Applies the logical operation 'xor' between each operand's digits.
4269
4270        The operands must be both logical numbers.
4271
4272        >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4273        Decimal('0')
4274        >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4275        Decimal('1')
4276        >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4277        Decimal('1')
4278        >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4279        Decimal('0')
4280        >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4281        Decimal('110')
4282        >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4283        Decimal('1101')
4284        """
4285        return a.logical_xor(b, context=self)
4286
4287    def max(self, a,b):
4288        """max compares two values numerically and returns the maximum.
4289
4290        If either operand is a NaN then the general rules apply.
4291        Otherwise, the operands are compared as though by the compare
4292        operation.  If they are numerically equal then the left-hand operand
4293        is chosen as the result.  Otherwise the maximum (closer to positive
4294        infinity) of the two operands is chosen as the result.
4295
4296        >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
4297        Decimal('3')
4298        >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
4299        Decimal('3')
4300        >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
4301        Decimal('1')
4302        >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4303        Decimal('7')
4304        """
4305        return a.max(b, context=self)
4306
4307    def max_mag(self, a, b):
4308        """Compares the values numerically with their sign ignored."""
4309        return a.max_mag(b, context=self)
4310
4311    def min(self, a,b):
4312        """min compares two values numerically and returns the minimum.
4313
4314        If either operand is a NaN then the general rules apply.
4315        Otherwise, the operands are compared as though by the compare
4316        operation.  If they are numerically equal then the left-hand operand
4317        is chosen as the result.  Otherwise the minimum (closer to negative
4318        infinity) of the two operands is chosen as the result.
4319
4320        >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
4321        Decimal('2')
4322        >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
4323        Decimal('-10')
4324        >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
4325        Decimal('1.0')
4326        >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4327        Decimal('7')
4328        """
4329        return a.min(b, context=self)
4330
4331    def min_mag(self, a, b):
4332        """Compares the values numerically with their sign ignored."""
4333        return a.min_mag(b, context=self)
4334
4335    def minus(self, a):
4336        """Minus corresponds to unary prefix minus in Python.
4337
4338        The operation is evaluated using the same rules as subtract; the
4339        operation minus(a) is calculated as subtract('0', a) where the '0'
4340        has the same exponent as the operand.
4341
4342        >>> ExtendedContext.minus(Decimal('1.3'))
4343        Decimal('-1.3')
4344        >>> ExtendedContext.minus(Decimal('-1.3'))
4345        Decimal('1.3')
4346        """
4347        return a.__neg__(context=self)
4348
4349    def multiply(self, a, b):
4350        """multiply multiplies two operands.
4351
4352        If either operand is a special value then the general rules apply.
4353        Otherwise, the operands are multiplied together ('long multiplication'),
4354        resulting in a number which may be as long as the sum of the lengths
4355        of the two operands.
4356
4357        >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
4358        Decimal('3.60')
4359        >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
4360        Decimal('21')
4361        >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
4362        Decimal('0.72')
4363        >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
4364        Decimal('-0.0')
4365        >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
4366        Decimal('4.28135971E+11')
4367        """
4368        return a.__mul__(b, context=self)
4369
4370    def next_minus(self, a):
4371        """Returns the largest representable number smaller than a.
4372
4373        >>> c = ExtendedContext.copy()
4374        >>> c.Emin = -999
4375        >>> c.Emax = 999
4376        >>> ExtendedContext.next_minus(Decimal('1'))
4377        Decimal('0.999999999')
4378        >>> c.next_minus(Decimal('1E-1007'))
4379        Decimal('0E-1007')
4380        >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4381        Decimal('-1.00000004')
4382        >>> c.next_minus(Decimal('Infinity'))
4383        Decimal('9.99999999E+999')
4384        """
4385        return a.next_minus(context=self)
4386
4387    def next_plus(self, a):
4388        """Returns the smallest representable number larger than a.
4389
4390        >>> c = ExtendedContext.copy()
4391        >>> c.Emin = -999
4392        >>> c.Emax = 999
4393        >>> ExtendedContext.next_plus(Decimal('1'))
4394        Decimal('1.00000001')
4395        >>> c.next_plus(Decimal('-1E-1007'))
4396        Decimal('-0E-1007')
4397        >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4398        Decimal('-1.00000002')
4399        >>> c.next_plus(Decimal('-Infinity'))
4400        Decimal('-9.99999999E+999')
4401        """
4402        return a.next_plus(context=self)
4403
4404    def next_toward(self, a, b):
4405        """Returns the number closest to a, in direction towards b.
4406
4407        The result is the closest representable number from the first
4408        operand (but not the first operand) that is in the direction
4409        towards the second operand, unless the operands have the same
4410        value.
4411
4412        >>> c = ExtendedContext.copy()
4413        >>> c.Emin = -999
4414        >>> c.Emax = 999
4415        >>> c.next_toward(Decimal('1'), Decimal('2'))
4416        Decimal('1.00000001')
4417        >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4418        Decimal('-0E-1007')
4419        >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4420        Decimal('-1.00000002')
4421        >>> c.next_toward(Decimal('1'), Decimal('0'))
4422        Decimal('0.999999999')
4423        >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4424        Decimal('0E-1007')
4425        >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4426        Decimal('-1.00000004')
4427        >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4428        Decimal('-0.00')
4429        """
4430        return a.next_toward(b, context=self)
4431
4432    def normalize(self, a):
4433        """normalize reduces an operand to its simplest form.
4434
4435        Essentially a plus operation with all trailing zeros removed from the
4436        result.
4437
4438        >>> ExtendedContext.normalize(Decimal('2.1'))
4439        Decimal('2.1')
4440        >>> ExtendedContext.normalize(Decimal('-2.0'))
4441        Decimal('-2')
4442        >>> ExtendedContext.normalize(Decimal('1.200'))
4443        Decimal('1.2')
4444        >>> ExtendedContext.normalize(Decimal('-120'))
4445        Decimal('-1.2E+2')
4446        >>> ExtendedContext.normalize(Decimal('120.00'))
4447        Decimal('1.2E+2')
4448        >>> ExtendedContext.normalize(Decimal('0.00'))
4449        Decimal('0')
4450        """
4451        return a.normalize(context=self)
4452
4453    def number_class(self, a):
4454        """Returns an indication of the class of the operand.
4455
4456        The class is one of the following strings:
4457          -sNaN
4458          -NaN
4459          -Infinity
4460          -Normal
4461          -Subnormal
4462          -Zero
4463          +Zero
4464          +Subnormal
4465          +Normal
4466          +Infinity
4467
4468        >>> c = Context(ExtendedContext)
4469        >>> c.Emin = -999
4470        >>> c.Emax = 999
4471        >>> c.number_class(Decimal('Infinity'))
4472        '+Infinity'
4473        >>> c.number_class(Decimal('1E-10'))
4474        '+Normal'
4475        >>> c.number_class(Decimal('2.50'))
4476        '+Normal'
4477        >>> c.number_class(Decimal('0.1E-999'))
4478        '+Subnormal'
4479        >>> c.number_class(Decimal('0'))
4480        '+Zero'
4481        >>> c.number_class(Decimal('-0'))
4482        '-Zero'
4483        >>> c.number_class(Decimal('-0.1E-999'))
4484        '-Subnormal'
4485        >>> c.number_class(Decimal('-1E-10'))
4486        '-Normal'
4487        >>> c.number_class(Decimal('-2.50'))
4488        '-Normal'
4489        >>> c.number_class(Decimal('-Infinity'))
4490        '-Infinity'
4491        >>> c.number_class(Decimal('NaN'))
4492        'NaN'
4493        >>> c.number_class(Decimal('-NaN'))
4494        'NaN'
4495        >>> c.number_class(Decimal('sNaN'))
4496        'sNaN'
4497        """
4498        return a.number_class(context=self)
4499
4500    def plus(self, a):
4501        """Plus corresponds to unary prefix plus in Python.
4502
4503        The operation is evaluated using the same rules as add; the
4504        operation plus(a) is calculated as add('0', a) where the '0'
4505        has the same exponent as the operand.
4506
4507        >>> ExtendedContext.plus(Decimal('1.3'))
4508        Decimal('1.3')
4509        >>> ExtendedContext.plus(Decimal('-1.3'))
4510        Decimal('-1.3')
4511        """
4512        return a.__pos__(context=self)
4513
4514    def power(self, a, b, modulo=None):
4515        """Raises a to the power of b, to modulo if given.
4516
4517        With two arguments, compute a**b.  If a is negative then b
4518        must be integral.  The result will be inexact unless b is
4519        integral and the result is finite and can be expressed exactly
4520        in 'precision' digits.
4521
4522        With three arguments, compute (a**b) % modulo.  For the
4523        three argument form, the following restrictions on the
4524        arguments hold:
4525
4526         - all three arguments must be integral
4527         - b must be nonnegative
4528         - at least one of a or b must be nonzero
4529         - modulo must be nonzero and have at most 'precision' digits
4530
4531        The result of pow(a, b, modulo) is identical to the result
4532        that would be obtained by computing (a**b) % modulo with
4533        unbounded precision, but is computed more efficiently.  It is
4534        always exact.
4535
4536        >>> c = ExtendedContext.copy()
4537        >>> c.Emin = -999
4538        >>> c.Emax = 999
4539        >>> c.power(Decimal('2'), Decimal('3'))
4540        Decimal('8')
4541        >>> c.power(Decimal('-2'), Decimal('3'))
4542        Decimal('-8')
4543        >>> c.power(Decimal('2'), Decimal('-3'))
4544        Decimal('0.125')
4545        >>> c.power(Decimal('1.7'), Decimal('8'))
4546        Decimal('69.7575744')
4547        >>> c.power(Decimal('10'), Decimal('0.301029996'))
4548        Decimal('2.00000000')
4549        >>> c.power(Decimal('Infinity'), Decimal('-1'))
4550        Decimal('0')
4551        >>> c.power(Decimal('Infinity'), Decimal('0'))
4552        Decimal('1')
4553        >>> c.power(Decimal('Infinity'), Decimal('1'))
4554        Decimal('Infinity')
4555        >>> c.power(Decimal('-Infinity'), Decimal('-1'))
4556        Decimal('-0')
4557        >>> c.power(Decimal('-Infinity'), Decimal('0'))
4558        Decimal('1')
4559        >>> c.power(Decimal('-Infinity'), Decimal('1'))
4560        Decimal('-Infinity')
4561        >>> c.power(Decimal('-Infinity'), Decimal('2'))
4562        Decimal('Infinity')
4563        >>> c.power(Decimal('0'), Decimal('0'))
4564        Decimal('NaN')
4565
4566        >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4567        Decimal('11')
4568        >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4569        Decimal('-11')
4570        >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4571        Decimal('1')
4572        >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4573        Decimal('11')
4574        >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4575        Decimal('11729830')
4576        >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4577        Decimal('-0')
4578        >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4579        Decimal('1')
4580        """
4581        return a.__pow__(b, modulo, context=self)
4582
4583    def quantize(self, a, b):
4584        """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
4585
4586        The coefficient of the result is derived from that of the left-hand
4587        operand.  It may be rounded using the current rounding setting (if the
4588        exponent is being increased), multiplied by a positive power of ten (if
4589        the exponent is being decreased), or is unchanged (if the exponent is
4590        already equal to that of the right-hand operand).
4591
4592        Unlike other operations, if the length of the coefficient after the
4593        quantize operation would be greater than precision then an Invalid
4594        operation condition is raised.  This guarantees that, unless there is
4595        an error condition, the exponent of the result of a quantize is always
4596        equal to that of the right-hand operand.
4597
4598        Also unlike other operations, quantize will never raise Underflow, even
4599        if the result is subnormal and inexact.
4600
4601        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
4602        Decimal('2.170')
4603        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
4604        Decimal('2.17')
4605        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
4606        Decimal('2.2')
4607        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
4608        Decimal('2')
4609        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
4610        Decimal('0E+1')
4611        >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
4612        Decimal('-Infinity')
4613        >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
4614        Decimal('NaN')
4615        >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
4616        Decimal('-0')
4617        >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
4618        Decimal('-0E+5')
4619        >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
4620        Decimal('NaN')
4621        >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
4622        Decimal('NaN')
4623        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
4624        Decimal('217.0')
4625        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
4626        Decimal('217')
4627        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
4628        Decimal('2.2E+2')
4629        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
4630        Decimal('2E+2')
4631        """
4632        return a.quantize(b, context=self)
4633
4634    def radix(self):
4635        """Just returns 10, as this is Decimal, :)
4636
4637        >>> ExtendedContext.radix()
4638        Decimal('10')
4639        """
4640        return Decimal(10)
4641
4642    def remainder(self, a, b):
4643        """Returns the remainder from integer division.
4644
4645        The result is the residue of the dividend after the operation of
4646        calculating integer division as described for divide-integer, rounded
4647        to precision digits if necessary.  The sign of the result, if
4648        non-zero, is the same as that of the original dividend.
4649
4650        This operation will fail under the same conditions as integer division
4651        (that is, if integer division on the same two operands would fail, the
4652        remainder cannot be calculated).
4653
4654        >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
4655        Decimal('2.1')
4656        >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
4657        Decimal('1')
4658        >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
4659        Decimal('-1')
4660        >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
4661        Decimal('0.2')
4662        >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
4663        Decimal('0.1')
4664        >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
4665        Decimal('1.0')
4666        """
4667        return a.__mod__(b, context=self)
4668
4669    def remainder_near(self, a, b):
4670        """Returns to be "a - b * n", where n is the integer nearest the exact
4671        value of "x / b" (if two integers are equally near then the even one
4672        is chosen).  If the result is equal to 0 then its sign will be the
4673        sign of a.
4674
4675        This operation will fail under the same conditions as integer division
4676        (that is, if integer division on the same two operands would fail, the
4677        remainder cannot be calculated).
4678
4679        >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
4680        Decimal('-0.9')
4681        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
4682        Decimal('-2')
4683        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
4684        Decimal('1')
4685        >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
4686        Decimal('-1')
4687        >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
4688        Decimal('0.2')
4689        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
4690        Decimal('0.1')
4691        >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
4692        Decimal('-0.3')
4693        """
4694        return a.remainder_near(b, context=self)
4695
4696    def rotate(self, a, b):
4697        """Returns a rotated copy of a, b times.
4698
4699        The coefficient of the result is a rotated copy of the digits in
4700        the coefficient of the first operand.  The number of places of
4701        rotation is taken from the absolute value of the second operand,
4702        with the rotation being to the left if the second operand is
4703        positive or to the right otherwise.
4704
4705        >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4706        Decimal('400000003')
4707        >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4708        Decimal('12')
4709        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4710        Decimal('891234567')
4711        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4712        Decimal('123456789')
4713        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4714        Decimal('345678912')
4715        """
4716        return a.rotate(b, context=self)
4717
4718    def same_quantum(self, a, b):
4719        """Returns True if the two operands have the same exponent.
4720
4721        The result is never affected by either the sign or the coefficient of
4722        either operand.
4723
4724        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
4725        False
4726        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
4727        True
4728        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
4729        False
4730        >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
4731        True
4732        """
4733        return a.same_quantum(b)
4734
4735    def scaleb (self, a, b):
4736        """Returns the first operand after adding the second value its exp.
4737
4738        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4739        Decimal('0.0750')
4740        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4741        Decimal('7.50')
4742        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4743        Decimal('7.50E+3')
4744        """
4745        return a.scaleb (b, context=self)
4746
4747    def shift(self, a, b):
4748        """Returns a shifted copy of a, b times.
4749
4750        The coefficient of the result is a shifted copy of the digits
4751        in the coefficient of the first operand.  The number of places
4752        to shift is taken from the absolute value of the second operand,
4753        with the shift being to the left if the second operand is
4754        positive or to the right otherwise.  Digits shifted into the
4755        coefficient are zeros.
4756
4757        >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4758        Decimal('400000000')
4759        >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4760        Decimal('0')
4761        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4762        Decimal('1234567')
4763        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4764        Decimal('123456789')
4765        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4766        Decimal('345678900')
4767        """
4768        return a.shift(b, context=self)
4769
4770    def sqrt(self, a):
4771        """Square root of a non-negative number to context precision.
4772
4773        If the result must be inexact, it is rounded using the round-half-even
4774        algorithm.
4775
4776        >>> ExtendedContext.sqrt(Decimal('0'))
4777        Decimal('0')
4778        >>> ExtendedContext.sqrt(Decimal('-0'))
4779        Decimal('-0')
4780        >>> ExtendedContext.sqrt(Decimal('0.39'))
4781        Decimal('0.624499800')
4782        >>> ExtendedContext.sqrt(Decimal('100'))
4783        Decimal('10')
4784        >>> ExtendedContext.sqrt(Decimal('1'))
4785        Decimal('1')
4786        >>> ExtendedContext.sqrt(Decimal('1.0'))
4787        Decimal('1.0')
4788        >>> ExtendedContext.sqrt(Decimal('1.00'))
4789        Decimal('1.0')
4790        >>> ExtendedContext.sqrt(Decimal('7'))
4791        Decimal('2.64575131')
4792        >>> ExtendedContext.sqrt(Decimal('10'))
4793        Decimal('3.16227766')
4794        >>> ExtendedContext.prec
4795        9
4796        """
4797        return a.sqrt(context=self)
4798
4799    def subtract(self, a, b):
4800        """Return the difference between the two operands.
4801
4802        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
4803        Decimal('0.23')
4804        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
4805        Decimal('0.00')
4806        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
4807        Decimal('-0.77')
4808        """
4809        return a.__sub__(b, context=self)
4810
4811    def to_eng_string(self, a):
4812        """Converts a number to a string, using scientific notation.
4813
4814        The operation is not affected by the context.
4815        """
4816        return a.to_eng_string(context=self)
4817
4818    def to_sci_string(self, a):
4819        """Converts a number to a string, using scientific notation.
4820
4821        The operation is not affected by the context.
4822        """
4823        return a.__str__(context=self)
4824
4825    def to_integral_exact(self, a):
4826        """Rounds to an integer.
4827
4828        When the operand has a negative exponent, the result is the same
4829        as using the quantize() operation using the given operand as the
4830        left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4831        of the operand as the precision setting; Inexact and Rounded flags
4832        are allowed in this operation.  The rounding mode is taken from the
4833        context.
4834
4835        >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4836        Decimal('2')
4837        >>> ExtendedContext.to_integral_exact(Decimal('100'))
4838        Decimal('100')
4839        >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4840        Decimal('100')
4841        >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4842        Decimal('102')
4843        >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4844        Decimal('-102')
4845        >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4846        Decimal('1.0E+6')
4847        >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4848        Decimal('7.89E+77')
4849        >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4850        Decimal('-Infinity')
4851        """
4852        return a.to_integral_exact(context=self)
4853
4854    def to_integral_value(self, a):
4855        """Rounds to an integer.
4856
4857        When the operand has a negative exponent, the result is the same
4858        as using the quantize() operation using the given operand as the
4859        left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4860        of the operand as the precision setting, except that no flags will
4861        be set.  The rounding mode is taken from the context.
4862
4863        >>> ExtendedContext.to_integral_value(Decimal('2.1'))
4864        Decimal('2')
4865        >>> ExtendedContext.to_integral_value(Decimal('100'))
4866        Decimal('100')
4867        >>> ExtendedContext.to_integral_value(Decimal('100.0'))
4868        Decimal('100')
4869        >>> ExtendedContext.to_integral_value(Decimal('101.5'))
4870        Decimal('102')
4871        >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
4872        Decimal('-102')
4873        >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
4874        Decimal('1.0E+6')
4875        >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
4876        Decimal('7.89E+77')
4877        >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
4878        Decimal('-Infinity')
4879        """
4880        return a.to_integral_value(context=self)
4881
4882    # the method name changed, but we provide also the old one, for compatibility
4883    to_integral = to_integral_value
4884
4885class _WorkRep(object):
4886    __slots__ = ('sign','int','exp')
4887    # sign: 0 or 1
4888    # int:  int or long
4889    # exp:  None, int, or string
4890
4891    def __init__(self, value=None):
4892        if value is None:
4893            self.sign = None
4894            self.int = 0
4895            self.exp = None
4896        elif isinstance(value, Decimal):
4897            self.sign = value._sign
4898            self.int = int(value._int)
4899            self.exp = value._exp
4900        else:
4901            # assert isinstance(value, tuple)
4902            self.sign = value[0]
4903            self.int = value[1]
4904            self.exp = value[2]
4905
4906    def __repr__(self):
4907        return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4908
4909    __str__ = __repr__
4910
4911
4912
4913def _normalize(op1, op2, prec = 0):
4914    """Normalizes op1, op2 to have the same exp and length of coefficient.
4915
4916    Done during addition.
4917    """
4918    if op1.exp < op2.exp:
4919        tmp = op2
4920        other = op1
4921    else:
4922        tmp = op1
4923        other = op2
4924
4925    # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4926    # Then adding 10**exp to tmp has the same effect (after rounding)
4927    # as adding any positive quantity smaller than 10**exp; similarly
4928    # for subtraction.  So if other is smaller than 10**exp we replace
4929    # it with 10**exp.  This avoids tmp.exp - other.exp getting too large.
4930    tmp_len = len(str(tmp.int))
4931    other_len = len(str(other.int))
4932    exp = tmp.exp + min(-1, tmp_len - prec - 2)
4933    if other_len + other.exp - 1 < exp:
4934        other.int = 1
4935        other.exp = exp
4936
4937    tmp.int *= 10 ** (tmp.exp - other.exp)
4938    tmp.exp = other.exp
4939    return op1, op2
4940
4941##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4942
4943# This function from Tim Peters was taken from here:
4944# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4945# The correction being in the function definition is for speed, and
4946# the whole function is not resolved with math.log because of avoiding
4947# the use of floats.
4948def _nbits(n, correction = {
4949        '0': 4, '1': 3, '2': 2, '3': 2,
4950        '4': 1, '5': 1, '6': 1, '7': 1,
4951        '8': 0, '9': 0, 'a': 0, 'b': 0,
4952        'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4953    """Number of bits in binary representation of the positive integer n,
4954    or 0 if n == 0.
4955    """
4956    if n < 0:
4957        raise ValueError("The argument to _nbits should be nonnegative.")
4958    hex_n = "%x" % n
4959    return 4*len(hex_n) - correction[hex_n[0]]
4960
4961def _sqrt_nearest(n, a):
4962    """Closest integer to the square root of the positive integer n.  a is
4963    an initial approximation to the square root.  Any positive integer
4964    will do for a, but the closer a is to the square root of n the
4965    faster convergence will be.
4966
4967    """
4968    if n <= 0 or a <= 0:
4969        raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4970
4971    b=0
4972    while a != b:
4973        b, a = a, a--n//a>>1
4974    return a
4975
4976def _rshift_nearest(x, shift):
4977    """Given an integer x and a nonnegative integer shift, return closest
4978    integer to x / 2**shift; use round-to-even in case of a tie.
4979
4980    """
4981    b, q = 1L << shift, x >> shift
4982    return q + (2*(x & (b-1)) + (q&1) > b)
4983
4984def _div_nearest(a, b):
4985    """Closest integer to a/b, a and b positive integers; rounds to even
4986    in the case of a tie.
4987
4988    """
4989    q, r = divmod(a, b)
4990    return q + (2*r + (q&1) > b)
4991
4992def _ilog(x, M, L = 8):
4993    """Integer approximation to M*log(x/M), with absolute error boundable
4994    in terms only of x/M.
4995
4996    Given positive integers x and M, return an integer approximation to
4997    M * log(x/M).  For L = 8 and 0.1 <= x/M <= 10 the difference
4998    between the approximation and the exact result is at most 22.  For
4999    L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15.  In
5000    both cases these are upper bounds on the error; it will usually be
5001    much smaller."""
5002
5003    # The basic algorithm is the following: let log1p be the function
5004    # log1p(x) = log(1+x).  Then log(x/M) = log1p((x-M)/M).  We use
5005    # the reduction
5006    #
5007    #    log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5008    #
5009    # repeatedly until the argument to log1p is small (< 2**-L in
5010    # absolute value).  For small y we can use the Taylor series
5011    # expansion
5012    #
5013    #    log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5014    #
5015    # truncating at T such that y**T is small enough.  The whole
5016    # computation is carried out in a form of fixed-point arithmetic,
5017    # with a real number z being represented by an integer
5018    # approximation to z*M.  To avoid loss of precision, the y below
5019    # is actually an integer approximation to 2**R*y*M, where R is the
5020    # number of reductions performed so far.
5021
5022    y = x-M
5023    # argument reduction; R = number of reductions performed
5024    R = 0
5025    while (R <= L and long(abs(y)) << L-R >= M or
5026           R > L and abs(y) >> R-L >= M):
5027        y = _div_nearest(long(M*y) << 1,
5028                         M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5029        R += 1
5030
5031    # Taylor series with T terms
5032    T = -int(-10*len(str(M))//(3*L))
5033    yshift = _rshift_nearest(y, R)
5034    w = _div_nearest(M, T)
5035    for k in xrange(T-1, 0, -1):
5036        w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5037
5038    return _div_nearest(w*y, M)
5039
5040def _dlog10(c, e, p):
5041    """Given integers c, e and p with c > 0, p >= 0, compute an integer
5042    approximation to 10**p * log10(c*10**e), with an absolute error of
5043    at most 1.  Assumes that c*10**e is not exactly 1."""
5044
5045    # increase precision by 2; compensate for this by dividing
5046    # final result by 100
5047    p += 2
5048
5049    # write c*10**e as d*10**f with either:
5050    #   f >= 0 and 1 <= d <= 10, or
5051    #   f <= 0 and 0.1 <= d <= 1.
5052    # Thus for c*10**e close to 1, f = 0
5053    l = len(str(c))
5054    f = e+l - (e+l >= 1)
5055
5056    if p > 0:
5057        M = 10**p
5058        k = e+p-f
5059        if k >= 0:
5060            c *= 10**k
5061        else:
5062            c = _div_nearest(c, 10**-k)
5063
5064        log_d = _ilog(c, M) # error < 5 + 22 = 27
5065        log_10 = _log10_digits(p) # error < 1
5066        log_d = _div_nearest(log_d*M, log_10)
5067        log_tenpower = f*M # exact
5068    else:
5069        log_d = 0  # error < 2.31
5070        log_tenpower = div_nearest(f, 10**-p) # error < 0.5
5071
5072    return _div_nearest(log_tenpower+log_d, 100)
5073
5074def _dlog(c, e, p):
5075    """Given integers c, e and p with c > 0, compute an integer
5076    approximation to 10**p * log(c*10**e), with an absolute error of
5077    at most 1.  Assumes that c*10**e is not exactly 1."""
5078
5079    # Increase precision by 2. The precision increase is compensated
5080    # for at the end with a division by 100.
5081    p += 2
5082
5083    # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5084    # or f <= 0 and 0.1 <= d <= 1.  Then we can compute 10**p * log(c*10**e)
5085    # as 10**p * log(d) + 10**p*f * log(10).
5086    l = len(str(c))
5087    f = e+l - (e+l >= 1)
5088
5089    # compute approximation to 10**p*log(d), with error < 27
5090    if p > 0:
5091        k = e+p-f
5092        if k >= 0:
5093            c *= 10**k
5094        else:
5095            c = _div_nearest(c, 10**-k)  # error of <= 0.5 in c
5096
5097        # _ilog magnifies existing error in c by a factor of at most 10
5098        log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5099    else:
5100        # p <= 0: just approximate the whole thing by 0; error < 2.31
5101        log_d = 0
5102
5103    # compute approximation to f*10**p*log(10), with error < 11.
5104    if f:
5105        extra = len(str(abs(f)))-1
5106        if p + extra >= 0:
5107            # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5108            # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5109            f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
5110        else:
5111            f_log_ten = 0
5112    else:
5113        f_log_ten = 0
5114
5115    # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
5116    return _div_nearest(f_log_ten + log_d, 100)
5117
5118class _Log10Memoize(object):
5119    """Class to compute, store, and allow retrieval of, digits of the
5120    constant log(10) = 2.302585....  This constant is needed by
5121    Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5122    def __init__(self):
5123        self.digits = "23025850929940456840179914546843642076011014886"
5124
5125    def getdigits(self, p):
5126        """Given an integer p >= 0, return floor(10**p)*log(10).
5127
5128        For example, self.getdigits(3) returns 2302.
5129        """
5130        # digits are stored as a string, for quick conversion to
5131        # integer in the case that we've already computed enough
5132        # digits; the stored digits should always be correct
5133        # (truncated, not rounded to nearest).
5134        if p < 0:
5135            raise ValueError("p should be nonnegative")
5136
5137        if p >= len(self.digits):
5138            # compute p+3, p+6, p+9, ... digits; continue until at
5139            # least one of the extra digits is nonzero
5140            extra = 3
5141            while True:
5142                # compute p+extra digits, correct to within 1ulp
5143                M = 10**(p+extra+2)
5144                digits = str(_div_nearest(_ilog(10*M, M), 100))
5145                if digits[-extra:] != '0'*extra:
5146                    break
5147                extra += 3
5148            # keep all reliable digits so far; remove trailing zeros
5149            # and next nonzero digit
5150            self.digits = digits.rstrip('0')[:-1]
5151        return int(self.digits[:p+1])
5152
5153_log10_digits = _Log10Memoize().getdigits
5154
5155def _iexp(x, M, L=8):
5156    """Given integers x and M, M > 0, such that x/M is small in absolute
5157    value, compute an integer approximation to M*exp(x/M).  For 0 <=
5158    x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5159    is usually much smaller)."""
5160
5161    # Algorithm: to compute exp(z) for a real number z, first divide z
5162    # by a suitable power R of 2 so that |z/2**R| < 2**-L.  Then
5163    # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5164    # series
5165    #
5166    #     expm1(x) = x + x**2/2! + x**3/3! + ...
5167    #
5168    # Now use the identity
5169    #
5170    #     expm1(2x) = expm1(x)*(expm1(x)+2)
5171    #
5172    # R times to compute the sequence expm1(z/2**R),
5173    # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5174
5175    # Find R such that x/2**R/M <= 2**-L
5176    R = _nbits((long(x)<<L)//M)
5177
5178    # Taylor series.  (2**L)**T > M
5179    T = -int(-10*len(str(M))//(3*L))
5180    y = _div_nearest(x, T)
5181    Mshift = long(M)<<R
5182    for i in xrange(T-1, 0, -1):
5183        y = _div_nearest(x*(Mshift + y), Mshift * i)
5184
5185    # Expansion
5186    for k in xrange(R-1, -1, -1):
5187        Mshift = long(M)<<(k+2)
5188        y = _div_nearest(y*(y+Mshift), Mshift)
5189
5190    return M+y
5191
5192def _dexp(c, e, p):
5193    """Compute an approximation to exp(c*10**e), with p decimal places of
5194    precision.
5195
5196    Returns integers d, f such that:
5197
5198      10**(p-1) <= d <= 10**p, and
5199      (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5200
5201    In other words, d*10**f is an approximation to exp(c*10**e) with p
5202    digits of precision, and with an error in d of at most 1.  This is
5203    almost, but not quite, the same as the error being < 1ulp: when d
5204    = 10**(p-1) the error could be up to 10 ulp."""
5205
5206    # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5207    p += 2
5208
5209    # compute log(10) with extra precision = adjusted exponent of c*10**e
5210    extra = max(0, e + len(str(c)) - 1)
5211    q = p + extra
5212
5213    # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
5214    # rounding down
5215    shift = e+q
5216    if shift >= 0:
5217        cshift = c*10**shift
5218    else:
5219        cshift = c//10**-shift
5220    quot, rem = divmod(cshift, _log10_digits(q))
5221
5222    # reduce remainder back to original precision
5223    rem = _div_nearest(rem, 10**extra)
5224
5225    # error in result of _iexp < 120;  error after division < 0.62
5226    return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5227
5228def _dpower(xc, xe, yc, ye, p):
5229    """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5230    y = yc*10**ye, compute x**y.  Returns a pair of integers (c, e) such that:
5231
5232      10**(p-1) <= c <= 10**p, and
5233      (c-1)*10**e < x**y < (c+1)*10**e
5234
5235    in other words, c*10**e is an approximation to x**y with p digits
5236    of precision, and with an error in c of at most 1.  (This is
5237    almost, but not quite, the same as the error being < 1ulp: when c
5238    == 10**(p-1) we can only guarantee error < 10ulp.)
5239
5240    We assume that: x is positive and not equal to 1, and y is nonzero.
5241    """
5242
5243    # Find b such that 10**(b-1) <= |y| <= 10**b
5244    b = len(str(abs(yc))) + ye
5245
5246    # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5247    lxc = _dlog(xc, xe, p+b+1)
5248
5249    # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5250    shift = ye-b
5251    if shift >= 0:
5252        pc = lxc*yc*10**shift
5253    else:
5254        pc = _div_nearest(lxc*yc, 10**-shift)
5255
5256    if pc == 0:
5257        # we prefer a result that isn't exactly 1; this makes it
5258        # easier to compute a correctly rounded result in __pow__
5259        if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5260            coeff, exp = 10**(p-1)+1, 1-p
5261        else:
5262            coeff, exp = 10**p-1, -p
5263    else:
5264        coeff, exp = _dexp(pc, -(p+1), p+1)
5265        coeff = _div_nearest(coeff, 10)
5266        exp += 1
5267
5268    return coeff, exp
5269
5270def _log10_lb(c, correction = {
5271        '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5272        '6': 23, '7': 16, '8': 10, '9': 5}):
5273    """Compute a lower bound for 100*log10(c) for a positive integer c."""
5274    if c <= 0:
5275        raise ValueError("The argument to _log10_lb should be nonnegative.")
5276    str_c = str(c)
5277    return 100*len(str_c) - correction[str_c[0]]
5278
5279##### Helper Functions ####################################################
5280
5281def _convert_other(other, raiseit=False):
5282    """Convert other to Decimal.
5283
5284    Verifies that it's ok to use in an implicit construction.
5285    """
5286    if isinstance(other, Decimal):
5287        return other
5288    if isinstance(other, (int, long)):
5289        return Decimal(other)
5290    if raiseit:
5291        raise TypeError("Unable to convert %s to Decimal" % other)
5292    return NotImplemented
5293
5294##### Setup Specific Contexts ############################################
5295
5296# The default context prototype used by Context()
5297# Is mutable, so that new contexts can have different default values
5298
5299DefaultContext = Context(
5300        prec=28, rounding=ROUND_HALF_EVEN,
5301        traps=[DivisionByZero, Overflow, InvalidOperation],
5302        flags=[],
5303        Emax=999999999,
5304        Emin=-999999999,
5305        capitals=1
5306)
5307
5308# Pre-made alternate contexts offered by the specification
5309# Don't change these; the user should be able to select these
5310# contexts and be able to reproduce results from other implementations
5311# of the spec.
5312
5313BasicContext = Context(
5314        prec=9, rounding=ROUND_HALF_UP,
5315        traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5316        flags=[],
5317)
5318
5319ExtendedContext = Context(
5320        prec=9, rounding=ROUND_HALF_EVEN,
5321        traps=[],
5322        flags=[],
5323)
5324
5325
5326##### crud for parsing strings #############################################
5327#
5328# Regular expression used for parsing numeric strings.  Additional
5329# comments:
5330#
5331# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5332# whitespace.  But note that the specification disallows whitespace in
5333# a numeric string.
5334#
5335# 2. For finite numbers (not infinities and NaNs) the body of the
5336# number between the optional sign and the optional exponent must have
5337# at least one decimal digit, possibly after the decimal point.  The
5338# lookahead expression '(?=\d|\.\d)' checks this.
5339#
5340# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5341# other meaning for \d than the numbers [0-9].
5342
5343import re
5344_parser = re.compile(r"""     # A numeric string consists of:
5345#    \s*
5346    (?P<sign>[-+])?           # an optional sign, followed by either...
5347    (
5348        (?=\d|\.\d)           # ...a number (with at least one digit)
5349        (?P<int>\d*)          # consisting of a (possibly empty) integer part
5350        (\.(?P<frac>\d*))?    # followed by an optional fractional part
5351        (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5352    |
5353        Inf(inity)?           # ...an infinity, or...
5354    |
5355        (?P<signal>s)?        # ...an (optionally signaling)
5356        NaN                   # NaN
5357        (?P<diag>\d*)         # with (possibly empty) diagnostic information.
5358    )
5359#    \s*
5360    \Z
5361""", re.VERBOSE | re.IGNORECASE).match
5362
5363_all_zeros = re.compile('0*$').match
5364_exact_half = re.compile('50*$').match
5365
5366##### PEP3101 support functions ##############################################
5367# The functions parse_format_specifier and format_align have little to do
5368# with the Decimal class, and could potentially be reused for other pure
5369# Python numeric classes that want to implement __format__
5370#
5371# A format specifier for Decimal looks like:
5372#
5373#   [[fill]align][sign][0][minimumwidth][.precision][type]
5374#
5375
5376_parse_format_specifier_regex = re.compile(r"""\A
5377(?:
5378   (?P<fill>.)?
5379   (?P<align>[<>=^])
5380)?
5381(?P<sign>[-+ ])?
5382(?P<zeropad>0)?
5383(?P<minimumwidth>(?!0)\d+)?
5384(?:\.(?P<precision>0|(?!0)\d+))?
5385(?P<type>[eEfFgG%])?
5386\Z
5387""", re.VERBOSE)
5388
5389del re
5390
5391def _parse_format_specifier(format_spec):
5392    """Parse and validate a format specifier.
5393
5394    Turns a standard numeric format specifier into a dict, with the
5395    following entries:
5396
5397      fill: fill character to pad field to minimum width
5398      align: alignment type, either '<', '>', '=' or '^'
5399      sign: either '+', '-' or ' '
5400      minimumwidth: nonnegative integer giving minimum width
5401      precision: nonnegative integer giving precision, or None
5402      type: one of the characters 'eEfFgG%', or None
5403      unicode: either True or False (always True for Python 3.x)
5404
5405    """
5406    m = _parse_format_specifier_regex.match(format_spec)
5407    if m is None:
5408        raise ValueError("Invalid format specifier: " + format_spec)
5409
5410    # get the dictionary
5411    format_dict = m.groupdict()
5412
5413    # defaults for fill and alignment
5414    fill = format_dict['fill']
5415    align = format_dict['align']
5416    if format_dict.pop('zeropad') is not None:
5417        # in the face of conflict, refuse the temptation to guess
5418        if fill is not None and fill != '0':
5419            raise ValueError("Fill character conflicts with '0'"
5420                             " in format specifier: " + format_spec)
5421        if align is not None and align != '=':
5422            raise ValueError("Alignment conflicts with '0' in "
5423                             "format specifier: " + format_spec)
5424        fill = '0'
5425        align = '='
5426    format_dict['fill'] = fill or ' '
5427    format_dict['align'] = align or '<'
5428
5429    if format_dict['sign'] is None:
5430        format_dict['sign'] = '-'
5431
5432    # turn minimumwidth and precision entries into integers.
5433    # minimumwidth defaults to 0; precision remains None if not given
5434    format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5435    if format_dict['precision'] is not None:
5436        format_dict['precision'] = int(format_dict['precision'])
5437
5438    # if format type is 'g' or 'G' then a precision of 0 makes little
5439    # sense; convert it to 1.  Same if format type is unspecified.
5440    if format_dict['precision'] == 0:
5441        if format_dict['type'] in 'gG' or format_dict['type'] is None:
5442            format_dict['precision'] = 1
5443
5444    # record whether return type should be str or unicode
5445    format_dict['unicode'] = isinstance(format_spec, unicode)
5446
5447    return format_dict
5448
5449def _format_align(body, spec_dict):
5450    """Given an unpadded, non-aligned numeric string, add padding and
5451    aligment to conform with the given format specifier dictionary (as
5452    output from parse_format_specifier).
5453
5454    It's assumed that if body is negative then it starts with '-'.
5455    Any leading sign ('-' or '+') is stripped from the body before
5456    applying the alignment and padding rules, and replaced in the
5457    appropriate position.
5458
5459    """
5460    # figure out the sign; we only examine the first character, so if
5461    # body has leading whitespace the results may be surprising.
5462    if len(body) > 0 and body[0] in '-+':
5463        sign = body[0]
5464        body = body[1:]
5465    else:
5466        sign = ''
5467
5468    if sign != '-':
5469        if spec_dict['sign'] in ' +':
5470            sign = spec_dict['sign']
5471        else:
5472            sign = ''
5473
5474    # how much extra space do we have to play with?
5475    minimumwidth = spec_dict['minimumwidth']
5476    fill = spec_dict['fill']
5477    padding = fill*(max(minimumwidth - (len(sign+body)), 0))
5478
5479    align = spec_dict['align']
5480    if align == '<':
5481        result = padding + sign + body
5482    elif align == '>':
5483        result = sign + body + padding
5484    elif align == '=':
5485        result = sign + padding + body
5486    else: #align == '^'
5487        half = len(padding)//2
5488        result = padding[:half] + sign + body + padding[half:]
5489
5490    # make sure that result is unicode if necessary
5491    if spec_dict['unicode']:
5492        result = unicode(result)
5493
5494    return result
5495
5496##### Useful Constants (internal use only) ################################
5497
5498# Reusable defaults
5499Inf = Decimal('Inf')
5500negInf = Decimal('-Inf')
5501NaN = Decimal('NaN')
5502Dec_0 = Decimal(0)
5503Dec_p1 = Decimal(1)
5504Dec_n1 = Decimal(-1)
5505
5506# Infsign[sign] is infinity w/ that sign
5507Infsign = (Inf, negInf)
5508
5509
5510
5511if __name__ == '__main__':
5512    import doctest, sys
5513    doctest.testmod(sys.modules[__name__])
5514