decimal.py revision a016debad07f11c3b85131b4205305d190ac9eca
17c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# Copyright (c) 2004 Python Software Foundation.
27c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# All rights reserved.
37c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# Written by Eric Price <eprice at tjhsst.edu>
57c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger#    and Facundo Batista <facundo at taniquetil.com.ar>
67c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger#    and Raymond Hettinger <python at rcn.com>
71f34eb17b501687c1251678bcffab9accd432591Fred Drake#    and Aahz <aahz at pobox.com>
87c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger#    and Tim Peters
97c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1027dbcf2162c61d5ba248c57c89ff4fa3d85a21c7Raymond Hettinger# This module is currently Py2.3 compatible and should be kept that way
1127dbcf2162c61d5ba248c57c89ff4fa3d85a21c7Raymond Hettinger# unless a major compelling advantage arises.  IOW, 2.3 compatibility is
1227dbcf2162c61d5ba248c57c89ff4fa3d85a21c7Raymond Hettinger# strongly preferred, but not guaranteed.
1327dbcf2162c61d5ba248c57c89ff4fa3d85a21c7Raymond Hettinger
1427dbcf2162c61d5ba248c57c89ff4fa3d85a21c7Raymond Hettinger# Also, this module should be kept in sync with the latest updates of
1527dbcf2162c61d5ba248c57c89ff4fa3d85a21c7Raymond Hettinger# the IBM specification as it evolves.  Those updates will be treated
1627dbcf2162c61d5ba248c57c89ff4fa3d85a21c7Raymond Hettinger# as bug fixes (deviation from the spec is a compatibility, usability
1727dbcf2162c61d5ba248c57c89ff4fa3d85a21c7Raymond Hettinger# bug) and will be backported.  At this point the spec is stabilizing
1827dbcf2162c61d5ba248c57c89ff4fa3d85a21c7Raymond Hettinger# and the updates are becoming fewer, smaller, and less significant.
197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger"""
217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerThis is a Py2.3 implementation of decimal floating point arithmetic based on
227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerthe General Decimal Arithmetic Specification:
237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    www2.hursley.ibm.com/decimal/decarith.html
257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
260ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettingerand IEEE standard 854-1987:
277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerDecimal floating point has finite precision with arbitrarily large bounds.
317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo BatistaThe purpose of this module is to support arithmetic using familiar
3359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista"schoolhouse" rules and to avoid some of the tricky representation
347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerissues associated with binary floating point.  The package is especially
357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingeruseful for financial applications or for contexts where users have
367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerexpectations that are at odds with binary floating point (for instance,
377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerin binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
38abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettingerof the expected Decimal('0.00') returned by decimal floating point).
397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerHere are some examples of using the decimal module:
417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> from decimal import *
43bd7f76dd04780304c397323ae994092ce759d5a2Raymond Hettinger>>> setcontext(ExtendedContext)
447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> Decimal(0)
45abe32371878dcaea31c835e10144fdaa2eca6492Raymond HettingerDecimal('0')
46abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger>>> Decimal('1')
47abe32371878dcaea31c835e10144fdaa2eca6492Raymond HettingerDecimal('1')
48abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger>>> Decimal('-.0123')
49abe32371878dcaea31c835e10144fdaa2eca6492Raymond HettingerDecimal('-0.0123')
507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> Decimal(123456)
51abe32371878dcaea31c835e10144fdaa2eca6492Raymond HettingerDecimal('123456')
52abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger>>> Decimal('123.45e12345678901234567890')
53abe32371878dcaea31c835e10144fdaa2eca6492Raymond HettingerDecimal('1.2345E+12345678901234567892')
54abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger>>> Decimal('1.33') + Decimal('1.27')
55abe32371878dcaea31c835e10144fdaa2eca6492Raymond HettingerDecimal('2.60')
56abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger>>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
57abe32371878dcaea31c835e10144fdaa2eca6492Raymond HettingerDecimal('-2.20')
587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> dig = Decimal(1)
597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print dig / Decimal(3)
607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger0.333333333
617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> getcontext().prec = 18
627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print dig / Decimal(3)
637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger0.333333333333333333
647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print dig.sqrt()
657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger1
667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print Decimal(3).sqrt()
677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger1.73205080756887729
687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print Decimal(3) ** 123
697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger4.85192780976896427E+58
707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> inf = Decimal(1) / Decimal(0)
717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print inf
727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerInfinity
737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> neginf = Decimal(-1) / Decimal(0)
747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print neginf
757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger-Infinity
767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print neginf + inf
777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerNaN
787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print neginf * inf
797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger-Infinity
807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print dig / 0
817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerInfinity
82bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger>>> getcontext().traps[DivisionByZero] = 1
837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print dig / 0
847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerTraceback (most recent call last):
857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger  ...
867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger  ...
877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger  ...
887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerDivisionByZero: x / 0
897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> c = Context()
90bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger>>> c.traps[InvalidOperation] = 0
915aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger>>> print c.flags[InvalidOperation]
927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger0
937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> c.divide(Decimal(0), Decimal(0))
94abe32371878dcaea31c835e10144fdaa2eca6492Raymond HettingerDecimal('NaN')
95bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger>>> c.traps[InvalidOperation] = 1
965aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger>>> print c.flags[InvalidOperation]
977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger1
985aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger>>> c.flags[InvalidOperation] = 0
995aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger>>> print c.flags[InvalidOperation]
1007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger0
1017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print c.divide(Decimal(0), Decimal(0))
1027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerTraceback (most recent call last):
1037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger  ...
1047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger  ...
1057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger  ...
1065aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond HettingerInvalidOperation: 0 / 0
1075aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger>>> print c.flags[InvalidOperation]
1087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger1
1095aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger>>> c.flags[InvalidOperation] = 0
110bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger>>> c.traps[InvalidOperation] = 0
1117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print c.divide(Decimal(0), Decimal(0))
1127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerNaN
1135aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger>>> print c.flags[InvalidOperation]
1147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger1
1157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>>
1167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger"""
1177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger__all__ = [
1197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    # Two major classes
1207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    'Decimal', 'Context',
1217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    # Contexts
1239ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger    'DefaultContext', 'BasicContext', 'ExtendedContext',
1247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    # Exceptions
126d87ac8f24da5dce860b559b69e6af59edd2c3eecRaymond Hettinger    'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
127d87ac8f24da5dce860b559b69e6af59edd2c3eecRaymond Hettinger    'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
1287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    # Constants for use in setting up contexts
1307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
131353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
1327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    # Functions for manipulating contexts
1348b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    'setcontext', 'getcontext', 'localcontext'
1357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger]
1367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
137a016debad07f11c3b85131b4205305d190ac9ecaRaymond Hettinger__version__ = '1.70'    # Highest version of the spec this complies with
138daeceb2de80047f25aedbf16bf40dc5d619e64ddRaymond Hettinger
139eb2608415ee4eb8aaea746f6a313937e264d0cdaRaymond Hettingerimport copy as _copy
140f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettingerimport math as _math
1412c8585b0afb6a39c215a71963e2fadea96f2c6aeRaymond Hettingerimport numbers as _numbers
1427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
143097a1903035f9ee2efb1953306123f183124125dRaymond Hettingertry:
144097a1903035f9ee2efb1953306123f183124125dRaymond Hettinger    from collections import namedtuple as _namedtuple
145097a1903035f9ee2efb1953306123f183124125dRaymond Hettinger    DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
146097a1903035f9ee2efb1953306123f183124125dRaymond Hettingerexcept ImportError:
147097a1903035f9ee2efb1953306123f183124125dRaymond Hettinger    DecimalTuple = lambda *args: args
148097a1903035f9ee2efb1953306123f183124125dRaymond Hettinger
14959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista# Rounding
1500ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_DOWN = 'ROUND_DOWN'
1510ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_HALF_UP = 'ROUND_HALF_UP'
1520ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
1530ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_CEILING = 'ROUND_CEILING'
1540ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_FLOOR = 'ROUND_FLOOR'
1550ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_UP = 'ROUND_UP'
1560ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
157353750c405c9099d0be69c6af1d17037b38c4ddfFacundo BatistaROUND_05UP = 'ROUND_05UP'
1587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
15959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista# Errors
1607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass DecimalException(ArithmeticError):
1625aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger    """Base exception class.
1637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Used exceptions derive from this.
1657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    If an exception derives from another exception besides this (such as
1667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
1677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    called if the others are present.  This isn't actually used for
1687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    anything, though.
1697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
170cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis    handle  -- Called when context._raise_error is called and the
171cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis               trap_enabler is set.  First argument is self, second is the
172cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis               context.  More arguments can be given, those being after
173cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis               the explanation in _raise_error (For example,
174cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis               context._raise_error(NewError, '(-x)!', self._sign) would
175cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis               call NewError().handle(context, self._sign).)
176cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
1777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    To define a new exception, it should be sufficient to have it derive
1787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    from DecimalException.
1797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
1807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, *args):
1817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        pass
1827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Clamped(DecimalException):
1857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Exponent of a 0 changed to fit bounds.
1867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals clamped if the exponent of a result has been
1887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    altered in order to fit the constraints of a specific concrete
18959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    representation.  This may occur when the exponent of a zero result would
19059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    be outside the bounds of a representation, or when a large normal
19159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    number would have an encoded exponent that cannot be represented.  In
1927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    this latter case, the exponent is reduced to fit and the corresponding
1937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    number of zero digits are appended to the coefficient ("fold-down").
1947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
1957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass InvalidOperation(DecimalException):
1977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """An invalid operation was performed.
1987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Various bad things cause this:
2007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Something creates a signaling NaN
2027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    -INF + INF
20359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    0 * (+-)INF
20459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    (+-)INF / (+-)INF
2057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    x % 0
2067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    (+-)INF % x
2077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    x._rescale( non-integer )
2087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    sqrt(-x) , x > 0
2097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    0 ** 0
2107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    x ** (non-integer)
2117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    x ** (+-)INF
2127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    An operand is invalid
213353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
214353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    The result of the operation after these is a quiet positive NaN,
215353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    except when the cause is a signaling NaN, in which case the result is
216353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    also a quiet NaN, but with the original sign, and an optional
217353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    diagnostic information.
2187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
2197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, *args):
2207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if args:
2210f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista            ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
2220f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista            return ans._fix_nan(context)
223c5de0969ca2a82c66efd30bb675f03c2324a3b27Mark Dickinson        return _NaN
2247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass ConversionSyntax(InvalidOperation):
2267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Trying to convert badly formed string.
2277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals invalid-operation if an string is being
2297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    converted to a number and it does not conform to the numeric string
23059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    syntax.  The result is [0,qNaN].
2317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
232cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis    def handle(self, context, *args):
233c5de0969ca2a82c66efd30bb675f03c2324a3b27Mark Dickinson        return _NaN
2347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass DivisionByZero(DecimalException, ZeroDivisionError):
2367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Division by 0.
2377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals division-by-zero if division of a finite number
2397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    by zero was attempted (during a divide-integer or divide operation, or a
2407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    power operation with negative right-hand operand), and the dividend was
2417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    not zero.
2427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The result of the operation is [sign,inf], where sign is the exclusive
2447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    or of the signs of the operands for divide, or is 1 for an odd power of
2457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    -0, for power.
2467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
247cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
248cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista    def handle(self, context, sign, *args):
249b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger        return _SignedInfinity[sign]
2507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass DivisionImpossible(InvalidOperation):
2527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Cannot perform the division adequately.
2537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals invalid-operation if the integer result of a
2557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    divide-integer or remainder operation had too many digits (would be
25659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    longer than precision).  The result is [0,qNaN].
2577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
258cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
2597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, *args):
260c5de0969ca2a82c66efd30bb675f03c2324a3b27Mark Dickinson        return _NaN
2617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass DivisionUndefined(InvalidOperation, ZeroDivisionError):
2637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Undefined result of division.
2647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals invalid-operation if division by zero was
2667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    attempted (during a divide-integer, divide, or remainder operation), and
26759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    the dividend is also zero.  The result is [0,qNaN].
2687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
269cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
270cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista    def handle(self, context, *args):
271c5de0969ca2a82c66efd30bb675f03c2324a3b27Mark Dickinson        return _NaN
2727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Inexact(DecimalException):
2747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Had to round, losing information.
2757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals inexact whenever the result of an operation is
2777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    not exact (that is, it needed to be rounded and any discarded digits
27859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    were non-zero), or if an overflow or underflow condition occurs.  The
2797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    result in all cases is unchanged.
2807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The inexact signal may be tested (or trapped) to determine if a given
2827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    operation (or sequence of operations) was inexact.
2837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
2847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass InvalidContext(InvalidOperation):
2867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Invalid context.  Unknown rounding, for example.
2877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals invalid-operation if an invalid context was
28959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    detected during an operation.  This can occur if contexts are not checked
2907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    on creation and either the precision exceeds the capability of the
2917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    underlying concrete representation or an unknown or unsupported rounding
29259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    was specified.  These aspects of the context need only be checked when
29359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    the values are required to be used.  The result is [0,qNaN].
2947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
295cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
2967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, *args):
297c5de0969ca2a82c66efd30bb675f03c2324a3b27Mark Dickinson        return _NaN
2987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Rounded(DecimalException):
3007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Number got rounded (not  necessarily changed during rounding).
3017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals rounded whenever the result of an operation is
3037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    rounded (that is, some zero or non-zero digits were discarded from the
30459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    coefficient), or if an overflow or underflow condition occurs.  The
3057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    result in all cases is unchanged.
3067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The rounded signal may be tested (or trapped) to determine if a given
3087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    operation (or sequence of operations) caused a loss of precision.
3097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
3107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Subnormal(DecimalException):
3127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Exponent < Emin before rounding.
3137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals subnormal whenever the result of a conversion or
3157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    operation is subnormal (that is, its adjusted exponent is less than
31659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    Emin, before any rounding).  The result in all cases is unchanged.
3177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The subnormal signal may be tested (or trapped) to determine if a given
3197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    or operation (or sequence of operations) yielded a subnormal result.
3207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
3217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Overflow(Inexact, Rounded):
3237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Numerical overflow.
3247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals overflow if the adjusted exponent of a result
3267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    (from a conversion or from an operation that is not an attempt to divide
3277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    by zero), after rounding, would be greater than the largest value that
3287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    can be handled by the implementation (the value Emax).
3297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The result depends on the rounding mode:
3317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    For round-half-up and round-half-even (and for round-half-down and
3337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    round-up, if implemented), the result of the operation is [sign,inf],
33459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    where sign is the sign of the intermediate result.  For round-down, the
3357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    result is the largest finite number that can be represented in the
33659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    current precision, with the sign of the intermediate result.  For
3377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    round-ceiling, the result is the same as for round-down if the sign of
33859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    the intermediate result is 1, or is [0,inf] otherwise.  For round-floor,
3397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    the result is the same as for round-down if the sign of the intermediate
34059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    result is 0, or is [1,inf] otherwise.  In all cases, Inexact and Rounded
3417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    will also be raised.
3420f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista    """
343cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
3447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, sign, *args):
3457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
346353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                ROUND_HALF_DOWN, ROUND_UP):
347b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger            return _SignedInfinity[sign]
3487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if sign == 0:
3497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if context.rounding == ROUND_CEILING:
350b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                return _SignedInfinity[sign]
35172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(sign, '9'*context.prec,
35272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                            context.Emax-context.prec+1)
3537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if sign == 1:
3547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if context.rounding == ROUND_FLOOR:
355b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                return _SignedInfinity[sign]
35672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(sign, '9'*context.prec,
35772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                             context.Emax-context.prec+1)
3587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Underflow(Inexact, Rounded, Subnormal):
3617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Numerical underflow with result rounded to 0.
3627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals underflow if a result is inexact and the
3647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    adjusted exponent of the result would be smaller (more negative) than
3657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    the smallest value that can be handled by the implementation (the value
36659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    Emin).  That is, the result is both inexact and subnormal.
3677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The result after an underflow will be a subnormal number rounded, if
36959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    necessary, so that its exponent is not less than Etiny.  This may result
3707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    in 0 with the sign of the intermediate result and an exponent of Etiny.
3717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    In all cases, Inexact, Rounded, and Subnormal will also be raised.
3737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
3747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3755aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger# List of public traps and flags
376fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
377cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis           Underflow, InvalidOperation, Subnormal]
3787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3795aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger# Map conditions (per the spec) to signals
3805aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger_condition_map = {ConversionSyntax:InvalidOperation,
3815aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger                  DivisionImpossible:InvalidOperation,
3825aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger                  DivisionUndefined:InvalidOperation,
3835aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger                  InvalidContext:InvalidOperation}
3847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
38559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Context Functions ##################################################
3867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
387ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger# The getcontext() and setcontext() function manage access to a thread-local
388ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger# current context.  Py2.4 offers direct support for thread locals.  If that
389ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger# is not available, use threading.currentThread() which is slower but will
3907e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger# work for older Pythons.  If threads are not part of the build, create a
391cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis# mock threading object with threading.local() returning the module namespace.
3927e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger
3937e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettingertry:
3947e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    import threading
3957e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettingerexcept ImportError:
3967e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    # Python was compiled without threads; create a mock object instead
3977e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    import sys
39859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    class MockThreading(object):
3997e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger        def local(self, sys=sys):
4007e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger            return sys.modules[__name__]
4017e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    threading = MockThreading()
4027e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    del sys, MockThreading
403ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
404ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettingertry:
405ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    threading.local
406ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
407ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettingerexcept AttributeError:
408ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
40959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # To fix reloading, force it to create a new context
41059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # Old contexts have different exceptions in their dicts, making problems.
411ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    if hasattr(threading.currentThread(), '__decimal_context__'):
412ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        del threading.currentThread().__decimal_context__
413ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
414ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    def setcontext(context):
415ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """Set this thread's context to context."""
416ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        if context in (DefaultContext, BasicContext, ExtendedContext):
4179fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger            context = context.copy()
41861992efc4bb413ae7a19752215eca5af09be6b6dRaymond Hettinger            context.clear_flags()
4197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        threading.currentThread().__decimal_context__ = context
420ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
421ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    def getcontext():
422ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """Returns this thread's context.
423ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
424ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        If this thread does not yet have a context, returns
425ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        a new context and sets this thread's context.
426ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        New contexts are copies of DefaultContext.
427ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """
428ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        try:
429ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            return threading.currentThread().__decimal_context__
430ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        except AttributeError:
431ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            context = Context()
432ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            threading.currentThread().__decimal_context__ = context
433ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            return context
434ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
435ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettingerelse:
436ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
437ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    local = threading.local()
4389fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger    if hasattr(local, '__decimal_context__'):
4399fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        del local.__decimal_context__
440ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
441ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    def getcontext(_local=local):
442ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """Returns this thread's context.
443ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
444ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        If this thread does not yet have a context, returns
445ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        a new context and sets this thread's context.
446ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        New contexts are copies of DefaultContext.
447ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """
448ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        try:
449ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            return _local.__decimal_context__
450ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        except AttributeError:
451ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            context = Context()
452ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            _local.__decimal_context__ = context
453ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            return context
454ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
455ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    def setcontext(context, _local=local):
456ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """Set this thread's context to context."""
457ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        if context in (DefaultContext, BasicContext, ExtendedContext):
4589fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger            context = context.copy()
45961992efc4bb413ae7a19752215eca5af09be6b6dRaymond Hettinger            context.clear_flags()
460ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        _local.__decimal_context__ = context
461ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
462cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis    del threading, local        # Don't contaminate the namespace
4637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4648b6999b4c5fab174090be263ba90f193bdede141Nick Coghlandef localcontext(ctx=None):
4658b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """Return a context manager for a copy of the supplied context
4668b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan
4678b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    Uses a copy of the current context if no context is specified
4688b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    The returned context manager creates a local decimal context
4698b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    in a with statement:
4708b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan        def sin(x):
4718b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan             with localcontext() as ctx:
4728b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 ctx.prec += 2
4738b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # Rest of sin calculation algorithm
4748b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # uses a precision 2 greater than normal
47559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista             return +s  # Convert result to normal precision
4768b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan
4778b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan         def sin(x):
4788b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan             with localcontext(ExtendedContext):
4798b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # Rest of sin calculation algorithm
4808b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # uses the Extended Context from the
4818b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # General Decimal Arithmetic Specification
48259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista             return +s  # Convert result to normal context
4838b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan
484ee340e501d2a59d70a91748ebd948787bfac8044Facundo Batista    >>> setcontext(DefaultContext)
4858b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> print getcontext().prec
4868b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    28
4878b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> with localcontext():
4888b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...     ctx = getcontext()
489495df4716fce4156c1eb110f9342297164eecbb6Raymond Hettinger    ...     ctx.prec += 2
4908b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...     print ctx.prec
4918b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...
4928b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    30
4938b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> with localcontext(ExtendedContext):
4948b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...     print getcontext().prec
4958b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...
4968b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    9
4978b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> print getcontext().prec
4988b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    28
4998b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """
500ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlan    if ctx is None: ctx = getcontext()
501ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlan    return _ContextManager(ctx)
5028b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan
5037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
50459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Decimal class #######################################################
5057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
5067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Decimal(object):
5077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Floating point class for decimal arithmetic."""
5087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
509636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    __slots__ = ('_exp','_int','_sign', '_is_special')
510636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    # Generally, the value of the Decimal instance is given by
511636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    #  (-1)**_sign * _int * 10**_exp
512636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    # Special values are signified by _is_special == True
5137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
514dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger    # We're immutable, so use __new__ not __init__
515636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    def __new__(cls, value="0", context=None):
5167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Create a decimal point instance.
5177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
5187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        >>> Decimal('3.14')              # string input
519abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('3.14')
52059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        >>> Decimal((0, (3, 1, 4), -2))  # tuple (sign, digit_tuple, exponent)
521abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('3.14')
5227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        >>> Decimal(314)                 # int or long
523abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('314')
5247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        >>> Decimal(Decimal(314))        # another decimal instance
525abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('314')
52659bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson        >>> Decimal('  3.14  \\n')        # leading and trailing whitespace okay
527abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('3.14')
5287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
5297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
53072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # Note that the coefficient, self._int, is actually stored as
53172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # a string rather than as a tuple of digits.  This speeds up
53272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # the "digits to integer" and "integer to digits" conversions
53372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # that are used in almost every arithmetic operation on
53472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # Decimals.  This is an internal detail: the as_tuple function
53572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # and the Decimal constructor still deal with tuples of
53672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # digits.
53772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista
538636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        self = object.__new__(cls)
539636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
5400d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        # From a string
5410d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        # REs insist on real strings, so we can too.
5420d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        if isinstance(value, basestring):
54359bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson            m = _parser(value.strip())
5440d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            if m is None:
5450d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                if context is None:
5460d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    context = getcontext()
5470d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                return context._raise_error(ConversionSyntax,
5480d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                                "Invalid literal for Decimal: %r" % value)
549636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
5500d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            if m.group('sign') == "-":
5510d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                self._sign = 1
5520d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            else:
5530d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                self._sign = 0
5540d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            intpart = m.group('int')
5550d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            if intpart is not None:
5560d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                # finite number
5570d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                fracpart = m.group('frac')
5580d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                exp = int(m.group('exp') or '0')
5590d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                if fracpart is not None:
5608e85ffa4b213be809109180142a107a1ac66f4d5Mark Dickinson                    self._int = str((intpart+fracpart).lstrip('0') or '0')
5610d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    self._exp = exp - len(fracpart)
5620d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                else:
5638e85ffa4b213be809109180142a107a1ac66f4d5Mark Dickinson                    self._int = str(intpart.lstrip('0') or '0')
5640d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    self._exp = exp
5650d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                self._is_special = False
5660d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            else:
5670d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                diag = m.group('diag')
5680d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                if diag is not None:
5690d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    # NaN
5708e85ffa4b213be809109180142a107a1ac66f4d5Mark Dickinson                    self._int = str(diag.lstrip('0'))
5710d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    if m.group('signal'):
5720d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                        self._exp = 'N'
5730d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    else:
5740d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                        self._exp = 'n'
5750d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                else:
5760d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    # infinity
5770d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    self._int = '0'
5780d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    self._exp = 'F'
5790d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                self._is_special = True
580636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return self
581636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
582636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        # From an integer
5837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if isinstance(value, (int,long)):
584636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if value >= 0:
585636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                self._sign = 0
586636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            else:
587636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                self._sign = 1
588636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self._exp = 0
58972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self._int = str(abs(value))
5900d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._is_special = False
5910d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            return self
5920d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista
5930d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        # From another decimal
5940d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        if isinstance(value, Decimal):
5950d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._exp  = value._exp
5960d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._sign = value._sign
5970d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._int  = value._int
5980d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._is_special  = value._is_special
5990d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            return self
6000d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista
6010d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        # From an internal working value
6020d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        if isinstance(value, _WorkRep):
6030d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._sign = value.sign
6040d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._int = str(value.int)
6050d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._exp = int(value.exp)
6060d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._is_special = False
607636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return self
608636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
609636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        # tuple/list conversion (possibly from as_tuple())
610636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if isinstance(value, (list,tuple)):
611636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if len(value) != 3:
6129b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                raise ValueError('Invalid tuple size in creation of Decimal '
6139b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                 'from list or tuple.  The list or tuple '
6149b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                 'should have exactly three elements.')
6159b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista            # process sign.  The isinstance test rejects floats
6169b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista            if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
6179b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                raise ValueError("Invalid sign.  The first value in the tuple "
6189b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                 "should be an integer; either 0 for a "
6199b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                 "positive number or 1 for a negative number.")
620636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self._sign = value[0]
6219b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista            if value[2] == 'F':
6229b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                # infinity: value[1] is ignored
62372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                self._int = '0'
624636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                self._exp = value[2]
625636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                self._is_special = True
626636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            else:
6279b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                # process and validate the digits in value[1]
6289b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                digits = []
6299b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                for digit in value[1]:
6309b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    if isinstance(digit, (int, long)) and 0 <= digit <= 9:
6319b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                        # skip leading zeros
6329b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                        if digits or digit != 0:
6339b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                            digits.append(digit)
6349b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    else:
6359b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                        raise ValueError("The second value in the tuple must "
6369b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                         "be composed of integers in the range "
6379b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                         "0 through 9.")
6389b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                if value[2] in ('n', 'N'):
6399b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    # NaN: digits form the diagnostic
64072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                    self._int = ''.join(map(str, digits))
6419b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    self._exp = value[2]
6429b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    self._is_special = True
6439b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                elif isinstance(value[2], (int, long)):
6449b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    # finite number: digits give the coefficient
64572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                    self._int = ''.join(map(str, digits or [0]))
6469b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    self._exp = value[2]
6479b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    self._is_special = False
6489b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                else:
6499b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    raise ValueError("The third value in the tuple must "
6509b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                     "be an integer, or one of the "
6519b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                     "strings 'F', 'n', 'N'.")
652636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return self
653636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
654636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if isinstance(value, float):
655636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            raise TypeError("Cannot convert float to Decimal.  " +
656636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                            "First convert the float to a string")
6577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
658636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        raise TypeError("Cannot convert %r to Decimal" % value)
6597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6606a961637a826ab6293293866a43d5924cf1a77e7Mark Dickinson    # @classmethod, but @decorator is not valid Python 2.3 syntax, so
6616a961637a826ab6293293866a43d5924cf1a77e7Mark Dickinson    # don't use it (see notes on Py2.3 compatibility at top of file)
662f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger    def from_float(cls, f):
663f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        """Converts a float to a decimal number, exactly.
664f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger
665f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
666f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        Since 0.1 is not exactly representable in binary floating point, the
667f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        value is stored as the nearest representable value which is
668f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        0x1.999999999999ap-4.  The exact equivalent of the value in decimal
669f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        is 0.1000000000000000055511151231257827021181583404541015625.
670f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger
671f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        >>> Decimal.from_float(0.1)
672f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        Decimal('0.1000000000000000055511151231257827021181583404541015625')
673f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        >>> Decimal.from_float(float('nan'))
674f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        Decimal('NaN')
675f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        >>> Decimal.from_float(float('inf'))
676f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        Decimal('Infinity')
677f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        >>> Decimal.from_float(-float('inf'))
678f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        Decimal('-Infinity')
679f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        >>> Decimal.from_float(-0.0)
680f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        Decimal('-0')
681f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger
682f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        """
683f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        if isinstance(f, (int, long)):        # handle integer inputs
684f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger            return cls(f)
685f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        if _math.isinf(f) or _math.isnan(f):  # raises TypeError if not a float
686f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger            return cls(repr(f))
6876a961637a826ab6293293866a43d5924cf1a77e7Mark Dickinson        if _math.copysign(1.0, f) == 1.0:
6886a961637a826ab6293293866a43d5924cf1a77e7Mark Dickinson            sign = 0
6896a961637a826ab6293293866a43d5924cf1a77e7Mark Dickinson        else:
6906a961637a826ab6293293866a43d5924cf1a77e7Mark Dickinson            sign = 1
691f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        n, d = abs(f).as_integer_ratio()
692f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        k = d.bit_length() - 1
693f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        result = _dec_from_triple(sign, str(n*5**k), -k)
6946a961637a826ab6293293866a43d5924cf1a77e7Mark Dickinson        if cls is Decimal:
6956a961637a826ab6293293866a43d5924cf1a77e7Mark Dickinson            return result
6966a961637a826ab6293293866a43d5924cf1a77e7Mark Dickinson        else:
6976a961637a826ab6293293866a43d5924cf1a77e7Mark Dickinson            return cls(result)
6986a961637a826ab6293293866a43d5924cf1a77e7Mark Dickinson    from_float = classmethod(from_float)
699f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger
7007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _isnan(self):
7017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns whether the number is not actually one.
7027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        0 if a number
7040f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista        1 if NaN
7057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        2 if sNaN
7067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
707636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
708636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            exp = self._exp
709636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if exp == 'n':
710636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return 1
711636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            elif exp == 'N':
712636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return 2
7137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return 0
7147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _isinfinity(self):
7167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns whether the number is infinite
7177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        0 if finite or not a number
7197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        1 if +INF
7207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        -1 if -INF
7217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
7227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._exp == 'F':
7237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if self._sign:
7247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return -1
7257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return 1
7267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return 0
7277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
728353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _check_nans(self, other=None, context=None):
7297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns whether the number is not actually one.
7307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self, other are sNaN, signal
7327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self, other are NaN return nan
7337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return 0
7347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Done before operations.
7367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
7377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
738636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        self_is_nan = self._isnan()
739636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if other is None:
740636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            other_is_nan = False
741636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        else:
742636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            other_is_nan = other._isnan()
743636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
744636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self_is_nan or other_is_nan:
745636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if context is None:
746636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                context = getcontext()
747636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
748636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self_is_nan == 2:
749636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return context._raise_error(InvalidOperation, 'sNaN',
7500f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista                                        self)
751636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if other_is_nan == 2:
752636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return context._raise_error(InvalidOperation, 'sNaN',
7530f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista                                        other)
754636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self_is_nan:
755353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self._fix_nan(context)
756636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
757353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return other._fix_nan(context)
7587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return 0
7597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7602fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    def _compare_check_nans(self, other, context):
7612fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        """Version of _check_nans used for the signaling comparisons
7622fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        compare_signal, __le__, __lt__, __ge__, __gt__.
7632fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson
7642fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        Signal InvalidOperation if either self or other is a (quiet
7652fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        or signaling) NaN.  Signaling NaNs take precedence over quiet
7662fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        NaNs.
7672fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson
7682fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        Return 0 if neither operand is a NaN.
7692fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson
7702fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        """
7712fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if context is None:
7722fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            context = getcontext()
7732fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson
7742fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if self._is_special or other._is_special:
7752fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            if self.is_snan():
7762fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                return context._raise_error(InvalidOperation,
7772fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                                            'comparison involving sNaN',
7782fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                                            self)
7792fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            elif other.is_snan():
7802fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                return context._raise_error(InvalidOperation,
7812fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                                            'comparison involving sNaN',
7822fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                                            other)
7832fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            elif self.is_qnan():
7842fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                return context._raise_error(InvalidOperation,
7852fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                                            'comparison involving NaN',
7862fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                                            self)
7872fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            elif other.is_qnan():
7882fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                return context._raise_error(InvalidOperation,
7892fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                                            'comparison involving NaN',
7902fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                                            other)
7912fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        return 0
7922fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson
7937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __nonzero__(self):
7941a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is nonzero; otherwise return False.
7957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7961a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        NaNs and infinities are considered nonzero.
7977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
79872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return self._is_special or self._int != '0'
7997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8002fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    def _cmp(self, other):
8012fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        """Compare the two non-NaN decimal instances self and other.
8027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8032fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        Returns -1 if self < other, 0 if self == other and 1
8042fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if self > other.  This routine is for internal use only."""
805636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
8062fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if self._is_special or other._is_special:
807e52c31450dfbe649b559b3fa96630d348b838c19Mark Dickinson            self_inf = self._isinfinity()
808e52c31450dfbe649b559b3fa96630d348b838c19Mark Dickinson            other_inf = other._isinfinity()
809e52c31450dfbe649b559b3fa96630d348b838c19Mark Dickinson            if self_inf == other_inf:
810e52c31450dfbe649b559b3fa96630d348b838c19Mark Dickinson                return 0
811e52c31450dfbe649b559b3fa96630d348b838c19Mark Dickinson            elif self_inf < other_inf:
812e52c31450dfbe649b559b3fa96630d348b838c19Mark Dickinson                return -1
813e52c31450dfbe649b559b3fa96630d348b838c19Mark Dickinson            else:
814e52c31450dfbe649b559b3fa96630d348b838c19Mark Dickinson                return 1
8157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
816e52c31450dfbe649b559b3fa96630d348b838c19Mark Dickinson        # check for zeros;  Decimal('0') == Decimal('-0')
817353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
818353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if not other:
819353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return 0
820353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
821353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return -((-1)**other._sign)
822353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other:
823353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return (-1)**self._sign
8247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
82559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # If different signs, neg one is less
8267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if other._sign < self._sign:
8277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return -1
8287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign < other._sign:
8297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return 1
8307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
831636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        self_adjusted = self.adjusted()
832636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other_adjusted = other.adjusted()
833353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_adjusted == other_adjusted:
83472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self_padded = self._int + '0'*(self._exp - other._exp)
83572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            other_padded = other._int + '0'*(other._exp - self._exp)
836e52c31450dfbe649b559b3fa96630d348b838c19Mark Dickinson            if self_padded == other_padded:
837e52c31450dfbe649b559b3fa96630d348b838c19Mark Dickinson                return 0
838e52c31450dfbe649b559b3fa96630d348b838c19Mark Dickinson            elif self_padded < other_padded:
839e52c31450dfbe649b559b3fa96630d348b838c19Mark Dickinson                return -(-1)**self._sign
840e52c31450dfbe649b559b3fa96630d348b838c19Mark Dickinson            else:
841e52c31450dfbe649b559b3fa96630d348b838c19Mark Dickinson                return (-1)**self._sign
842353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif self_adjusted > other_adjusted:
8437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return (-1)**self._sign
844353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else: # self_adjusted < other_adjusted
8457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return -((-1)**self._sign)
8467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8472fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    # Note: The Decimal standard doesn't cover rich comparisons for
8482fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    # Decimals.  In particular, the specification is silent on the
8492fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    # subject of what should happen for a comparison involving a NaN.
8502fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    # We take the following approach:
8512fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    #
8522fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    #   == comparisons involving a NaN always return False
8532fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    #   != comparisons involving a NaN always return True
8542fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    #   <, >, <= and >= comparisons involving a (quiet or signaling)
8552fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    #      NaN signal InvalidOperation, and return False if the
8563a94ee05f77d0200cfb7988d02f3fdf292932a94Mark Dickinson    #      InvalidOperation is not trapped.
8572fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    #
8582fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    # This behavior is designed to conform as closely as possible to
8592fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    # that specified by IEEE 754.
8602fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson
8610aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger    def __eq__(self, other):
8622fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        other = _convert_other(other)
8632fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if other is NotImplemented:
8642fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return other
8652fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if self.is_nan() or other.is_nan():
8662fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return False
8672fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        return self._cmp(other) == 0
8680aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger
8690aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger    def __ne__(self, other):
8702fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        other = _convert_other(other)
8712fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if other is NotImplemented:
8722fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return other
8732fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if self.is_nan() or other.is_nan():
8742fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return True
8752fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        return self._cmp(other) != 0
8762fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson
8772fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    def __lt__(self, other, context=None):
8782fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        other = _convert_other(other)
8792fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if other is NotImplemented:
8802fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return other
8812fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        ans = self._compare_check_nans(other, context)
8822fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if ans:
8832fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return False
8842fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        return self._cmp(other) < 0
8852fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson
8862fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    def __le__(self, other, context=None):
8872fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        other = _convert_other(other)
8882fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if other is NotImplemented:
8892fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return other
8902fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        ans = self._compare_check_nans(other, context)
8912fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if ans:
8922fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return False
8932fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        return self._cmp(other) <= 0
8942fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson
8952fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    def __gt__(self, other, context=None):
8962fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        other = _convert_other(other)
8972fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if other is NotImplemented:
8982fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return other
8992fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        ans = self._compare_check_nans(other, context)
9002fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if ans:
9012fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return False
9022fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        return self._cmp(other) > 0
9032fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson
9042fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    def __ge__(self, other, context=None):
9052fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        other = _convert_other(other)
9062fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if other is NotImplemented:
9072fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return other
9082fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        ans = self._compare_check_nans(other, context)
9092fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if ans:
9102fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return False
9112fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        return self._cmp(other) >= 0
9120aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger
9137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def compare(self, other, context=None):
9147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Compares one to another.
9157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        -1 => a < b
9177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        0  => a = b
9187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        1  => a > b
9197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        NaN => one is NaN
9207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Like __cmp__, but returns Decimal instances.
9217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
922353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
9237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
92459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # Compare(NaN, NaN) = NaN
925636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if (self._is_special or other and other._is_special):
926636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
927636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
928636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
9297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9302fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        return Decimal(self._cmp(other))
9317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __hash__(self):
9337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """x.__hash__() <==> hash(x)"""
9347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Decimal integers must hash the same as the ints
93552b25795c02442fc40f8932d05e5d728266339a4Facundo Batista        #
93652b25795c02442fc40f8932d05e5d728266339a4Facundo Batista        # The hash of a nonspecial noninteger Decimal must depend only
93752b25795c02442fc40f8932d05e5d728266339a4Facundo Batista        # on the value of that Decimal, and not on its representation.
938abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
939bea3f6f5c788eb4f0f7639913ff89654152864c0Raymond Hettinger        if self._is_special:
940bea3f6f5c788eb4f0f7639913ff89654152864c0Raymond Hettinger            if self._isnan():
941bea3f6f5c788eb4f0f7639913ff89654152864c0Raymond Hettinger                raise TypeError('Cannot hash a NaN value.')
942bea3f6f5c788eb4f0f7639913ff89654152864c0Raymond Hettinger            return hash(str(self))
9438c202440699cef19602acc24822366d0d7c32083Facundo Batista        if not self:
9448c202440699cef19602acc24822366d0d7c32083Facundo Batista            return 0
9458c202440699cef19602acc24822366d0d7c32083Facundo Batista        if self._isinteger():
9468c202440699cef19602acc24822366d0d7c32083Facundo Batista            op = _WorkRep(self.to_integral_value())
9478c202440699cef19602acc24822366d0d7c32083Facundo Batista            # to make computation feasible for Decimals with large
9488c202440699cef19602acc24822366d0d7c32083Facundo Batista            # exponent, we use the fact that hash(n) == hash(m) for
9498c202440699cef19602acc24822366d0d7c32083Facundo Batista            # any two nonzero integers n and m such that (i) n and m
9508c202440699cef19602acc24822366d0d7c32083Facundo Batista            # have the same sign, and (ii) n is congruent to m modulo
9518c202440699cef19602acc24822366d0d7c32083Facundo Batista            # 2**64-1.  So we can replace hash((-1)**s*c*10**e) with
9528c202440699cef19602acc24822366d0d7c32083Facundo Batista            # hash((-1)**s*c*pow(10, e, 2**64-1).
9538c202440699cef19602acc24822366d0d7c32083Facundo Batista            return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
95452b25795c02442fc40f8932d05e5d728266339a4Facundo Batista        # The value of a nonzero nonspecial Decimal instance is
95552b25795c02442fc40f8932d05e5d728266339a4Facundo Batista        # faithfully represented by the triple consisting of its sign,
95652b25795c02442fc40f8932d05e5d728266339a4Facundo Batista        # its adjusted exponent, and its coefficient with trailing
95752b25795c02442fc40f8932d05e5d728266339a4Facundo Batista        # zeros removed.
95852b25795c02442fc40f8932d05e5d728266339a4Facundo Batista        return hash((self._sign,
95952b25795c02442fc40f8932d05e5d728266339a4Facundo Batista                     self._exp+len(self._int),
96052b25795c02442fc40f8932d05e5d728266339a4Facundo Batista                     self._int.rstrip('0')))
9617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def as_tuple(self):
9637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Represents the number as a triple tuple.
9647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        To show the internals exactly as they are.
9667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
967097a1903035f9ee2efb1953306123f183124125dRaymond Hettinger        return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
9687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __repr__(self):
9707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Represents the number as an instance of Decimal."""
9717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Invariant:  eval(repr(d)) == d
972abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        return "Decimal('%s')" % str(self)
9737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
974353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def __str__(self, eng=False, context=None):
9757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return string representation of the number in scientific notation.
9767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Captures all of the information in the underlying representation.
9787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
9797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
98062edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        sign = ['', '-'][self._sign]
981e5a0a9609faea9afdc6f81f1f6dfa07b1437e3aeRaymond Hettinger        if self._is_special:
98262edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            if self._exp == 'F':
98362edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista                return sign + 'Infinity'
98462edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            elif self._exp == 'n':
98562edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista                return sign + 'NaN' + self._int
98662edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            else: # self._exp == 'N'
98762edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista                return sign + 'sNaN' + self._int
98862edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista
98962edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        # number of digits of self._int to left of decimal point
99062edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        leftdigits = self._exp + len(self._int)
99162edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista
99262edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        # dotplace is number of digits of self._int to the left of the
99362edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        # decimal point in the mantissa of the output string (that is,
99462edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        # after adjusting the exponent)
99562edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        if self._exp <= 0 and leftdigits > -6:
99662edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            # no exponent required
99762edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            dotplace = leftdigits
99862edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        elif not eng:
99962edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            # usual scientific notation: 1 digit on left of the point
10007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            dotplace = 1
100162edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        elif self._int == '0':
100262edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            # engineering notation, zero
100362edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            dotplace = (leftdigits + 1) % 3 - 1
10047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
100562edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            # engineering notation, nonzero
100662edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            dotplace = (leftdigits - 1) % 3 + 1
100762edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista
100862edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        if dotplace <= 0:
100962edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            intpart = '0'
101062edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            fracpart = '.' + '0'*(-dotplace) + self._int
101162edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        elif dotplace >= len(self._int):
101262edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            intpart = self._int+'0'*(dotplace-len(self._int))
101362edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            fracpart = ''
101462edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        else:
101562edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            intpart = self._int[:dotplace]
101662edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            fracpart = '.' + self._int[dotplace:]
101762edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        if leftdigits == dotplace:
101862edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            exp = ''
101962edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        else:
102062edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            if context is None:
102162edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista                context = getcontext()
102262edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
102362edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista
102462edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        return sign + intpart + fracpart + exp
10257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def to_eng_string(self, context=None):
10277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Convert to engineering-type string.
10287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Engineering notation has an exponent which is a multiple of 3, so there
10307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        are up to 3 digits left of the decimal place.
10317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Same rules for when in exponential and when as a value as in __str__.
10337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1034353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self.__str__(eng=True, context=context)
10357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __neg__(self, context=None):
10377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns a copy with the sign switched.
10387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Rounds, if it has reason.
10407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1041636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
1042636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
1043636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
1044636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
10457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
10477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            # -Decimal('0') is Decimal('0'), not Decimal('-0')
10480f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista            ans = self.copy_abs()
10497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
1050353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.copy_negate()
1051636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1052636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
1053636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
1054e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        return ans._fix(context)
10557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __pos__(self, context=None):
10577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns a copy, unless it is a sNaN.
10587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Rounds the number (if more then precision digits)
10607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1061636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
1062636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
1063636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
1064636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
10657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
10677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            # + (-0) = 0
10680f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista            ans = self.copy_abs()
1069353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
1070353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal(self)
10717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1072636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
1073636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
1074e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        return ans._fix(context)
10757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1076e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista    def __abs__(self, round=True, context=None):
10777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the absolute value of self.
10787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1079e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        If the keyword argument 'round' is false, do not round.  The
1080e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        expression self.__abs__(round=False) is equivalent to
1081e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        self.copy_abs().
10827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1083e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        if not round:
1084e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            return self.copy_abs()
1085e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista
1086636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
1087636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
1088636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
1089636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
10907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign:
10927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = self.__neg__(context=context)
10937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
10947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = self.__pos__(context=context)
10957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
10977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __add__(self, other, context=None):
10997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns self + other.
11007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        -INF + INF (or the reverse) cause InvalidOperation errors.
11027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1103636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1104267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1105267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
1106636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
11077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
11087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
11097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1110636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
1111636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
1112636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
1113636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
11147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1115636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity():
111659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                # If both INF, same sign => same as both, opposite => error.
1117636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if self._sign != other._sign and other._isinfinity():
1118636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    return context._raise_error(InvalidOperation, '-INF + INF')
1119636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Decimal(self)
1120636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if other._isinfinity():
112159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                return Decimal(other)  # Can't both be infinity here
11227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exp = min(self._exp, other._exp)
11247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        negativezero = 0
11257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context.rounding == ROUND_FLOOR and self._sign != other._sign:
112659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If the answer is 0, the sign should be negative, in this case.
11277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            negativezero = 1
11287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self and not other:
11307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            sign = min(self._sign, other._sign)
11317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if negativezero:
11327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                sign = 1
113372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(sign, '0', exp)
1134e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            ans = ans._fix(context)
1135353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
11367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
113799b5548298ffc2ae5f03bd9ef873ce45a9844f0eFacundo Batista            exp = max(exp, other._exp - context.prec-1)
1138353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = other._rescale(exp, context.rounding)
1139e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            ans = ans._fix(context)
11407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
11417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not other:
114299b5548298ffc2ae5f03bd9ef873ce45a9844f0eFacundo Batista            exp = max(exp, self._exp - context.prec-1)
1143353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._rescale(exp, context.rounding)
1144e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            ans = ans._fix(context)
11457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
11467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        op1 = _WorkRep(self)
11487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        op2 = _WorkRep(other)
1149e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        op1, op2 = _normalize(op1, op2, context.prec)
11507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        result = _WorkRep()
11527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if op1.sign != op2.sign:
11537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            # Equal and opposite
115417931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            if op1.int == op2.int:
115572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(negativezero, '0', exp)
1156e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista                ans = ans._fix(context)
1157353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return ans
115817931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            if op1.int < op2.int:
11597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                op1, op2 = op2, op1
116059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                # OK, now abs(op1) > abs(op2)
116117931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            if op1.sign == 1:
116217931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger                result.sign = 1
11637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                op1.sign, op2.sign = op2.sign, op1.sign
11647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            else:
116517931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger                result.sign = 0
116659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                # So we know the sign, and op1 > 0.
116717931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        elif op1.sign == 1:
11687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            result.sign = 1
116917931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            op1.sign, op2.sign = (0, 0)
117017931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        else:
117117931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            result.sign = 0
117259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # Now, op1 > abs(op2) > 0
11737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
117417931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        if op2.sign == 0:
1175636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            result.int = op1.int + op2.int
11767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
1177636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            result.int = op1.int - op2.int
11787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        result.exp = op1.exp
11807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        ans = Decimal(result)
1181e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        ans = ans._fix(context)
11827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
11837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __radd__ = __add__
11857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __sub__(self, other, context=None):
1187353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return self - other"""
1188636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1189267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1190267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
11917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1192636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
1193636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context=context)
1194636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
1195636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
11967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1197353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self - other is computed as self + other.copy_negate()
1198353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self.__add__(other.copy_negate(), context=context)
11997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rsub__(self, other, context=None):
1201353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return other - self"""
1202636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1203267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1204267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
12057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1206353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return other.__sub__(self, context=context)
12077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __mul__(self, other, context=None):
12097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return self * other.
12107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        (+-) INF * 0 (or its reverse) raise InvalidOperation.
12127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1213636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1214267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1215267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
1216636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
12177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
12187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
12197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1220d87ac8f24da5dce860b559b69e6af59edd2c3eecRaymond Hettinger        resultsign = self._sign ^ other._sign
12217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1222636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
1223636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
1224636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
1225636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
1226636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1227636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity():
1228636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if not other:
1229636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    return context._raise_error(InvalidOperation, '(+-)INF * 0')
1230b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                return _SignedInfinity[resultsign]
1231636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1232636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if other._isinfinity():
1233636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if not self:
1234636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    return context._raise_error(InvalidOperation, '0 * (+-)INF')
1235b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                return _SignedInfinity[resultsign]
12367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        resultexp = self._exp + other._exp
12387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Special case for multiplying by zero
12407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self or not other:
124172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(resultsign, '0', resultexp)
1242e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            # Fixing in case the exponent is out of bounds
1243e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            ans = ans._fix(context)
12447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
12457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Special case for multiplying by power of 10
124772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        if self._int == '1':
124872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(resultsign, other._int, resultexp)
1249e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            ans = ans._fix(context)
12507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
125172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        if other._int == '1':
125272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(resultsign, self._int, resultexp)
1253e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            ans = ans._fix(context)
12547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
12557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1256636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        op1 = _WorkRep(self)
1257636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        op2 = _WorkRep(other)
1258636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
125972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
1260e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        ans = ans._fix(context)
12617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
12637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __rmul__ = __mul__
12647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12658aca9d032e7813da9a23fd0771c008aff5a5e62fMark Dickinson    def __truediv__(self, other, context=None):
12667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return self / other."""
1267636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1268267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1269cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return NotImplemented
1270636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
12717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
12727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
12737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1274636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        sign = self._sign ^ other._sign
1275636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1276636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
1277636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
1278636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
12797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return ans
12807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1281636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity() and other._isinfinity():
12827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
12837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if self._isinfinity():
1285b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                return _SignedInfinity[sign]
1286636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1287636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if other._isinfinity():
1288636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                context._raise_error(Clamped, 'Division by infinity')
128972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(sign, '0', context.Etiny())
1290636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1291636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        # Special cases for zeroes
1292636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if not other:
1293cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if not self:
1294cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(DivisionUndefined, '0 / 0')
1295636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return context._raise_error(DivisionByZero, 'x / 0', sign)
12967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1297cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if not self:
1298cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            exp = self._exp - other._exp
1299cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            coeff = 0
1300cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        else:
1301cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            # OK, so neither = 0, INF or NaN
1302cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            shift = len(other._int) - len(self._int) + context.prec + 1
1303cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            exp = self._exp - other._exp - shift
1304cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            op1 = _WorkRep(self)
1305cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            op2 = _WorkRep(other)
1306cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if shift >= 0:
1307cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1308cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1309cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1310cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if remainder:
1311cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                # result is not exact; adjust to ensure correct rounding
1312cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                if coeff % 5 == 0:
1313cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                    coeff += 1
1314cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1315cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                # result is exact; get as close to ideal exponent as possible
1316cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                ideal_exp = self._exp - other._exp
1317cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                while exp < ideal_exp and coeff % 10 == 0:
1318cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                    coeff //= 10
1319cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                    exp += 1
13207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
132172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        ans = _dec_from_triple(sign, str(coeff), exp)
1322cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return ans._fix(context)
13237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1324cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista    def _divide(self, other, context):
1325cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        """Return (self // other, self % other), to context.prec precision.
13267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1327cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        Assumes that neither self nor other is a NaN, that self is not
1328cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        infinite and that other is nonzero.
1329cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        """
1330cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        sign = self._sign ^ other._sign
1331cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if other._isinfinity():
1332cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            ideal_exp = self._exp
1333cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        else:
1334cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            ideal_exp = min(self._exp, other._exp)
13357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1336cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        expdiff = self.adjusted() - other.adjusted()
1337cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if not self or other._isinfinity() or expdiff <= -2:
133872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return (_dec_from_triple(sign, '0', 0),
1339cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                    self._rescale(ideal_exp, context.rounding))
1340cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if expdiff <= context.prec:
1341cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            op1 = _WorkRep(self)
1342cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            op2 = _WorkRep(other)
1343cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if op1.exp >= op2.exp:
1344cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                op1.int *= 10**(op1.exp - op2.exp)
1345cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1346cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                op2.int *= 10**(op2.exp - op1.exp)
1347cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            q, r = divmod(op1.int, op2.int)
1348cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if q < 10**context.prec:
134972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return (_dec_from_triple(sign, str(q), 0),
135072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                        _dec_from_triple(self._sign, str(r), ideal_exp))
13517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1352cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        # Here the quotient is too large to be representable
1353cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        ans = context._raise_error(DivisionImpossible,
1354cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                                   'quotient too large in //, % or divmod')
1355cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return ans, ans
13567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13578aca9d032e7813da9a23fd0771c008aff5a5e62fMark Dickinson    def __rtruediv__(self, other, context=None):
13588aca9d032e7813da9a23fd0771c008aff5a5e62fMark Dickinson        """Swaps self/other and returns __truediv__."""
1359636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1360267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1361267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
13628aca9d032e7813da9a23fd0771c008aff5a5e62fMark Dickinson        return other.__truediv__(self, context=context)
13638aca9d032e7813da9a23fd0771c008aff5a5e62fMark Dickinson
13648aca9d032e7813da9a23fd0771c008aff5a5e62fMark Dickinson    __div__ = __truediv__
13658aca9d032e7813da9a23fd0771c008aff5a5e62fMark Dickinson    __rdiv__ = __rtruediv__
13667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __divmod__(self, other, context=None):
13687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1369cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        Return (self // other, self % other)
13707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1371cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        other = _convert_other(other)
1372cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if other is NotImplemented:
1373cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return other
1374cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1375cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if context is None:
1376cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            context = getcontext()
1377cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1378cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        ans = self._check_nans(other, context)
1379cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if ans:
1380cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return (ans, ans)
1381cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1382cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        sign = self._sign ^ other._sign
1383cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if self._isinfinity():
1384cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if other._isinfinity():
1385cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1386cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return ans, ans
1387cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1388b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                return (_SignedInfinity[sign],
1389cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                        context._raise_error(InvalidOperation, 'INF % x'))
1390cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1391cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if not other:
1392cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if not self:
1393cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1394cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return ans, ans
1395cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1396cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return (context._raise_error(DivisionByZero, 'x // 0', sign),
1397cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                        context._raise_error(InvalidOperation, 'x % 0'))
1398cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1399cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        quotient, remainder = self._divide(other, context)
1400e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        remainder = remainder._fix(context)
1401cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return quotient, remainder
14027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rdivmod__(self, other, context=None):
14047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Swaps self/other and returns __divmod__."""
1405636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1406267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1407267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
14087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return other.__divmod__(self, context=context)
14097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __mod__(self, other, context=None):
14117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
14127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self % other
14137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1414636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1415267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1416267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
14177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1418cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if context is None:
1419cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            context = getcontext()
14207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1421cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        ans = self._check_nans(other, context)
1422cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if ans:
1423cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return ans
14247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1425cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if self._isinfinity():
1426cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return context._raise_error(InvalidOperation, 'INF % x')
1427cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        elif not other:
1428cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if self:
1429cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(InvalidOperation, 'x % 0')
1430cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1431cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(DivisionUndefined, '0 % 0')
1432cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1433cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        remainder = self._divide(other, context)[1]
1434e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        remainder = remainder._fix(context)
1435cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return remainder
14367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rmod__(self, other, context=None):
14387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Swaps self/other and returns __mod__."""
1439636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1440267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1441267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
14427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return other.__mod__(self, context=context)
14437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def remainder_near(self, other, context=None):
14457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
14467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Remainder nearest to 0-  abs(remainder-near) <= other/2
14477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1448636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
1449636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
14507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1451353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
14527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1453353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
1454353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
1455353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
14567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1457353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self == +/-infinity -> InvalidOperation
1458353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
1459353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1460353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'remainder_near(infinity, x)')
14617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1462353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # other == 0 -> either InvalidOperation or DivisionUndefined
1463353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other:
1464353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self:
1465353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation,
1466353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                            'remainder_near(x, 0)')
1467353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1468353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(DivisionUndefined,
1469353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                            'remainder_near(0, 0)')
14707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1471353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # other = +/-infinity -> remainder = self
1472353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._isinfinity():
1473353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal(self)
1474353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
14757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1476353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self = 0 -> remainder = self, with ideal exponent
1477353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ideal_exponent = min(self._exp, other._exp)
1478353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
147972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(self._sign, '0', ideal_exponent)
1480353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
14817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1482353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # catch most cases of large or small quotient
1483353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        expdiff = self.adjusted() - other.adjusted()
1484353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if expdiff >= context.prec + 1:
1485353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # expdiff >= prec+1 => abs(self/other) > 10**prec
1486cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return context._raise_error(DivisionImpossible)
1487353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if expdiff <= -2:
1488353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # expdiff <= -2 => abs(self/other) < 0.1
1489353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._rescale(ideal_exponent, context.rounding)
1490353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
14917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1492353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # adjust both arguments to have the same exponent, then divide
1493353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op1 = _WorkRep(self)
1494353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op2 = _WorkRep(other)
1495353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if op1.exp >= op2.exp:
1496353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            op1.int *= 10**(op1.exp - op2.exp)
14977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
1498353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            op2.int *= 10**(op2.exp - op1.exp)
1499353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        q, r = divmod(op1.int, op2.int)
1500353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # remainder is r*10**ideal_exponent; other is +/-op2.int *
1501353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 10**ideal_exponent.   Apply correction to ensure that
1502353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # abs(remainder) <= abs(other)/2
1503353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if 2*r + (q&1) > op2.int:
1504353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            r -= op2.int
1505353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            q += 1
1506353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1507353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if q >= 10**context.prec:
1508cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return context._raise_error(DivisionImpossible)
1509353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1510353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # result has same sign as self unless r is negative
1511353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        sign = self._sign
1512353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if r < 0:
1513353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sign = 1-sign
1514353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            r = -r
15157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
151672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        ans = _dec_from_triple(sign, str(r), ideal_exponent)
1517353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans._fix(context)
15187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
15197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __floordiv__(self, other, context=None):
15207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """self // other"""
1521cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        other = _convert_other(other)
1522cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if other is NotImplemented:
1523cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return other
1524cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1525cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if context is None:
1526cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            context = getcontext()
1527cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1528cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        ans = self._check_nans(other, context)
1529cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if ans:
1530cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return ans
1531cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1532cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if self._isinfinity():
1533cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if other._isinfinity():
1534cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(InvalidOperation, 'INF // INF')
1535cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1536b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                return _SignedInfinity[self._sign ^ other._sign]
1537cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1538cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if not other:
1539cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if self:
1540cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(DivisionByZero, 'x // 0',
1541cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                                            self._sign ^ other._sign)
1542cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1543cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(DivisionUndefined, '0 // 0')
1544cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1545cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return self._divide(other, context)[0]
15467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
15477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rfloordiv__(self, other, context=None):
15487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Swaps self/other and returns __floordiv__."""
1549636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1550267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1551267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
15527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return other.__floordiv__(self, context=context)
15537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
15547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __float__(self):
15557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Float representation."""
15567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return float(str(self))
15577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
15587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __int__(self):
155946b0802ccd9a9c47b27a285526fbb2a8bee5b8cbBrett Cannon        """Converts self to an int, truncating if necessary."""
1560636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
1561636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isnan():
1562636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                context = getcontext()
1563636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return context._raise_error(InvalidContext)
1564636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            elif self._isinfinity():
15658aca9d032e7813da9a23fd0771c008aff5a5e62fMark Dickinson                raise OverflowError("Cannot convert infinity to int")
1566353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        s = (-1)**self._sign
15677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._exp >= 0:
156872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return s*int(self._int)*10**self._exp
1569605ed0248375bbf87bbd1d80afc7c6918fd3ce2bRaymond Hettinger        else:
157072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return s*int(self._int[:self._exp] or '0')
15717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
15725a05364049a7b0c3eeee94fb7b77e6b41036b3aeRaymond Hettinger    __trunc__ = __int__
15735a05364049a7b0c3eeee94fb7b77e6b41036b3aeRaymond Hettinger
1574116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger    def real(self):
1575116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger        return self
157665808ff0c08e60572cf81ebe5dc24794a706f390Mark Dickinson    real = property(real)
1577116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger
1578116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger    def imag(self):
1579116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger        return Decimal(0)
158065808ff0c08e60572cf81ebe5dc24794a706f390Mark Dickinson    imag = property(imag)
1581116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger
1582116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger    def conjugate(self):
1583116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger        return self
1584116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger
1585116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger    def __complex__(self):
1586116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger        return complex(float(self))
1587116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger
15887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __long__(self):
15897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Converts to a long.
15907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
15917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Equivalent to long(int(self))
15927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
15937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return long(self.__int__())
15947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1595353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _fix_nan(self, context):
1596353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Decapitate the payload of a NaN to fit the context"""
1597353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        payload = self._int
1598353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1599353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # maximum length of payload is precision if _clamp=0,
1600353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # precision-1 if _clamp=1.
1601353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        max_payload_len = context.prec - context._clamp
1602353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if len(payload) > max_payload_len:
160372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            payload = payload[len(payload)-max_payload_len:].lstrip('0')
160472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(self._sign, payload, self._exp, True)
16056c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        return Decimal(self)
1606353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1607dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger    def _fix(self, context):
16087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Round if it is necessary to keep self within prec precision.
16097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
16107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Rounds and fixes the exponent.  Does not raise on a sNaN.
16117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
16127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Arguments:
16137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self - Decimal instance
16147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        context - context used.
16157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1616636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1617353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
1618353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self._isnan():
1619353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # decapitate payload if necessary
1620353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self._fix_nan(context)
1621353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1622353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # self is +/-Infinity; return unaltered
16236c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                return Decimal(self)
16247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1625353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if self is zero then exponent should be between Etiny and
1626353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1627353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Etiny = context.Etiny()
1628353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Etop = context.Etop()
16297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
1630353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            exp_max = [context.Emax, Etop][context._clamp]
1631353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            new_exp = min(max(self._exp, Etiny), exp_max)
1632353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if new_exp != self._exp:
1633353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Clamped)
163472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(self._sign, '0', new_exp)
16357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            else:
16366c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                return Decimal(self)
16377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1638353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp_min is the smallest allowable exponent of the result,
1639353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # equal to max(self.adjusted()-context.prec+1, Etiny)
1640353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exp_min = len(self._int) + self._exp - context.prec
1641353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if exp_min > Etop:
1642353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # overflow: exp_min > Etop iff self.adjusted() > Emax
1643353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
1644353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Rounded)
1645353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(Overflow, 'above Emax', self._sign)
1646353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_is_subnormal = exp_min < Etiny
1647353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_is_subnormal:
1648353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Subnormal)
1649353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            exp_min = Etiny
16507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1651353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # round if self has too many digits
1652353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp < exp_min:
16537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context._raise_error(Rounded)
16542ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            digits = len(self._int) + self._exp - exp_min
16552ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            if digits < 0:
16562ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista                self = _dec_from_triple(self._sign, '1', exp_min-1)
16572ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista                digits = 0
16582ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            this_function = getattr(self, self._pick_rounding_function[context.rounding])
16592ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            changed = this_function(digits)
16602ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            coeff = self._int[:digits] or '0'
16612ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            if changed == 1:
16622ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista                coeff = str(int(coeff)+1)
16632ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            ans = _dec_from_triple(self._sign, coeff, exp_min)
16642ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista
16652ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            if changed:
1666353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Inexact)
1667353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_is_subnormal:
1668353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    context._raise_error(Underflow)
1669353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if not ans:
1670353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        # raise Clamped on underflow to 0
1671353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        context._raise_error(Clamped)
1672353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                elif len(ans._int) == context.prec+1:
1673353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    # we get here only if rescaling rounds the
1674353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    # cofficient up to exactly 10**context.prec
1675353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if ans._exp < Etop:
167672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                        ans = _dec_from_triple(ans._sign,
167772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                                   ans._int[:-1], ans._exp+1)
1678353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    else:
1679353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        # Inexact and Rounded have already been raised
1680353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        ans = context._raise_error(Overflow, 'above Emax',
1681353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                                   self._sign)
16827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
16837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1684353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # fold down if _clamp == 1 and self has too few digits
1685353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context._clamp == 1 and self._exp > Etop:
1686353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Clamped)
168772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self_padded = self._int + '0'*(self._exp - Etop)
168872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(self._sign, self_padded, Etop)
16897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1690353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # here self was representable to begin with; return unchanged
16916c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        return Decimal(self)
16927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
16937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    _pick_rounding_function = {}
16947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1695353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # for each of the rounding functions below:
1696353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #   self is a finite, nonzero Decimal
1697353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #   prec is an integer satisfying 0 <= prec < len(self._int)
16982ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    #
16992ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    # each function returns either -1, 0, or 1, as follows:
17002ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    #   1 indicates that self should be rounded up (away from zero)
17012ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    #   0 indicates that self should be truncated, and that all the
17022ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    #     digits to be truncated are zeros (so the value is unchanged)
17032ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    #  -1 indicates that there are nonzero digits to be truncated
17047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1705353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_down(self, prec):
1706353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Also known as round-towards-0, truncate."""
17072ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        if _all_zeros(self._int, prec):
17082ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return 0
17092ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        else:
17102ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -1
17117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1712353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_up(self, prec):
1713353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds away from 0."""
17142ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        return -self._round_down(prec)
17157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1716353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_half_up(self, prec):
1717353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds 5 up (away from 0)"""
171872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        if self._int[prec] in '56789':
17192ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return 1
17202ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        elif _all_zeros(self._int, prec):
17212ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return 0
1722353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
17232ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -1
17247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1725353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_half_down(self, prec):
17267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Round 5 down"""
17272ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        if _exact_half(self._int, prec):
17282ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -1
17292ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        else:
17302ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return self._round_half_up(prec)
17317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1732353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_half_even(self, prec):
1733353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Round 5 to even, rest to nearest."""
17342ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        if _exact_half(self._int, prec) and \
17352ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista                (prec == 0 or self._int[prec-1] in '02468'):
17362ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -1
1737353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
17382ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return self._round_half_up(prec)
17397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1740353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_ceiling(self, prec):
17417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Rounds up (not away from 0 if negative.)"""
17427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign:
1743353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_down(prec)
17447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
17452ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -self._round_down(prec)
17467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1747353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_floor(self, prec):
17487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Rounds down (not towards 0 if negative)"""
17497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self._sign:
1750353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_down(prec)
17517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
17522ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -self._round_down(prec)
17537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1754353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_05up(self, prec):
1755353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Round down unless digit prec-1 is 0 or 5."""
17562ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        if prec and self._int[prec-1] not in '05':
1757353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_down(prec)
17582ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        else:
17592ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -self._round_down(prec)
1760353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1761353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def fma(self, other, third, context=None):
1762353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Fused multiply-add.
17637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1764353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Returns self*other+third with no rounding of the intermediate
1765353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        product self*other.
1766353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1767353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self and other are multiplied together, with no rounding of
1768353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        the result.  The third operand is then added to the result,
1769353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        and a single final rounding is performed.
17707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1771353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1772353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
17737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
177458f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista        # compute product; raise InvalidOperation if either operand is
177558f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista        # a signaling NaN or if the product is zero times infinity.
177658f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista        if self._is_special or other._is_special:
177758f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            if context is None:
177858f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                context = getcontext()
177958f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            if self._exp == 'N':
17800f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista                return context._raise_error(InvalidOperation, 'sNaN', self)
178158f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            if other._exp == 'N':
17820f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista                return context._raise_error(InvalidOperation, 'sNaN', other)
178358f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            if self._exp == 'n':
178458f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                product = self
178558f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            elif other._exp == 'n':
178658f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                product = other
178758f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            elif self._exp == 'F':
178858f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                if not other:
178958f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                    return context._raise_error(InvalidOperation,
179058f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                                                'INF * 0 in fma')
1791b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                product = _SignedInfinity[self._sign ^ other._sign]
179258f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            elif other._exp == 'F':
179358f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                if not self:
179458f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                    return context._raise_error(InvalidOperation,
179558f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                                                '0 * INF in fma')
1796b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                product = _SignedInfinity[self._sign ^ other._sign]
179758f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista        else:
179858f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            product = _dec_from_triple(self._sign ^ other._sign,
179958f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                                       str(int(self._int) * int(other._int)),
180058f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                                       self._exp + other._exp)
18017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
180258f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista        third = _convert_other(third, raiseit=True)
180358f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista        return product.__add__(third, context)
18047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1805353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _power_modulo(self, other, modulo, context=None):
1806353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Three argument version of __pow__"""
18077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1808353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if can't convert other and modulo to Decimal, raise
1809353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # TypeError; there's no point returning NotImplemented (no
1810353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # equivalent of __rpow__ for three argument pow)
1811353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
1812353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        modulo = _convert_other(modulo, raiseit=True)
18137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1814353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
1815353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
18167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1817353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # deal with NaNs: if there are any sNaNs then first one wins,
1818353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (i.e. behaviour for NaNs is identical to that of fma)
1819353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_is_nan = self._isnan()
1820353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other_is_nan = other._isnan()
1821353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        modulo_is_nan = modulo._isnan()
1822353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_is_nan or other_is_nan or modulo_is_nan:
1823353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self_is_nan == 2:
1824353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation, 'sNaN',
18250f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista                                        self)
1826353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other_is_nan == 2:
1827353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation, 'sNaN',
18280f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista                                        other)
1829353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if modulo_is_nan == 2:
1830353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation, 'sNaN',
18310f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista                                        modulo)
1832353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self_is_nan:
18336c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                return self._fix_nan(context)
1834353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other_is_nan:
18356c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                return other._fix_nan(context)
18366c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return modulo._fix_nan(context)
1837353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1838353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # check inputs: we apply same restrictions as Python's pow()
1839353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (self._isinteger() and
1840353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                other._isinteger() and
1841353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                modulo._isinteger()):
1842353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1843353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'pow() 3rd argument not allowed '
1844353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'unless all arguments are integers')
1845353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other < 0:
1846353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1847353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'pow() 2nd argument cannot be '
1848353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'negative when 3rd argument specified')
1849353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not modulo:
1850353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1851353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'pow() 3rd argument cannot be 0')
1852353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1853353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # additional restriction for decimal: the modulus must be less
1854353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # than 10**prec in absolute value
1855353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if modulo.adjusted() >= context.prec:
1856353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1857353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'insufficient precision: pow() 3rd '
1858353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'argument must not have more than '
1859353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'precision digits')
1860353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1861353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # define 0**0 == NaN, for consistency with two-argument pow
1862353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (even though it hurts!)
1863353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other and not self:
1864353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1865353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'at least one of pow() 1st argument '
1866353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'and 2nd argument must be nonzero ;'
1867353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        '0**0 is not defined')
1868353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1869353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute sign of result
1870353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._iseven():
1871353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sign = 0
1872353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
1873353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sign = self._sign
1874353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1875353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # convert modulo to a Python integer, and self and other to
1876353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Decimal integers (i.e. force their exponents to be >= 0)
1877353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        modulo = abs(int(modulo))
1878353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        base = _WorkRep(self.to_integral_value())
1879353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exponent = _WorkRep(other.to_integral_value())
1880353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1881353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute result using integer pow()
1882353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1883353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        for i in xrange(exponent.exp):
1884353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            base = pow(base, 10, modulo)
1885353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        base = pow(base, exponent.int, modulo)
1886353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
188772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(sign, str(base), 0)
1888353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1889353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _power_exact(self, other, p):
1890353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Attempt to compute self**other exactly.
1891353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1892353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Given Decimals self and other and an integer p, attempt to
1893353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        compute an exact result for the power self**other, with p
1894353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        digits of precision.  Return None if self**other is not
1895353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exactly representable in p digits.
1896353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1897353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Assumes that elimination of special cases has already been
1898353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        performed: self and other must both be nonspecial; self must
1899353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        be positive and not numerically equal to 1; other must be
1900353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        nonzero.  For efficiency, other._exp should not be too large,
1901353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        so that 10**abs(other._exp) is a feasible calculation."""
1902353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1903353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # In the comments below, we write x for the value of self and
1904353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # y for the value of other.  Write x = xc*10**xe and y =
1905353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # yc*10**ye.
1906353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1907353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # The main purpose of this method is to identify the *failure*
1908353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # of x**y to be exactly representable with as little effort as
1909353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # possible.  So we look for cheap and easy tests that
1910353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # eliminate the possibility of x**y being exact.  Only if all
1911353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # these tests are passed do we go on to actually compute x**y.
1912353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1913353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Here's the main idea.  First normalize both x and y.  We
1914353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # express y as a rational m/n, with m and n relatively prime
1915353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # and n>0.  Then for x**y to be exactly representable (at
1916353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # *any* precision), xc must be the nth power of a positive
1917353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # integer and xe must be divisible by n.  If m is negative
1918353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # then additionally xc must be a power of either 2 or 5, hence
1919353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # a power of 2**n or 5**n.
1920353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1921353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # There's a limit to how small |y| can be: if y=m/n as above
1922353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # then:
1923353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1924353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #  (1) if xc != 1 then for the result to be representable we
1925353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      need xc**(1/n) >= 2, and hence also xc**|y| >= 2.  So
1926353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1927353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      2**(1/|y|), hence xc**|y| < 2 and the result is not
1928353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      representable.
1929353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1930353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #  (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1.  Hence if
1931353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      |y| < 1/|xe| then the result is not representable.
1932353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1933353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Note that since x is not equal to 1, at least one of (1) and
1934353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (2) must apply.  Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1935353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1936353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1937353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # There's also a limit to how large y can be, at least if it's
1938353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # positive: the normalized result will have coefficient xc**y,
1939353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # so if it's representable then xc**y < 10**p, and y <
1940353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # p/log10(xc).  Hence if y*log10(xc) >= p then the result is
1941353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # not exactly representable.
1942353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1943353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1944353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # so |y| < 1/xe and the result is not representable.
1945353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1946353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # < 1/nbits(xc).
1947353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1948353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        x = _WorkRep(self)
1949353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        xc, xe = x.int, x.exp
1950353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while xc % 10 == 0:
1951353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xc //= 10
1952353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xe += 1
1953353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1954353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        y = _WorkRep(other)
1955353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        yc, ye = y.int, y.exp
1956353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while yc % 10 == 0:
1957353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            yc //= 10
1958353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ye += 1
1959353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1960353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # case where xc == 1: result is 10**(xe*y), with xe*y
1961353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # required to be an integer
1962353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if xc == 1:
1963353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ye >= 0:
1964353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exponent = xe*yc*10**ye
1965353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1966353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exponent, remainder = divmod(xe*yc, 10**-ye)
1967353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if remainder:
1968353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1969353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if y.sign == 1:
1970353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exponent = -exponent
1971353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # if other is a nonnegative integer, use ideal exponent
1972353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._isinteger() and other._sign == 0:
1973353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                ideal_exponent = self._exp*int(other)
1974353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                zeros = min(exponent-ideal_exponent, p-1)
1975353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1976353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                zeros = 0
197772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
1978353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1979353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # case where y is negative: xc must be either a power
1980353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # of 2 or a power of 5.
1981353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if y.sign == 1:
1982353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            last_digit = xc % 10
1983353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if last_digit in (2,4,6,8):
1984353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # quick test for power of 2
1985353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if xc & -xc != xc:
1986353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1987353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # now xc is a power of 2; e is its exponent
1988353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                e = _nbits(xc)-1
1989353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # find e*y and xe*y; both must be integers
1990353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if ye >= 0:
1991353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    y_as_int = yc*10**ye
1992353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e = e*y_as_int
1993353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xe = xe*y_as_int
1994353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                else:
1995353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    ten_pow = 10**-ye
1996353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e, remainder = divmod(e*yc, ten_pow)
1997353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if remainder:
1998353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return None
1999353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xe, remainder = divmod(xe*yc, ten_pow)
2000353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if remainder:
2001353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return None
2002353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2003353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if e*65 >= p*93: # 93/65 > log(10)/log(5)
2004353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
2005353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                xc = 5**e
2006353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2007353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            elif last_digit == 5:
2008353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # e >= log_5(xc) if xc is a power of 5; we have
2009353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # equality all the way up to xc=5**2658
2010353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                e = _nbits(xc)*28//65
2011353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                xc, remainder = divmod(5**e, xc)
2012353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if remainder:
2013353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
2014353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                while xc % 5 == 0:
2015353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xc //= 5
2016353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e -= 1
2017353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if ye >= 0:
2018353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    y_as_integer = yc*10**ye
2019353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e = e*y_as_integer
2020353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xe = xe*y_as_integer
2021353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                else:
2022353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    ten_pow = 10**-ye
2023353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e, remainder = divmod(e*yc, ten_pow)
2024353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if remainder:
2025353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return None
2026353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xe, remainder = divmod(xe*yc, ten_pow)
2027353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if remainder:
2028353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return None
2029353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if e*3 >= p*10: # 10/3 > log(10)/log(2)
2030353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
2031353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                xc = 2**e
2032353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2033353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
20347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2035353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if xc >= 10**p:
2036353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
2037353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xe = -e-xe
203872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(0, str(xc), xe)
20397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2040353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # now y is positive; find m and n such that y = m/n
2041353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ye >= 0:
2042353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            m, n = yc*10**ye, 1
2043353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2044353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2045353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
2046353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xc_bits = _nbits(xc)
2047353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2048353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
2049353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            m, n = yc, 10**(-ye)
2050353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while m % 2 == n % 2 == 0:
2051353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                m //= 2
2052353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n //= 2
2053353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while m % 5 == n % 5 == 0:
2054353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                m //= 5
2055353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n //= 5
2056353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute nth root of xc*10**xe
2058353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if n > 1:
2059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # if 1 < xc < 2**n then xc isn't an nth power
2060353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if xc != 1 and xc_bits <= n:
2061353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
2062353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2063353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xe, rem = divmod(xe, n)
2064353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if rem != 0:
2065353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
2066353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2067353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # compute nth root of xc using Newton's method
2068353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            a = 1L << -(-_nbits(xc)//n) # initial estimate
2069353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while True:
2070353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                q, r = divmod(xc, a**(n-1))
2071353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if a <= q:
2072353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
2073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                else:
2074353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    a = (a*(n-1) + q)//n
2075353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if not (a == q and r == 0):
2076353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
2077353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xc = a
2078353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2079353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # now xc*10**xe is the nth root of the original xc*10**xe
2080353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute mth power of xc*10**xe
2081353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2082353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2083353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 10**p and the result is not representable.
2084353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if xc > 1 and m > p*100//_log10_lb(xc):
2085353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return None
2086353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        xc = xc**m
2087353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        xe *= m
2088353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if xc > 10**p:
2089353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return None
2090353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2091353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # by this point the result *is* exactly representable
2092353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # adjust the exponent to get as close as possible to the ideal
2093353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exponent, if necessary
2094353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        str_xc = str(xc)
2095353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._isinteger() and other._sign == 0:
2096353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ideal_exponent = self._exp*int(other)
2097353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            zeros = min(xe-ideal_exponent, p-len(str_xc))
2098353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2099353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            zeros = 0
210072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
2101cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
2102353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def __pow__(self, other, modulo=None, context=None):
2103353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return self ** other [ % modulo].
21047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2105353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        With two arguments, compute self**other.
21067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2107353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        With three arguments, compute (self**other) % modulo.  For the
2108353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        three argument form, the following restrictions on the
2109353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        arguments hold:
21107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2111353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - all three arguments must be integral
2112353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - other must be nonnegative
2113353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - either self or other (or both) must be nonzero
2114353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - modulo must be nonzero and must have at most p digits,
2115353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista           where p is the context precision.
21167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2117353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        If any of these restrictions is violated the InvalidOperation
2118353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        flag is raised.
2119353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2120353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result of pow(self, other, modulo) is identical to the
2121353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        result that would be obtained by computing (self**other) %
2122353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        modulo with unbounded precision, but is computed more
2123353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        efficiently.  It is always exact.
2124353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2125353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2126353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if modulo is not None:
2127353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._power_modulo(other, modulo, context)
21287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2129636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
2130267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
2131267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
21327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2133353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2134353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
21357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2136353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # either argument is a NaN => result is NaN
2137353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
2138353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
2139353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
21407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2141353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2142353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other:
2143353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if not self:
2144353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation, '0 ** 0')
2145353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2146b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                return _One
21477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2148353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # result has sign 1 iff self._sign is 1 and other is an odd integer
2149353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        result_sign = 0
2150353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign == 1:
2151353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._isinteger():
2152353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if not other._iseven():
2153353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    result_sign = 1
2154353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2155353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # -ve**noninteger = NaN
2156353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # (-0)**noninteger = 0**noninteger
2157353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self:
2158353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return context._raise_error(InvalidOperation,
2159353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        'x ** y with x negative and y not an integer')
2160353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # negate self, without doing any unwanted rounding
216172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self = self.copy_negate()
2162353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2163353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2164353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2165353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._sign == 0:
216672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(result_sign, '0', 0)
2167353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2168b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                return _SignedInfinity[result_sign]
2169353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2170353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
2171353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
2172353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._sign == 0:
2173b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                return _SignedInfinity[result_sign]
2174353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
217572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(result_sign, '0', 0)
2176353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2177353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 1**other = 1, but the choice of exponent and the flags
2178353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # depend on the exponent of self, and on whether other is a
2179353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # positive integer, a negative integer, or neither
2180b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger        if self == _One:
2181353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._isinteger():
2182353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # exp = max(self._exp*max(int(other), 0),
2183353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # 1-context.prec) but evaluating int(other) directly
2184353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # is dangerous until we know other is small (other
2185353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # could be 1e999999999)
2186353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other._sign == 1:
2187353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    multiplier = 0
2188353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                elif other > context.prec:
2189353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    multiplier = context.prec
2190353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                else:
2191353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    multiplier = int(other)
2192353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2193353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exp = self._exp * multiplier
2194353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if exp < 1-context.prec:
2195353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    exp = 1-context.prec
2196353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    context._raise_error(Rounded)
2197353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2198353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Inexact)
2199353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Rounded)
2200353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exp = 1-context.prec
2201353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
220272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
2203353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2204353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute adjusted exponent of self
2205353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_adj = self.adjusted()
2206353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2207353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self ** infinity is infinity if self > 1, 0 if self < 1
2208353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self ** -infinity is infinity if self < 1, 0 if self > 1
2209353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._isinfinity():
2210353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if (other._sign == 0) == (self_adj < 0):
221172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(result_sign, '0', 0)
2212353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2213b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                return _SignedInfinity[result_sign]
2214353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2215353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # from here on, the result always goes through the call
2216353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # to _fix at the end of this function.
2217353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = None
2218353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2219353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # crude test to catch cases of extreme overflow/underflow.  If
2220353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2221353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2222353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self**other >= 10**(Emax+1), so overflow occurs.  The test
2223353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # for underflow is similar.
2224353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        bound = self._log10_exp_bound() + other.adjusted()
2225353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if (self_adj >= 0) == (other._sign == 0):
2226353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # self > 1 and other +ve, or self < 1 and other -ve
2227353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # possibility of overflow
2228353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if bound >= len(str(context.Emax)):
222972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(result_sign, '1', context.Emax+1)
2230353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2231353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # self > 1 and other -ve, or self < 1 and other +ve
2232353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # possibility of underflow to 0
2233353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            Etiny = context.Etiny()
2234353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if bound >= len(str(-Etiny)):
223572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(result_sign, '1', Etiny-1)
2236353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2237353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # try for an exact result with precision +1
2238353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans is None:
2239353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._power_exact(other, context.prec + 1)
2240353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans is not None and result_sign == 1:
224172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(1, ans._int, ans._exp)
2242353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2243353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # usual case: inexact result, x**y computed directly as exp(y*log(x))
2244353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans is None:
2245353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            p = context.prec
2246353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            x = _WorkRep(self)
2247353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xc, xe = x.int, x.exp
2248353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            y = _WorkRep(other)
2249353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            yc, ye = y.int, y.exp
2250353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if y.sign == 1:
2251353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                yc = -yc
2252353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2253353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # compute correctly rounded result:  start with precision +3,
2254353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # then increase precision until result is unambiguously roundable
2255353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            extra = 3
2256353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while True:
2257353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2258353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if coeff % (5*10**(len(str(coeff))-p-1)):
2259353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
2260353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                extra += 3
2261353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
226272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(result_sign, str(coeff), exp)
2263353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2264353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the specification says that for non-integer other we need to
2265353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # raise Inexact, even when the result is actually exact.  In
2266353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the same way, we need to raise Underflow here if the result
2267353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # is subnormal.  (The call to _fix will take care of raising
2268353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Rounded and Subnormal, as usual.)
2269353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other._isinteger():
2270353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
2271353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # pad with zeros up to length context.prec+1 if necessary
2272353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if len(ans._int) <= context.prec:
2273353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                expdiff = context.prec+1 - len(ans._int)
227472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
227572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                       ans._exp-expdiff)
2276353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans.adjusted() < context.Emin:
2277353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Underflow)
2278353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2279353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # unlike exp, ln and log10, the power function respects the
2280353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # rounding mode; no need to use ROUND_HALF_EVEN here
2281353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2282353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
2283353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2284353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def __rpow__(self, other, context=None):
2285353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Swaps self/other and returns __pow__."""
2286353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other)
2287353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other is NotImplemented:
2288353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return other
2289353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return other.__pow__(self, context=context)
2290353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2291353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def normalize(self, context=None):
2292353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
2293353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2294353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2295353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2296353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2297353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
2298353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._check_nans(context=context)
2299353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans:
2300353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return ans
2301353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2302353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        dup = self._fix(context)
2303353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if dup._isinfinity():
2304353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return dup
2305353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2306353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not dup:
230772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(dup._sign, '0', 0)
2308353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exp_max = [context.Emax, context.Etop()][context._clamp]
2309353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        end = len(dup._int)
23107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exp = dup._exp
231172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        while dup._int[end-1] == '0' and exp < exp_max:
23127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            exp += 1
23137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            end -= 1
231472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(dup._sign, dup._int[:end], exp)
23157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2316bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista    def quantize(self, exp, rounding=None, context=None, watchexp=True):
23177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Quantize self so its exponent is the same as that of exp.
23187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
23197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Similar to self._rescale(exp._exp) but with error checking.
23207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2321bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista        exp = _convert_other(exp, raiseit=True)
2322bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista
2323353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2324353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2325353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if rounding is None:
2326353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rounding = context.rounding
2327353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2328636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or exp._is_special:
2329636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(exp, context)
2330636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
2331636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
23327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2333636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if exp._isinfinity() or self._isinfinity():
2334636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if exp._isinfinity() and self._isinfinity():
23356c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return Decimal(self)  # if both are inf, it is OK
2336636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return context._raise_error(InvalidOperation,
2337636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                                        'quantize with one INF')
2338353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2339bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista        # if we're not watching exponents, do a simple rescale
2340bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista        if not watchexp:
2341bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista            ans = self._rescale(exp._exp, rounding)
2342bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista            # raise Inexact and Rounded where appropriate
2343bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista            if ans._exp > self._exp:
2344bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista                context._raise_error(Rounded)
2345bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista                if ans != self:
2346bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista                    context._raise_error(Inexact)
2347bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista            return ans
2348bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista
2349353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp._exp should be between Etiny and Emax
2350353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (context.Etiny() <= exp._exp <= context.Emax):
2351353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2352353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                   'target exponent out of bounds in quantize')
2353353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2354353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
235572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(self._sign, '0', exp._exp)
2356353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
2357353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2358353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_adjusted = self.adjusted()
2359353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_adjusted > context.Emax:
2360353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2361353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'exponent of quantize result too large for current context')
2362353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_adjusted - exp._exp + 1 > context.prec:
2363353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2364353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'quantize result has too many digits for current context')
2365353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2366353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._rescale(exp._exp, rounding)
2367353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans.adjusted() > context.Emax:
2368353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2369353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'exponent of quantize result too large for current context')
2370353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if len(ans._int) > context.prec:
2371353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2372353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'quantize result has too many digits for current context')
2373353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2374353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # raise appropriate flags
2375353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans._exp > self._exp:
2376353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Rounded)
2377353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans != self:
2378353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Inexact)
2379353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans and ans.adjusted() < context.Emin:
2380353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Subnormal)
2381353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2382353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # call to fix takes care of any necessary folddown
2383353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2384353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
23857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
23867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def same_quantum(self, other):
23871a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self and other have the same exponent; otherwise
23881a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return False.
23897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
23901a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        If either operand is a special value, the following rules are used:
23911a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista           * return True if both operands are infinities
23921a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista           * return True if both operands are NaNs
23931a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista           * otherwise, return False.
23947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
23951a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        other = _convert_other(other, raiseit=True)
2396636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
23971a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista            return (self.is_nan() and other.is_nan() or
23981a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista                    self.is_infinite() and other.is_infinite())
23997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return self._exp == other._exp
24007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2401353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _rescale(self, exp, rounding):
2402353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rescale self so that the exponent is exp, either by padding with zeros
2403353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        or by truncating digits, using the given rounding mode.
2404353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2405353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Specials are returned without change.  This operation is
2406353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        quiet: it raises no flags, and uses no information from the
2407353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.
24087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
24097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exp = exp to scale to (an integer)
2410353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = rounding mode
24117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2412636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
24136c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
24147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
241572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(self._sign, '0', exp)
24167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2417353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp >= exp:
2418353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # pad answer with zeros if necessary
241972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(self._sign,
242072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                        self._int + '0'*(self._exp - exp), exp)
24217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2422353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # too many digits; round and lose data.  If self.adjusted() <
2423353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp-1, replace self by 10**(exp-1) before rounding
2424353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        digits = len(self._int) + self._exp - exp
24257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if digits < 0:
242672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self = _dec_from_triple(self._sign, '1', exp-1)
2427353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            digits = 0
2428353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        this_function = getattr(self, self._pick_rounding_function[rounding])
24292ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        changed = this_function(digits)
24302ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        coeff = self._int[:digits] or '0'
24312ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        if changed == 1:
24322ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            coeff = str(int(coeff)+1)
24332ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        return _dec_from_triple(self._sign, coeff, exp)
24347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
24351ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    def _round(self, places, rounding):
24361ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        """Round a nonzero, nonspecial Decimal to a fixed number of
24371ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        significant figures, using the given rounding mode.
24381ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
24391ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        Infinities, NaNs and zeros are returned unaltered.
24401ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
24411ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        This operation is quiet: it raises no flags, and uses no
24421ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        information from the context.
24431ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
24441ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        """
24451ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        if places <= 0:
24461ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson            raise ValueError("argument should be at least 1 in _round")
24471ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        if self._is_special or not self:
24481ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson            return Decimal(self)
24491ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        ans = self._rescale(self.adjusted()+1-places, rounding)
24501ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        # it can happen that the rescale alters the adjusted exponent;
24511ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        # for example when rounding 99.97 to 3 significant figures.
24521ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        # When this happens we end up with an extra 0 at the end of
24531ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        # the number; a second rescale fixes this.
24541ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        if ans.adjusted() != self.adjusted():
24551ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson            ans = ans._rescale(ans.adjusted()+1-places, rounding)
24561ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        return ans
24571ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
2458353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def to_integral_exact(self, rounding=None, context=None):
2459353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds to a nearby integer.
24607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2461353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        If no rounding mode is specified, take the rounding mode from
2462353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        the context.  This method raises the Rounded and Inexact flags
2463353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        when appropriate.
24647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2465353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        See also: to_integral_value, which does exactly the same as
2466353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        this method except that it doesn't raise Inexact or Rounded.
2467353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2468636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
2469636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
2470636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
2471636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
24726c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
24737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._exp >= 0:
24746c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
2475353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
247672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(self._sign, '0', 0)
2477636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
2478636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
2479353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if rounding is None:
2480353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rounding = context.rounding
2481353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._raise_error(Rounded)
2482353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._rescale(0, rounding)
2483353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans != self:
2484353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
24857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
24867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2487353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def to_integral_value(self, rounding=None, context=None):
2488353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds to the nearest integer, without raising inexact, rounded."""
2489353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2490353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2491353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if rounding is None:
2492353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rounding = context.rounding
2493353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
2494353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._check_nans(context=context)
2495353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans:
2496353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return ans
24976c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
2498353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp >= 0:
24996c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
2500353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2501353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._rescale(0, rounding)
25027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2503353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # the method name changed, but we provide also the old one, for compatibility
2504353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    to_integral = to_integral_value
2505353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2506353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def sqrt(self, context=None):
2507353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return the square root of self."""
25083b24ccbe7e2b43c4373e4b1e988df55978b819e7Mark Dickinson        if context is None:
25093b24ccbe7e2b43c4373e4b1e988df55978b819e7Mark Dickinson            context = getcontext()
25103b24ccbe7e2b43c4373e4b1e988df55978b819e7Mark Dickinson
2511636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
2512636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
2513636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
2514636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
25157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2516636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity() and self._sign == 0:
2517636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Decimal(self)
25187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
25197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
2520353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # exponent = self._exp // 2.  sqrt(-0) = -0
252172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(self._sign, '0', self._exp // 2)
2522353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
25237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
25247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign == 1:
25257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
25267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2527353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # At this point self represents a positive number.  Let p be
2528353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the desired precision and express self in the form c*100**e
2529353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # with c a positive real number and e an integer, c and e
2530353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # being chosen so that 100**(p-1) <= c < 100**p.  Then the
2531353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2532353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # <= sqrt(c) < 10**p, so the closest representable Decimal at
2533353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # precision p is n*10**e where n = round_half_even(sqrt(c)),
2534353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the closest integer to sqrt(c) with the even integer chosen
2535353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # in the case of a tie.
2536353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
2537353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # To ensure correct rounding in all cases, we use the
2538353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # following trick: we compute the square root to an extra
2539353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # place (precision p+1 instead of precision p), rounding down.
2540353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Then, if the result is inexact and its last digit is 0 or 5,
2541353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # we increase the last digit to 1 or 6 respectively; if it's
2542353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exact we leave the last digit alone.  Now the final round to
2543353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # p places (or fewer in the case of underflow) will round
2544353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # correctly and raise the appropriate flags.
2545353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2546353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # use an extra digit of precision
2547353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        prec = context.prec+1
2548353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2549353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # write argument in the form c*100**e where e = self._exp//2
2550353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # is the 'ideal' exponent, to be used if the square root is
2551353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exactly representable.  l is the number of 'digits' of c in
2552353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # base 100, so that 100**(l-1) <= c < 100**l.
2553353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op = _WorkRep(self)
2554353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        e = op.exp >> 1
2555353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if op.exp & 1:
2556353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = op.int * 10
2557353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            l = (len(self._int) >> 1) + 1
25587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
2559353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = op.int
2560353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            l = len(self._int)+1 >> 1
2561353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2562353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # rescale so that c has exactly prec base 100 'digits'
2563353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        shift = prec-l
2564353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if shift >= 0:
2565353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c *= 100**shift
2566353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            exact = True
25677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
2568353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c, remainder = divmod(c, 100**-shift)
2569353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            exact = not remainder
2570353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        e -= shift
2571353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2572353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # find n = floor(sqrt(c)) using Newton's method
2573353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        n = 10**prec
2574353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while True:
2575353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            q = c//n
2576353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if n <= q:
25777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                break
2578353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2579353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n = n + q >> 1
2580353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exact = exact and n*n == c
2581353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2582353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if exact:
2583353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # result is exact; rescale to use ideal exponent e
2584353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if shift >= 0:
2585353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # assert n % 10**shift == 0
2586353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n //= 10**shift
2587353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2588353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n *= 10**-shift
2589353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            e += shift
25907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
2591353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # result is not exact; fix last digit as described above
2592353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if n % 5 == 0:
2593353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n += 1
25947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
259572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        ans = _dec_from_triple(0, str(n), e)
25967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2597353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # round, and fit to current context
2598353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context._shallow_copy()
2599353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = context._set_rounding(ROUND_HALF_EVEN)
2600dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger        ans = ans._fix(context)
2601353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.rounding = rounding
26027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2603353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
26047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
26057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def max(self, other, context=None):
26067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the larger value.
26077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2608353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Like max(self, other) except if one is not a number, returns
26097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        NaN (and signals if one is sNaN).  Also rounds.
26107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2611353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
2612636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
26136c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        if context is None:
26146c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            context = getcontext()
26156c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista
2616636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
261759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If one operand is a quiet NaN and the other is number, then the
2618636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            # number is always returned
2619636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            sn = self._isnan()
2620636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            on = other._isnan()
2621636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if sn or on:
2622e29d435e0cefb3e1772f6de0844e628aac3cf98eFacundo Batista                if on == 1 and sn == 0:
2623e29d435e0cefb3e1772f6de0844e628aac3cf98eFacundo Batista                    return self._fix(context)
2624e29d435e0cefb3e1772f6de0844e628aac3cf98eFacundo Batista                if sn == 1 and on == 0:
2625e29d435e0cefb3e1772f6de0844e628aac3cf98eFacundo Batista                    return other._fix(context)
2626636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return self._check_nans(other, context)
26277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
26282fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        c = self._cmp(other)
2629d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        if c == 0:
263059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If both operands are finite and equal in numerical value
2631d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger            # then an ordering is applied:
2632d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger            #
263359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If the signs differ then max returns the operand with the
2634d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger            # positive sign and min returns the operand with the negative sign
2635d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger            #
263659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If the signs are the same then the exponent is used to select
2637353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # the result.  This is exactly the ordering used in compare_total.
2638353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = self.compare_total(other)
2639353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2640353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == -1:
26417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = other
2642353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2643353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self
2644636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
2645e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        return ans._fix(context)
26467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
26477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def min(self, other, context=None):
26487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the smaller value.
26497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
265059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        Like min(self, other) except if one is not a number, returns
26517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        NaN (and signals if one is sNaN).  Also rounds.
26527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2653353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
2654636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
26556c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        if context is None:
26566c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            context = getcontext()
26576c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista
2658636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
265959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If one operand is a quiet NaN and the other is number, then the
2660636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            # number is always returned
2661636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            sn = self._isnan()
2662636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            on = other._isnan()
2663636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if sn or on:
2664e29d435e0cefb3e1772f6de0844e628aac3cf98eFacundo Batista                if on == 1 and sn == 0:
2665e29d435e0cefb3e1772f6de0844e628aac3cf98eFacundo Batista                    return self._fix(context)
2666e29d435e0cefb3e1772f6de0844e628aac3cf98eFacundo Batista                if sn == 1 and on == 0:
2667e29d435e0cefb3e1772f6de0844e628aac3cf98eFacundo Batista                    return other._fix(context)
2668636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return self._check_nans(other, context)
26697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
26702fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        c = self._cmp(other)
2671d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        if c == 0:
2672353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = self.compare_total(other)
2673353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2674353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == -1:
2675353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self
2676353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
26777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = other
2678636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
2679e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        return ans._fix(context)
26807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
26817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _isinteger(self):
26827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns whether self is an integer"""
2683353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
2684353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return False
26857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._exp >= 0:
26867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return True
26877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rest = self._int[self._exp:]
268872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return rest == '0'*len(rest)
26897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
26907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _iseven(self):
2691353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns True if self is even.  Assumes self is an integer."""
2692353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self or self._exp > 0:
2693353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return True
269472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return self._int[-1+self._exp] in '02468'
26957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
26967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def adjusted(self):
26977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return the adjusted exponent of self"""
26987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        try:
26997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return self._exp + len(self._int) - 1
270059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # If NaN or Infinity, self._exp is string
27017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        except TypeError:
27027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return 0
27037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2704353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def canonical(self, context=None):
2705353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the same Decimal object.
2706353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2707353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        As we do not have different encodings for the same number, the
2708353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        received object already is in its canonical form.
2709353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2710353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self
2711353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2712353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_signal(self, other, context=None):
2713353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares self to the other operand numerically.
2714353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2715353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        It's pretty much like compare(), but all NaNs signal, with signaling
2716353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        NaNs taking precedence over quiet NaNs.
2717353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
27182fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        other = _convert_other(other, raiseit = True)
27192fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        ans = self._compare_check_nans(other, context)
27202fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if ans:
27212fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return ans
2722353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self.compare(other, context=context)
2723353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2724353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_total(self, other):
2725353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares self to other using the abstract representations.
2726353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2727353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        This is not like the standard compare, which use their numerical
2728353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        value. Note that a total ordering is defined for all possible abstract
2729353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        representations.
2730353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2731353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if one is negative and the other is positive, it's easy
2732353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign and not other._sign:
2733b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger            return _NegativeOne
2734353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self._sign and other._sign:
2735b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger            return _One
2736353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        sign = self._sign
2737353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2738353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # let's handle both NaN types
2739353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_nan = self._isnan()
2740353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other_nan = other._isnan()
2741353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_nan or other_nan:
2742353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self_nan == other_nan:
2743353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self._int < other._int:
2744353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if sign:
2745b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                        return _One
2746353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    else:
2747b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                        return _NegativeOne
2748353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self._int > other._int:
2749353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if sign:
2750b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                        return _NegativeOne
2751353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    else:
2752b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                        return _One
2753b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                return _Zero
2754353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2755353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sign:
2756353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_nan == 1:
2757b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                    return _NegativeOne
2758353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other_nan == 1:
2759b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                    return _One
2760353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_nan == 2:
2761b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                    return _NegativeOne
2762353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other_nan == 2:
2763b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                    return _One
2764353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2765353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_nan == 1:
2766b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                    return _One
2767353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other_nan == 1:
2768b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                    return _NegativeOne
2769353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_nan == 2:
2770b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                    return _One
2771353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other_nan == 2:
2772b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                    return _NegativeOne
2773353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2774353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self < other:
2775b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger            return _NegativeOne
2776353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self > other:
2777b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger            return _One
2778353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2779353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp < other._exp:
2780353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sign:
2781b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                return _One
2782353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2783b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                return _NegativeOne
2784353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp > other._exp:
2785353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sign:
2786b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                return _NegativeOne
2787353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2788b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger                return _One
2789b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger        return _Zero
2790353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2791353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2792353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_total_mag(self, other):
2793353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares self to other using abstract repr., ignoring sign.
2794353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2795353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Like compare_total, but with operand's sign ignored and assumed to be 0.
2796353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2797353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        s = self.copy_abs()
2798353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        o = other.copy_abs()
2799353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return s.compare_total(o)
2800353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2801353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_abs(self):
2802353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy with the sign set to 0. """
280372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(0, self._int, self._exp, self._is_special)
2804353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2805353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_negate(self):
2806353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy with the sign inverted."""
2807353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign:
280872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(0, self._int, self._exp, self._is_special)
2809353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
281072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(1, self._int, self._exp, self._is_special)
2811353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2812353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_sign(self, other):
2813353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns self with the sign of other."""
281472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(other._sign, self._int,
281572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                self._exp, self._is_special)
2816353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2817353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def exp(self, context=None):
2818353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns e ** self."""
2819353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2820353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2821353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2822353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2823353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp(NaN) = NaN
2824353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
2825353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
2826353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
2827353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2828353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp(-Infinity) = 0
2829353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == -1:
2830b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger            return _Zero
2831353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2832353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp(0) = 1
2833353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2834b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger            return _One
2835353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2836353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp(Infinity) = Infinity
2837353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
2838353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Decimal(self)
2839353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2840353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the result is now guaranteed to be inexact (the true
2841353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # mathematical result is transcendental). There's no need to
2842353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # raise Rounded and Inexact here---they'll always be raised as
2843353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # a result of the call to _fix.
2844353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        p = context.prec
2845353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        adj = self.adjusted()
2846353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2847353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # we only need to do any computation for quite a small range
2848353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # of adjusted exponents---for example, -29 <= adj <= 10 for
2849353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the default context.  For smaller exponent the result is
2850353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # indistinguishable from 1 at the given precision, while for
2851353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # larger exponent the result either overflows or underflows.
2852353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2853353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # overflow
285472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(0, '1', context.Emax+1)
2855353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2856353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # underflow to 0
285772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(0, '1', context.Etiny()-1)
2858353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif self._sign == 0 and adj < -p:
2859353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # p+1 digits; final round will raise correct flags
286072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
2861353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif self._sign == 1 and adj < -p-1:
2862353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # p+1 digits; final round will raise correct flags
286372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(0, '9'*(p+1), -p-1)
2864353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # general case
2865353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2866353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            op = _WorkRep(self)
2867353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c, e = op.int, op.exp
2868353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if op.sign == 1:
2869353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                c = -c
2870353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2871353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # compute correctly rounded result: increase precision by
2872353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # 3 digits at a time until we get an unambiguously
2873353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # roundable result
2874353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            extra = 3
2875353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while True:
2876353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                coeff, exp = _dexp(c, e, p+extra)
2877353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if coeff % (5*10**(len(str(coeff))-p-1)):
2878353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
2879353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                extra += 3
2880353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
288172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(0, str(coeff), exp)
2882353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2883353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # at this stage, ans should round correctly with *any*
2884353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # rounding mode, not just with ROUND_HALF_EVEN
2885353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context._shallow_copy()
2886353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = context._set_rounding(ROUND_HALF_EVEN)
2887353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2888353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.rounding = rounding
2889353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2890353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
2891353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2892353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_canonical(self):
28931a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is canonical; otherwise return False.
28941a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista
28951a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        Currently, the encoding of a Decimal instance is always
28961a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        canonical, so this method returns True for any Decimal.
28971a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """
28981a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return True
2899353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2900353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_finite(self):
29011a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is finite; otherwise return False.
2902353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
29031a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        A Decimal instance is considered finite if it is neither
29041a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        infinite nor a NaN.
2905353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
29061a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return not self._is_special
2907353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2908353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_infinite(self):
29091a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is infinite; otherwise return False."""
29101a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self._exp == 'F'
2911353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2912353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_nan(self):
29131a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is a qNaN or sNaN; otherwise return False."""
29141a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self._exp in ('n', 'N')
2915353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2916353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_normal(self, context=None):
29171a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is a normal number; otherwise return False."""
29181a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        if self._is_special or not self:
29191a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista            return False
2920353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2921353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
29221a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return context.Emin <= self.adjusted() <= context.Emax
2923353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2924353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_qnan(self):
29251a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is a quiet NaN; otherwise return False."""
29261a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self._exp == 'n'
2927353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2928353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_signed(self):
29291a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is negative; otherwise return False."""
29301a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self._sign == 1
2931353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2932353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_snan(self):
29331a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is a signaling NaN; otherwise return False."""
29341a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self._exp == 'N'
2935353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2936353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_subnormal(self, context=None):
29371a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is subnormal; otherwise return False."""
29381a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        if self._is_special or not self:
29391a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista            return False
2940353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2941353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
29421a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self.adjusted() < context.Emin
2943353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2944353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_zero(self):
29451a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is a zero; otherwise return False."""
294672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return not self._is_special and self._int == '0'
2947353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2948353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _ln_exp_bound(self):
2949353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compute a lower bound for the adjusted exponent of self.ln().
2950353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        In other words, compute r such that self.ln() >= 10**r.  Assumes
2951353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        that self is finite and positive and that self != 1.
2952353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2953353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2954353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2955353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        adj = self._exp + len(self._int) - 1
2956353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj >= 1:
2957353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2958353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(str(adj*23//10)) - 1
2959353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj <= -2:
2960353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # argument <= 0.1
2961353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(str((-1-adj)*23//10)) - 1
2962353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op = _WorkRep(self)
2963353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c, e = op.int, op.exp
2964353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj == 0:
2965353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # 1 < self < 10
2966353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            num = str(c-10**-e)
2967353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            den = str(c)
2968353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(num) - len(den) - (num < den)
2969353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # adj == -1, 0.1 <= self < 1
2970353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return e + len(str(10**-e - c)) - 1
2971353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2972353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2973353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def ln(self, context=None):
2974353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the natural (base e) logarithm of self."""
2975353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2976353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2977353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2978353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2979353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(NaN) = NaN
2980353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
2981353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
2982353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
2983353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2984353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(0.0) == -Infinity
2985353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2986b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger            return _NegativeInfinity
2987353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2988353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(Infinity) = Infinity
2989353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
2990b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger            return _Infinity
2991353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2992353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(1.0) == 0.0
2993b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger        if self == _One:
2994b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger            return _Zero
2995353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2996353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(negative) raises InvalidOperation
2997353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign == 1:
2998353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2999353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'ln of a negative value')
3000353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3001353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # result is irrational, so necessarily inexact
3002353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op = _WorkRep(self)
3003353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c, e = op.int, op.exp
3004353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        p = context.prec
3005353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3006353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # correctly rounded result: repeatedly increase precision by 3
3007353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # until we get an unambiguously roundable result
3008353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        places = p - self._ln_exp_bound() + 2 # at least p+3 places
3009353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while True:
3010353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            coeff = _dlog(c, e, places)
3011353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # assert len(str(abs(coeff)))-p >= 1
3012353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3013353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                break
3014353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            places += 3
301572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
3016353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3017353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context._shallow_copy()
3018353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = context._set_rounding(ROUND_HALF_EVEN)
3019353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
3020353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.rounding = rounding
3021353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
3022353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3023353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _log10_exp_bound(self):
3024353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compute a lower bound for the adjusted exponent of self.log10().
3025353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        In other words, find r such that self.log10() >= 10**r.
3026353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Assumes that self is finite and positive and that self != 1.
3027353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3028353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3029353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # For x >= 10 or x < 0.1 we only need a bound on the integer
3030353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # part of log10(self), and this comes directly from the
3031353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exponent of x.  For 0.1 <= x <= 10 we use the inequalities
3032353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3033353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (1-1/x)/2.31 > 0.  If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3034353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3035353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        adj = self._exp + len(self._int) - 1
3036353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj >= 1:
3037353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # self >= 10
3038353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(str(adj))-1
3039353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj <= -2:
3040353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # self < 0.1
3041353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(str(-1-adj))-1
3042353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op = _WorkRep(self)
3043353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c, e = op.int, op.exp
3044353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj == 0:
3045353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # 1 < self < 10
3046353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            num = str(c-10**-e)
3047353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            den = str(231*c)
3048353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(num) - len(den) - (num < den) + 2
3049353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # adj == -1, 0.1 <= self < 1
3050353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        num = str(10**-e-c)
3051353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return len(num) + e - (num < "231") - 1
3052353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3053353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def log10(self, context=None):
3054353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the base 10 logarithm of self."""
3055353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3056353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3058353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(NaN) = NaN
3060353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
3061353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3062353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3063353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3064353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(0.0) == -Infinity
3065353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
3066b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger            return _NegativeInfinity
3067353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3068353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(Infinity) = Infinity
3069353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
3070b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger            return _Infinity
3071353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3072353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(negative or -Infinity) raises InvalidOperation
3073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign == 1:
3074353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
3075353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'log10 of a negative value')
3076353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3077353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(10**n) = n
307872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
3079353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # answer may need rounding
3080353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal(self._exp + len(self._int) - 1)
3081353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
3082353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # result is irrational, so necessarily inexact
3083353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            op = _WorkRep(self)
3084353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c, e = op.int, op.exp
3085353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            p = context.prec
3086353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3087353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # correctly rounded result: repeatedly increase precision
3088353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # until result is unambiguously roundable
3089353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            places = p-self._log10_exp_bound()+2
3090353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while True:
3091353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                coeff = _dlog10(c, e, places)
3092353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # assert len(str(abs(coeff)))-p >= 1
3093353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3094353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
3095353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                places += 3
309672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
3097353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3098353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context._shallow_copy()
3099353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = context._set_rounding(ROUND_HALF_EVEN)
3100353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
3101353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.rounding = rounding
3102353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
3103353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3104353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logb(self, context=None):
3105353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """ Returns the exponent of the magnitude of self's MSD.
3106353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3107353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result is the integer which is the exponent of the magnitude
3108353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        of the most significant digit of self (as though it were truncated
3109353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        to a single digit while maintaining the value of that digit and
3110353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        without limiting the resulting exponent).
3111353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3112353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # logb(NaN) = NaN
3113353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
3114353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3115353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3116353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3117353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3118353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3119353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3120353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # logb(+/-Inf) = +Inf
3121353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
3122b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger            return _Infinity
3123353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3124353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # logb(0) = -Inf, DivisionByZero
3125353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
3126cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return context._raise_error(DivisionByZero, 'logb(0)', 1)
3127353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3128353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # otherwise, simply return the adjusted exponent of self, as a
3129353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Decimal.  Note that no attempt is made to fit the result
3130353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # into the current context.
3131353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal(self.adjusted())
3132353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3133353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _islogical(self):
3134353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return True if self is a logical operand.
3135353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3136c8acc882a92c1fe5df95ae73b7b8004737ed9222Andrew M. Kuchling        For being logical, it must be a finite number with a sign of 0,
3137353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        an exponent of 0, and a coefficient whose digits must all be
3138353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        either 0 or 1.
3139353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3140353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign != 0 or self._exp != 0:
3141353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return False
3142353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        for dig in self._int:
314372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            if dig not in '01':
3144353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return False
3145353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return True
3146353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3147353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _fill_logical(self, context, opa, opb):
3148353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        dif = context.prec - len(opa)
3149353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if dif > 0:
315072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            opa = '0'*dif + opa
3151353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif dif < 0:
3152353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            opa = opa[-context.prec:]
3153353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        dif = context.prec - len(opb)
3154353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if dif > 0:
315572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            opb = '0'*dif + opb
3156353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif dif < 0:
3157353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            opb = opb[-context.prec:]
3158353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return opa, opb
3159353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3160353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_and(self, other, context=None):
3161353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies an 'and' operation between self and other's digits."""
3162353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3163353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3164353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self._islogical() or not other._islogical():
3165353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3166353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3167353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # fill to context.prec
3168353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        (opa, opb) = self._fill_logical(context, self._int, other._int)
3169353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3170353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # make the operation, and clean starting zeroes
317172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
317272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3173353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3174353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_invert(self, context=None):
3175353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Invert all its digits."""
3176353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3177353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
317872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
317972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                context)
3180353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3181353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_or(self, other, context=None):
3182353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies an 'or' operation between self and other's digits."""
3183353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3184353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3185353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self._islogical() or not other._islogical():
3186353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3187353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3188353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # fill to context.prec
3189353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        (opa, opb) = self._fill_logical(context, self._int, other._int)
3190353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3191353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # make the operation, and clean starting zeroes
319265808ff0c08e60572cf81ebe5dc24794a706f390Mark Dickinson        result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
319372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3194353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3195353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_xor(self, other, context=None):
3196353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies an 'xor' operation between self and other's digits."""
3197353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3198353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3199353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self._islogical() or not other._islogical():
3200353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3201353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3202353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # fill to context.prec
3203353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        (opa, opb) = self._fill_logical(context, self._int, other._int)
3204353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3205353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # make the operation, and clean starting zeroes
320665808ff0c08e60572cf81ebe5dc24794a706f390Mark Dickinson        result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
320772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3208353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3209353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def max_mag(self, other, context=None):
3210353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values numerically with their sign ignored."""
3211353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
3212353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
32136c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        if context is None:
32146c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            context = getcontext()
32156c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista
3216353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special or other._is_special:
3217353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # If one operand is a quiet NaN and the other is number, then the
3218353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # number is always returned
3219353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sn = self._isnan()
3220353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            on = other._isnan()
3221353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sn or on:
3222e29d435e0cefb3e1772f6de0844e628aac3cf98eFacundo Batista                if on == 1 and sn == 0:
3223e29d435e0cefb3e1772f6de0844e628aac3cf98eFacundo Batista                    return self._fix(context)
3224e29d435e0cefb3e1772f6de0844e628aac3cf98eFacundo Batista                if sn == 1 and on == 0:
3225e29d435e0cefb3e1772f6de0844e628aac3cf98eFacundo Batista                    return other._fix(context)
3226353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self._check_nans(other, context)
3227353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
32282fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        c = self.copy_abs()._cmp(other.copy_abs())
3229353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == 0:
3230353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = self.compare_total(other)
3231353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3232353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == -1:
3233353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = other
3234353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
3235353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self
3236353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3237e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        return ans._fix(context)
3238353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3239353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def min_mag(self, other, context=None):
3240353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values numerically with their sign ignored."""
3241353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
3242353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
32436c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        if context is None:
32446c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            context = getcontext()
32456c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista
3246353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special or other._is_special:
3247353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # If one operand is a quiet NaN and the other is number, then the
3248353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # number is always returned
3249353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sn = self._isnan()
3250353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            on = other._isnan()
3251353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sn or on:
3252e29d435e0cefb3e1772f6de0844e628aac3cf98eFacundo Batista                if on == 1 and sn == 0:
3253e29d435e0cefb3e1772f6de0844e628aac3cf98eFacundo Batista                    return self._fix(context)
3254e29d435e0cefb3e1772f6de0844e628aac3cf98eFacundo Batista                if sn == 1 and on == 0:
3255e29d435e0cefb3e1772f6de0844e628aac3cf98eFacundo Batista                    return other._fix(context)
3256353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self._check_nans(other, context)
3257353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
32582fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        c = self.copy_abs()._cmp(other.copy_abs())
3259353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == 0:
3260353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = self.compare_total(other)
3261353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3262353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == -1:
3263353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self
3264353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
3265353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = other
3266353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3267e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        return ans._fix(context)
3268353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3269353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_minus(self, context=None):
3270353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the largest representable number smaller than itself."""
3271353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3272353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3273353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3274353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
3275353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3276353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3277353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3278353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == -1:
3279b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger            return _NegativeInfinity
3280353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
328172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(0, '9'*context.prec, context.Etop())
3282353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3283353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context.copy()
3284353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._set_rounding(ROUND_FLOOR)
3285353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._ignore_all_flags()
3286353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        new_self = self._fix(context)
3287353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if new_self != self:
3288353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return new_self
328972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
329072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                            context)
3291353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3292353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_plus(self, context=None):
3293353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the smallest representable number larger than itself."""
3294353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3295353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3296353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3297353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
3298353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3299353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3300353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3301353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
3302b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger            return _Infinity
3303353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == -1:
330472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(1, '9'*context.prec, context.Etop())
3305353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3306353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context.copy()
3307353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._set_rounding(ROUND_CEILING)
3308353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._ignore_all_flags()
3309353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        new_self = self._fix(context)
3310353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if new_self != self:
3311353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return new_self
331272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
331372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                            context)
3314353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3315353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_toward(self, other, context=None):
3316353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the number closest to self, in the direction towards other.
3317353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3318353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result is the closest representable number to self
3319353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        (excluding self) that is in the direction towards other,
3320353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        unless both have the same value.  If the two operands are
3321353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        numerically equal, then the result is a copy of self with the
3322353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        sign set to be the same as the sign of other.
3323353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3324353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
3325353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3326353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3327353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3328353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3329353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
3330353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3331353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3332353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
33332fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        comparison = self._cmp(other)
3334353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if comparison == 0:
333572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return self.copy_sign(other)
3336353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3337353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if comparison == -1:
3338353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.next_plus(context)
3339353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else: # comparison == 1
3340353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.next_minus(context)
3341353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3342353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # decide which flags to raise using value of ans
3343353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans._isinfinity():
3344353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Overflow,
3345353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                 'Infinite result from next_toward',
3346353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                 ans._sign)
3347353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Rounded)
3348353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
3349353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif ans.adjusted() < context.Emin:
3350353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Underflow)
3351353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Subnormal)
3352353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Rounded)
3353353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
3354353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # if precision == 1 then we don't raise Clamped for a
3355353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # result 0E-Etiny.
3356353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if not ans:
3357353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Clamped)
3358353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3359353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
3360353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3361353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def number_class(self, context=None):
3362353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns an indication of the class of self.
3363353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3364353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The class is one of the following strings:
33650f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista          sNaN
33660f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista          NaN
3367353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Infinity
3368353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Normal
3369353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Subnormal
3370353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Zero
3371353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Zero
3372353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Subnormal
3373353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Normal
3374353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Infinity
3375353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3376353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self.is_snan():
3377353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "sNaN"
3378353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self.is_qnan():
3379353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "NaN"
3380353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        inf = self._isinfinity()
3381353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if inf == 1:
3382353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "+Infinity"
3383353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if inf == -1:
3384353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "-Infinity"
3385353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self.is_zero():
3386353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self._sign:
3387353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return "-Zero"
3388353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
3389353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return "+Zero"
3390353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3391353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3392353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self.is_subnormal(context=context):
3393353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self._sign:
3394353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return "-Subnormal"
3395353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
3396353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return "+Subnormal"
3397353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # just a normal, regular, boring number, :)
3398353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign:
3399353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "-Normal"
3400353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
3401353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "+Normal"
3402353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3403353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def radix(self):
3404353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Just returns 10, as this is Decimal, :)"""
3405353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal(10)
3406353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3407353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def rotate(self, other, context=None):
3408353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a rotated copy of self, value-of-other times."""
3409353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3410353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3411353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3412353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
3413353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3414353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3415353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3416353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._exp != 0:
3417353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3418353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (-context.prec <= int(other) <= context.prec):
3419353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3420353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3421353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
34226c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
3423353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3424353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # get values, pad if necessary
3425353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        torot = int(other)
3426353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotdig = self._int
3427353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        topad = context.prec - len(rotdig)
3428353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if topad:
342972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            rotdig = '0'*topad + rotdig
3430353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3431353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # let's rotate!
3432353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotated = rotdig[torot:] + rotdig[:torot]
343372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(self._sign,
343472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                rotated.lstrip('0') or '0', self._exp)
3435353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3436353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def scaleb (self, other, context=None):
3437353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns self operand after adding the second value to its exp."""
3438353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3439353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3440353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3441353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
3442353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3443353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3444353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3445353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._exp != 0:
3446353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3447353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        liminf = -2 * (context.Emax + context.prec)
3448353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        limsup =  2 * (context.Emax + context.prec)
3449353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (liminf <= int(other) <= limsup):
3450353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3451353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3452353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
34536c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
3454353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
345572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
3456353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        d = d._fix(context)
3457353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return d
3458353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3459353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def shift(self, other, context=None):
3460353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a shifted copy of self, value-of-other times."""
3461353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3462353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3463353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3464353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
3465353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3466353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3467353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3468353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._exp != 0:
3469353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3470353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (-context.prec <= int(other) <= context.prec):
3471353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3472353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3473353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
34746c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
3475353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3476353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # get values, pad if necessary
3477353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        torot = int(other)
3478353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not torot:
34796c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
3480353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotdig = self._int
3481353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        topad = context.prec - len(rotdig)
3482353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if topad:
348372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            rotdig = '0'*topad + rotdig
3484353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3485353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # let's shift!
3486353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if torot < 0:
3487353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rotated = rotdig[:torot]
3488353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
348972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            rotated = rotdig + '0'*torot
3490353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rotated = rotated[-context.prec:]
3491353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
349272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(self._sign,
349372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                    rotated.lstrip('0') or '0', self._exp)
3494353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
349559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # Support for pickling, copy, and deepcopy
34967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __reduce__(self):
34977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return (self.__class__, (str(self),))
34987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
34997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __copy__(self):
35007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if type(self) == Decimal:
3501cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis            return self     # I'm immutable; therefore I am my own clone
35027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return self.__class__(str(self))
35037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __deepcopy__(self, memo):
35057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if type(self) == Decimal:
3506cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis            return self     # My components are also immutable
35077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return self.__class__(str(self))
35087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3509277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    # PEP 3101 support.  the _localeconv keyword argument should be
3510277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    # considered private: it's provided for ease of testing only.
3511277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    def __format__(self, specifier, context=None, _localeconv=None):
3512f4da77765f8581e31620e9f49c68028e57b0ae85Mark Dickinson        """Format a Decimal instance according to the given specifier.
35131ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
35141ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        The specifier should be a standard format specifier, with the
35151ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        form described in PEP 3101.  Formatting types 'e', 'E', 'f',
3516277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        'F', 'g', 'G', 'n' and '%' are supported.  If the formatting
3517277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        type is omitted it defaults to 'g' or 'G', depending on the
3518277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        value of context.capitals.
35191ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        """
35201ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
35211ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        # Note: PEP 3101 says that if the type is not present then
35221ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        # there should be at least one digit after the decimal point.
35231ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        # We take the liberty of ignoring this requirement for
35241ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        # Decimal---it's presumably there to make sure that
35251ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        # format(float, '') behaves similarly to str(float).
35261ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        if context is None:
35271ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson            context = getcontext()
35281ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
3529277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
35301ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
3531277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        # special values don't care about the type or precision
35321ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        if self._is_special:
3533277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson            sign = _format_sign(self._sign, spec)
3534277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson            body = str(self.copy_abs())
3535277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson            return _format_align(sign, body, spec)
35361ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
35371ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        # a type of None defaults to 'g' or 'G', depending on context
35381ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        if spec['type'] is None:
35391ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson            spec['type'] = ['g', 'G'][context.capitals]
3540277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
3541277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        # if type is '%', adjust exponent of self accordingly
3542277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        if spec['type'] == '%':
35431ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson            self = _dec_from_triple(self._sign, self._int, self._exp+2)
35441ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
35451ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        # round if necessary, taking rounding mode from the context
35461ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        rounding = context.rounding
35471ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        precision = spec['precision']
35481ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        if precision is not None:
35491ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson            if spec['type'] in 'eE':
35501ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson                self = self._round(precision+1, rounding)
35511ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson            elif spec['type'] in 'fF%':
35521ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson                self = self._rescale(-precision, rounding)
3553277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson            elif spec['type'] in 'gG' and len(self._int) > precision:
3554277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson                self = self._round(precision, rounding)
35551ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        # special case: zeros with a positive exponent can't be
35561ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        # represented in fixed point; rescale them to 0e0.
3557277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        if not self and self._exp > 0 and spec['type'] in 'fF%':
35581ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson            self = self._rescale(0, rounding)
35591ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
35601ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        # figure out placement of the decimal point
35611ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        leftdigits = self._exp + len(self._int)
3562277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        if spec['type'] in 'eE':
35631ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson            if not self and precision is not None:
35641ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson                dotplace = 1 - precision
35651ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson            else:
35661ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson                dotplace = 1
3567277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        elif spec['type'] in 'fF%':
3568277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson            dotplace = leftdigits
35691ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        elif spec['type'] in 'gG':
35701ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson            if self._exp <= 0 and leftdigits > -6:
35711ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson                dotplace = leftdigits
35721ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson            else:
35731ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson                dotplace = 1
35741ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
3575277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        # find digits before and after decimal point, and get exponent
3576277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        if dotplace < 0:
3577277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson            intpart = '0'
3578277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson            fracpart = '0'*(-dotplace) + self._int
3579277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        elif dotplace > len(self._int):
3580277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson            intpart = self._int + '0'*(dotplace-len(self._int))
3581277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson            fracpart = ''
35821ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        else:
3583277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson            intpart = self._int[:dotplace] or '0'
3584277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson            fracpart = self._int[dotplace:]
3585277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        exp = leftdigits-dotplace
35861ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
3587277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        # done with the decimal-specific stuff;  hand over the rest
3588277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        # of the formatting to the _format_number function
3589277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        return _format_number(self._sign, intpart, fracpart, exp, spec)
35901ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
359172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batistadef _dec_from_triple(sign, coefficient, exponent, special=False):
359272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    """Create a decimal instance directly, without any validation,
359372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    normalization (e.g. removal of leading zeros) or argument
359472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    conversion.
359572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista
359672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    This function is for *internal use only*.
359772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    """
359872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista
359972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    self = object.__new__(Decimal)
360072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    self._sign = sign
360172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    self._int = coefficient
360272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    self._exp = exponent
360372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    self._is_special = special
360472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista
360572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    return self
360672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista
36072c8585b0afb6a39c215a71963e2fadea96f2c6aeRaymond Hettinger# Register Decimal as a kind of Number (an abstract base class).
36082c8585b0afb6a39c215a71963e2fadea96f2c6aeRaymond Hettinger# However, do not register it as Real (because Decimals are not
36092c8585b0afb6a39c215a71963e2fadea96f2c6aeRaymond Hettinger# interoperable with floats).
36102c8585b0afb6a39c215a71963e2fadea96f2c6aeRaymond Hettinger_numbers.Number.register(Decimal)
36112c8585b0afb6a39c215a71963e2fadea96f2c6aeRaymond Hettinger
36122c8585b0afb6a39c215a71963e2fadea96f2c6aeRaymond Hettinger
361359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Context class #######################################################
3614cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
36157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3616cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis# get rounding method function:
361759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batistarounding_functions = [name for name in Decimal.__dict__.keys()
361859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                                    if name.startswith('_round_')]
36197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerfor name in rounding_functions:
362059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
36217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    globalname = name[1:].upper()
36227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    val = globals()[globalname]
36237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Decimal._pick_rounding_function[val] = name
36247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36259ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettingerdel name, val, globalname, rounding_functions
36267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3627ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlanclass _ContextManager(object):
36288b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """Context manager class to support localcontext().
36291a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum
3630ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlan      Sets a copy of the supplied context in __enter__() and restores
36318b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan      the previous decimal context in __exit__()
36328b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """
36331a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum    def __init__(self, new_context):
3634ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlan        self.new_context = new_context.copy()
36351a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum    def __enter__(self):
36361a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum        self.saved_context = getcontext()
36371a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum        setcontext(self.new_context)
36381a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum        return self.new_context
36391a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum    def __exit__(self, t, v, tb):
36401a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum        setcontext(self.saved_context)
36411a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum
36427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Context(object):
36437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Contains the context for a Decimal instance.
36447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Contains:
36467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    prec - precision (for use in rounding, division, square roots..)
364759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    rounding - rounding type (how you round)
3648bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger    traps - If traps[exception] = 1, then the exception is
36497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    raised when it is caused.  Otherwise, a value is
36507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    substituted in.
36511840c1abcade9215faf91b701ab4525ba948d9dcMark Dickinson    flags  - When an exception is caused, flags[exception] is set.
36527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger             (Whether or not the trap_enabler is set)
36537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger             Should be reset by user of Decimal instance.
36540ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettinger    Emin -   Minimum exponent
36550ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettinger    Emax -   Maximum exponent
36567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    capitals -      If 1, 1*10^1 is printed as 1E+1.
36577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    If 0, printed as 1e1
3658e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger    _clamp - If 1, change exponents if too high (Default 0)
36597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
36609ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger
36617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __init__(self, prec=None, rounding=None,
3662abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger                 traps=None, flags=None,
36630ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettinger                 Emin=None, Emax=None,
3664e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger                 capitals=None, _clamp=0,
3665abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger                 _ignored_flags=None):
3666abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger        if flags is None:
3667abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger            flags = []
3668abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger        if _ignored_flags is None:
3669abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger            _ignored_flags = []
3670bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        if not isinstance(flags, dict):
367171f3b85497f25bad3b00555173c51378f64edbb5Mark Dickinson            flags = dict([(s, int(s in flags)) for s in _signals])
3672b91af521fddac47b14c57cd9ba736775334e6379Raymond Hettinger            del s
3673bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        if traps is not None and not isinstance(traps, dict):
367471f3b85497f25bad3b00555173c51378f64edbb5Mark Dickinson            traps = dict([(s, int(s in traps)) for s in _signals])
3675b91af521fddac47b14c57cd9ba736775334e6379Raymond Hettinger            del s
36767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        for name, val in locals().items():
36777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if val is None:
3678eb2608415ee4eb8aaea746f6a313937e264d0cdaRaymond Hettinger                setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
36797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            else:
36807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                setattr(self, name, val)
36817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        del self.self
36827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3683b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger    def __repr__(self):
3684bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        """Show the current context."""
3685b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger        s = []
368659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
368759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
368859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                 % vars(self))
368959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        names = [f.__name__ for f, v in self.flags.items() if v]
369059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        s.append('flags=[' + ', '.join(names) + ']')
369159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        names = [t.__name__ for t, v in self.traps.items() if v]
369259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        s.append('traps=[' + ', '.join(names) + ']')
3693b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger        return ', '.join(s) + ')'
3694b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger
3695d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger    def clear_flags(self):
3696d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger        """Reset all flags to zero"""
3697d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger        for flag in self.flags:
3698b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger            self.flags[flag] = 0
3699d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger
37009fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger    def _shallow_copy(self):
37019fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        """Returns a shallow copy from self."""
3702e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        nc = Context(self.prec, self.rounding, self.traps,
3703e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista                     self.flags, self.Emin, self.Emax,
3704e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista                     self.capitals, self._clamp, self._ignored_flags)
37057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return nc
37069fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger
37079fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger    def copy(self):
37089fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        """Returns a deep copy from self."""
370959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        nc = Context(self.prec, self.rounding, self.traps.copy(),
3710e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista                     self.flags.copy(), self.Emin, self.Emax,
3711e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista                     self.capitals, self._clamp, self._ignored_flags)
37129fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        return nc
37139ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger    __copy__ = copy
37147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37155aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger    def _raise_error(self, condition, explanation = None, *args):
37167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Handles an error
37177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the flag is in _ignored_flags, returns the default response.
37191840c1abcade9215faf91b701ab4525ba948d9dcMark Dickinson        Otherwise, it sets the flag, then, if the corresponding
37207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        trap_enabler is set, it reaises the exception.  Otherwise, it returns
37211840c1abcade9215faf91b701ab4525ba948d9dcMark Dickinson        the default value after setting the flag.
37227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
37235aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger        error = _condition_map.get(condition, condition)
37247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if error in self._ignored_flags:
372559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # Don't touch the flag
37267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return error().handle(self, *args)
37277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37281840c1abcade9215faf91b701ab4525ba948d9dcMark Dickinson        self.flags[error] = 1
3729bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        if not self.traps[error]:
373059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # The errors define how to handle themselves.
37315aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger            return condition().handle(self, *args)
37327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Errors should only be risked on copies of the context
373459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # self._ignored_flags = []
37358aca9d032e7813da9a23fd0771c008aff5a5e62fMark Dickinson        raise error(explanation)
37367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _ignore_all_flags(self):
37387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Ignore all flags, if they are raised"""
3739fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger        return self._ignore_flags(*_signals)
37407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _ignore_flags(self, *flags):
37427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Ignore the flags, if they are raised"""
37437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Do not mutate-- This way, copies of a context leave the original
37447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # alone.
37457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self._ignored_flags = (self._ignored_flags + list(flags))
37467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return list(flags)
37477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _regard_flags(self, *flags):
37497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Stop ignoring the flags, if they are raised"""
37507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if flags and isinstance(flags[0], (tuple,list)):
37517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            flags = flags[0]
37527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        for flag in flags:
37537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self._ignored_flags.remove(flag)
37547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
375553663a695ef2bb96ac0252cd4cc4aa40d4f953beNick Coghlan    # We inherit object.__hash__, so we must deny this explicitly
375653663a695ef2bb96ac0252cd4cc4aa40d4f953beNick Coghlan    __hash__ = None
37575aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger
37587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def Etiny(self):
37597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns Etiny (= Emin - prec + 1)"""
37607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return int(self.Emin - self.prec + 1)
37617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def Etop(self):
3763e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger        """Returns maximum exponent (= Emax - prec + 1)"""
37647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return int(self.Emax - self.prec + 1)
37657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _set_rounding(self, type):
37677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Sets the rounding type.
37687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Sets the rounding type, and returns the current (previous)
37707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding type.  Often used like:
37717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        context = context.copy()
37737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # so you don't change the calling context
37747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # if an error occurs in the middle.
37757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding = context._set_rounding(ROUND_UP)
37767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        val = self.__sub__(other, context=context)
37777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        context._set_rounding(rounding)
37787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        This will make it round up for that operation.
37807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
37817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding = self.rounding
37827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self.rounding= type
37837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return rounding
37847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3785fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger    def create_decimal(self, num='0'):
378659bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson        """Creates a new Decimal instance but using self as context.
378759bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson
378859bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson        This method implements the to-number operation of the
378959bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson        IBM Decimal specification."""
379059bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson
379159bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson        if isinstance(num, basestring) and num != num.strip():
379259bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson            return self._raise_error(ConversionSyntax,
379359bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson                                     "no trailing or leading whitespace is "
379459bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson                                     "permitted.")
379559bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson
37967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        d = Decimal(num, context=self)
3797353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if d._isnan() and len(d._int) > self.prec - self._clamp:
3798353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._raise_error(ConversionSyntax,
3799353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                     "diagnostic info too long in NaN")
3800dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger        return d._fix(self)
38017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3802f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger    def create_decimal_from_float(self, f):
3803f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        """Creates a new Decimal instance from a float but rounding using self
3804f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        as the context.
3805f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger
3806f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        >>> context = Context(prec=5, rounding=ROUND_DOWN)
3807f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        >>> context.create_decimal_from_float(3.1415926535897932)
3808f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        Decimal('3.1415')
3809f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        >>> context = Context(prec=5, traps=[Inexact])
3810f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        >>> context.create_decimal_from_float(3.1415926535897932)
3811f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        Traceback (most recent call last):
3812f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger            ...
3813f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        Inexact: None
3814f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger
3815f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        """
3816f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        d = Decimal.from_float(f)       # An exact conversion
3817f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger        return d._fix(self)             # Apply the context rounding
3818f4d8597a59990c41bc9cc8d499d8bc919d7ebf2dRaymond Hettinger
381959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # Methods
38207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def abs(self, a):
38217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the absolute value of the operand.
38227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
38237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the operand is negative, the result is the same as using the minus
382459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operation on the operand.  Otherwise, the result is the same as using
38257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        the plus operation on the operand.
38267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
38279ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.abs(Decimal('2.1'))
3828abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.1')
38299ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.abs(Decimal('-100'))
3830abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('100')
38319ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.abs(Decimal('101.5'))
3832abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('101.5')
38339ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.abs(Decimal('-101.5'))
3834abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('101.5')
38357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
38367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__abs__(context=self)
38377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
38387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def add(self, a, b):
38397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return the sum of the two operands.
38407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
38419ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
3842abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('19.00')
38439ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
3844abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.02E+4')
38457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
38467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__add__(b, context=self)
38477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
38487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _apply(self, a):
3849dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger        return str(a._fix(self))
38507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3851353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def canonical(self, a):
3852353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the same Decimal object.
3853353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3854353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        As we do not have different encodings for the same number, the
3855353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        received object already is in its canonical form.
3856353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3857353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.canonical(Decimal('2.50'))
3858abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.50')
3859353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3860353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.canonical(context=self)
3861353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
38627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def compare(self, a, b):
38637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Compares values numerically.
38647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
38657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the signs of the operands differ, a value representing each operand
38667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        ('-1' if the operand is less than zero, '0' if the operand is zero or
38677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        negative zero, or '1' if the operand is greater than zero) is used in
38687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        place of that operand for the comparison instead of the actual
38697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        operand.
38707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
38717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The comparison is then effected by subtracting the second operand from
38727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        the first and then returning a value according to the result of the
38737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        subtraction: '-1' if the result is less than zero, '0' if the result is
38747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        zero or negative zero, or '1' if the result is greater than zero.
38757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
38769ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
3877abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1')
38789ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
3879abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
38809ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
3881abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
38829ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
3883abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
38849ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
3885abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
38869ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
3887abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1')
38887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
38897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.compare(b, context=self)
38907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3891353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_signal(self, a, b):
3892353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values of the two operands numerically.
3893353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3894353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        It's pretty much like compare(), but all NaNs signal, with signaling
3895353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        NaNs taking precedence over quiet NaNs.
3896353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3897353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext
3898353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3899abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1')
3900353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3901abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
3902353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.flags[InvalidOperation] = 0
3903353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> print c.flags[InvalidOperation]
3904353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        0
3905353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3906abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('NaN')
3907353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> print c.flags[InvalidOperation]
3908353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        1
3909353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.flags[InvalidOperation] = 0
3910353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> print c.flags[InvalidOperation]
3911353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        0
3912353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3913abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('NaN')
3914353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> print c.flags[InvalidOperation]
3915353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        1
3916353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3917353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.compare_signal(b, context=self)
3918353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3919353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_total(self, a, b):
3920353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares two operands using their abstract representation.
3921353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3922353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        This is not like the standard compare, which use their numerical
3923353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        value. Note that a total ordering is defined for all possible abstract
3924353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        representations.
3925353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3926353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3927abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1')
3928353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('-127'),  Decimal('12'))
3929abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1')
3930353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3931abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1')
3932353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3933abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
3934353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('12.300'))
3935abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
3936353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('NaN'))
3937abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1')
3938353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3939353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.compare_total(b)
3940353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3941353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_total_mag(self, a, b):
3942353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares two operands using their abstract representation ignoring sign.
3943353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3944353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Like compare_total, but with operand's sign ignored and assumed to be 0.
3945353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3946353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.compare_total_mag(b)
3947353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3948353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_abs(self, a):
3949353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy of the operand with the sign set to 0.
3950353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3951353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_abs(Decimal('2.1'))
3952abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.1')
3953353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_abs(Decimal('-100'))
3954abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('100')
3955353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3956353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.copy_abs()
3957353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3958353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_decimal(self, a):
3959353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy of the decimal objet.
3960353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3961353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3962abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.1')
3963353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3964abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1.00')
3965353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
39666c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        return Decimal(a)
3967353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3968353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_negate(self, a):
3969353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy of the operand with the sign inverted.
3970353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3971353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_negate(Decimal('101.5'))
3972abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-101.5')
3973353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3974abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('101.5')
3975353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3976353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.copy_negate()
3977353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3978353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_sign(self, a, b):
3979353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Copies the second operand's sign to the first one.
3980353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3981353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        In detail, it returns a copy of the first operand with the sign
3982353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        equal to the sign of the second operand.
3983353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3984353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3985abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.50')
3986353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3987abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.50')
3988353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3989abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1.50')
3990353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3991abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1.50')
3992353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3993353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.copy_sign(b)
3994353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
39957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def divide(self, a, b):
39967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Decimal division in a specified context.
39977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
39989ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
3999abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.333333333')
40009ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
4001abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.666666667')
40029ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
4003abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.5')
40049ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
4005abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.1')
40069ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
4007abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
40089ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
4009abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('4.00')
40109ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
4011abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.20')
40129ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
4013abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('10')
40149ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
4015abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1000')
40169ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
4017abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.20E+6')
40187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
40197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__div__(b, context=self)
40207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
40217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def divide_int(self, a, b):
40227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Divides two numbers and returns the integer part of the result.
40237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
40249ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
4025abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
40269ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
4027abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('3')
40289ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
4029abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('3')
40307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
40317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__floordiv__(b, context=self)
40327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
40337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def divmod(self, a, b):
40347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__divmod__(b, context=self)
40357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4036353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def exp(self, a):
4037353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns e ** a.
4038353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4039353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4040353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4041353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4042353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('-Infinity'))
4043abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4044353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('-1'))
4045abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.367879441')
4046353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('0'))
4047abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4048353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('1'))
4049abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.71828183')
4050353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('0.693147181'))
4051abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.00000000')
4052353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('+Infinity'))
4053abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('Infinity')
4054353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4055353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.exp(context=self)
4056353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def fma(self, a, b, c):
4058353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a multiplied by b, plus c.
4059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4060353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The first two operands are multiplied together, using multiply,
4061353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        the third operand is then added to the result of that
4062353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        multiplication, using add, all with only one final rounding.
4063353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4064353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
4065abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('22')
4066353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
4067abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-8')
4068353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
4069abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.38435736E+12')
4070353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4071353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.fma(b, c, context=self)
4072353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_canonical(self, a):
40741a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is canonical; otherwise return False.
40751a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista
40761a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        Currently, the encoding of a Decimal instance is always
40771a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        canonical, so this method returns True for any Decimal.
4078353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4079353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_canonical(Decimal('2.50'))
40801a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
4081353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
40821a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return a.is_canonical()
4083353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4084353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_finite(self, a):
40851a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is finite; otherwise return False.
4086353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
40871a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        A Decimal instance is considered finite if it is neither
40881a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        infinite nor a NaN.
4089353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4090353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('2.50'))
40911a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
4092353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('-0.3'))
40931a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
4094353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('0'))
40951a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
4096353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('Inf'))
40971a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4098353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('NaN'))
40991a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4100353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4101353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_finite()
4102353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4103353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_infinite(self, a):
41041a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is infinite; otherwise return False.
4105353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4106353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_infinite(Decimal('2.50'))
41071a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4108353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_infinite(Decimal('-Inf'))
41091a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
4110353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_infinite(Decimal('NaN'))
41111a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4112353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4113353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_infinite()
4114353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4115353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_nan(self, a):
41161a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is a qNaN or sNaN;
41171a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        otherwise return False.
4118353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4119353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_nan(Decimal('2.50'))
41201a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4121353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_nan(Decimal('NaN'))
41221a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
4123353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_nan(Decimal('-sNaN'))
41241a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
4125353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4126353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_nan()
4127353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4128353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_normal(self, a):
41291a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is a normal number;
41301a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        otherwise return False.
4131353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4132353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4133353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4134353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4135353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('2.50'))
41361a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
4137353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('0.1E-999'))
41381a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4139353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('0.00'))
41401a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4141353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('-Inf'))
41421a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4143353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('NaN'))
41441a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4145353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4146353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_normal(context=self)
4147353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4148353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_qnan(self, a):
41491a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is a quiet NaN; otherwise return False.
4150353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4151353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_qnan(Decimal('2.50'))
41521a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4153353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_qnan(Decimal('NaN'))
41541a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
4155353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_qnan(Decimal('sNaN'))
41561a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4157353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4158353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_qnan()
4159353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4160353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_signed(self, a):
41611a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is negative; otherwise return False.
4162353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4163353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_signed(Decimal('2.50'))
41641a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4165353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_signed(Decimal('-12'))
41661a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
4167353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_signed(Decimal('-0'))
41681a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
4169353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4170353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_signed()
4171353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4172353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_snan(self, a):
41731a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is a signaling NaN;
41741a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        otherwise return False.
4175353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4176353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_snan(Decimal('2.50'))
41771a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4178353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_snan(Decimal('NaN'))
41791a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4180353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_snan(Decimal('sNaN'))
41811a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
4182353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4183353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_snan()
4184353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4185353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_subnormal(self, a):
41861a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is subnormal; otherwise return False.
4187353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4188353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4189353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4190353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4191353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('2.50'))
41921a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4193353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('0.1E-999'))
41941a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
4195353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('0.00'))
41961a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4197353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('-Inf'))
41981a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4199353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('NaN'))
42001a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4201353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4202353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_subnormal(context=self)
4203353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4204353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_zero(self, a):
42051a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is a zero; otherwise return False.
4206353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4207353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_zero(Decimal('0'))
42081a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
4209353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_zero(Decimal('2.50'))
42101a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4211353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_zero(Decimal('-0E+2'))
42121a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
4213353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4214353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_zero()
4215353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4216353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def ln(self, a):
4217353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the natural (base e) logarithm of the operand.
4218353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4219353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4220353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4221353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4222353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('0'))
4223abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-Infinity')
4224353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('1.000'))
4225abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4226353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('2.71828183'))
4227abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.00000000')
4228353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('10'))
4229abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.30258509')
4230353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('+Infinity'))
4231abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('Infinity')
4232353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4233353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.ln(context=self)
4234353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4235353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def log10(self, a):
4236353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the base 10 logarithm of the operand.
4237353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4238353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4239353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4240353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4241353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('0'))
4242abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-Infinity')
4243353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('0.001'))
4244abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-3')
4245353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('1.000'))
4246abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4247353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('2'))
4248abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.301029996')
4249353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('10'))
4250abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4251353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('70'))
4252abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.84509804')
4253353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('+Infinity'))
4254abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('Infinity')
4255353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4256353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.log10(context=self)
4257353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4258353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logb(self, a):
4259353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """ Returns the exponent of the magnitude of the operand's MSD.
4260353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4261353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result is the integer which is the exponent of the magnitude
4262353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        of the most significant digit of the operand (as though the
4263353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        operand were truncated to a single digit while maintaining the
4264353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        value of that digit and without limiting the resulting exponent).
4265353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4266353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logb(Decimal('250'))
4267abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2')
4268353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logb(Decimal('2.50'))
4269abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4270353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logb(Decimal('0.03'))
4271abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-2')
4272353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logb(Decimal('0'))
4273abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-Infinity')
4274353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4275353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logb(context=self)
4276353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4277353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_and(self, a, b):
4278353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies the logical operation 'and' between each operand's digits.
4279353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4280353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The operands must be both logical numbers.
4281353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4282353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4283abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4284353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4285abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4286353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4287abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4288353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4289abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4290353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4291abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1000')
4292353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4293abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('10')
4294353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4295353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logical_and(b, context=self)
4296353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4297353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_invert(self, a):
4298353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Invert all the digits in the operand.
4299353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4300353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The operand must be a logical number.
4301353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4302353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_invert(Decimal('0'))
4303abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('111111111')
4304353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_invert(Decimal('1'))
4305abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('111111110')
4306353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_invert(Decimal('111111111'))
4307abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4308353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_invert(Decimal('101010101'))
4309abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('10101010')
4310353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4311353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logical_invert(context=self)
4312353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4313353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_or(self, a, b):
4314353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies the logical operation 'or' between each operand's digits.
4315353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4316353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The operands must be both logical numbers.
4317353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4318353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4319abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4320353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4321abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4322353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4323abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4324353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4325abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4326353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4327abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1110')
4328353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4329abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1110')
4330353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4331353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logical_or(b, context=self)
4332353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4333353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_xor(self, a, b):
4334353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies the logical operation 'xor' between each operand's digits.
4335353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4336353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The operands must be both logical numbers.
4337353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4338353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4339abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4340353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4341abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4342353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4343abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4344353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4345abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4346353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4347abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('110')
4348353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4349abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1101')
4350353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4351353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logical_xor(b, context=self)
4352353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
43537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def max(self, a,b):
43547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """max compares two values numerically and returns the maximum.
43557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
43567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If either operand is a NaN then the general rules apply.
4357c8acc882a92c1fe5df95ae73b7b8004737ed9222Andrew M. Kuchling        Otherwise, the operands are compared as though by the compare
435859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operation.  If they are numerically equal then the left-hand operand
435959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        is chosen as the result.  Otherwise the maximum (closer to positive
43607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        infinity) of the two operands is chosen as the result.
43617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
43629ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
4363abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('3')
43649ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
4365abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('3')
43669ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
4367abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4368d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4369abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('7')
43707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
43717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.max(b, context=self)
43727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4373353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def max_mag(self, a, b):
4374353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values numerically with their sign ignored."""
4375353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.max_mag(b, context=self)
4376353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
43777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def min(self, a,b):
43787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """min compares two values numerically and returns the minimum.
43797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
43807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If either operand is a NaN then the general rules apply.
4381c8acc882a92c1fe5df95ae73b7b8004737ed9222Andrew M. Kuchling        Otherwise, the operands are compared as though by the compare
438259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operation.  If they are numerically equal then the left-hand operand
438359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        is chosen as the result.  Otherwise the minimum (closer to negative
43847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        infinity) of the two operands is chosen as the result.
43857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
43869ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
4387abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2')
43889ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
4389abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-10')
43909ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
4391abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.0')
4392d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4393abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('7')
43947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
43957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.min(b, context=self)
43967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4397353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def min_mag(self, a, b):
4398353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values numerically with their sign ignored."""
4399353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.min_mag(b, context=self)
4400353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
44017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def minus(self, a):
44027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Minus corresponds to unary prefix minus in Python.
44037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The operation is evaluated using the same rules as subtract; the
44057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        operation minus(a) is calculated as subtract('0', a) where the '0'
44067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        has the same exponent as the operand.
44077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44089ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.minus(Decimal('1.3'))
4409abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1.3')
44109ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.minus(Decimal('-1.3'))
4411abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.3')
44127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
44137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__neg__(context=self)
44147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def multiply(self, a, b):
44167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """multiply multiplies two operands.
44177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4418cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis        If either operand is a special value then the general rules apply.
4419cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis        Otherwise, the operands are multiplied together ('long multiplication'),
4420cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis        resulting in a number which may be as long as the sum of the lengths
4421cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis        of the two operands.
44227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44239ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
4424abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('3.60')
44259ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
4426abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('21')
44279ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
4428abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.72')
44299ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
4430abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0.0')
44319ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
4432abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('4.28135971E+11')
44337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
44347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__mul__(b, context=self)
44357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4436353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_minus(self, a):
4437353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the largest representable number smaller than a.
4438353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4439353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4440353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4441353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4442353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.next_minus(Decimal('1'))
4443abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.999999999')
4444353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_minus(Decimal('1E-1007'))
4445abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0E-1007')
4446353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4447abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1.00000004')
4448353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_minus(Decimal('Infinity'))
4449abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('9.99999999E+999')
4450353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4451353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.next_minus(context=self)
4452353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4453353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_plus(self, a):
4454353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the smallest representable number larger than a.
4455353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4456353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4457353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4458353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4459353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.next_plus(Decimal('1'))
4460abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.00000001')
4461353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_plus(Decimal('-1E-1007'))
4462abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0E-1007')
4463353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4464abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1.00000002')
4465353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_plus(Decimal('-Infinity'))
4466abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-9.99999999E+999')
4467353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4468353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.next_plus(context=self)
4469353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4470353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_toward(self, a, b):
4471353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the number closest to a, in direction towards b.
4472353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4473353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result is the closest representable number from the first
4474353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        operand (but not the first operand) that is in the direction
4475353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        towards the second operand, unless the operands have the same
4476353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        value.
4477353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4478353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4479353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4480353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4481353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('1'), Decimal('2'))
4482abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.00000001')
4483353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4484abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0E-1007')
4485353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4486abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1.00000002')
4487353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('1'), Decimal('0'))
4488abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.999999999')
4489353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4490abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0E-1007')
4491353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4492abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1.00000004')
4493353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4494abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0.00')
4495353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4496353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.next_toward(b, context=self)
4497353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
44987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def normalize(self, a):
4499e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger        """normalize reduces an operand to its simplest form.
45007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Essentially a plus operation with all trailing zeros removed from the
45027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        result.
45037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45049ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('2.1'))
4505abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.1')
45069ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('-2.0'))
4507abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-2')
45089ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('1.200'))
4509abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.2')
45109ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('-120'))
4511abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1.2E+2')
45129ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('120.00'))
4513abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.2E+2')
45149ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('0.00'))
4515abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
45167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
45177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.normalize(context=self)
45187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4519353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def number_class(self, a):
4520353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns an indication of the class of the operand.
4521353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4522353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The class is one of the following strings:
4523353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -sNaN
4524353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -NaN
4525353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Infinity
4526353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Normal
4527353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Subnormal
4528353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Zero
4529353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Zero
4530353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Subnormal
4531353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Normal
4532353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Infinity
4533353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4534353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = Context(ExtendedContext)
4535353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4536353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4537353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('Infinity'))
4538353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Infinity'
4539353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('1E-10'))
4540353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Normal'
4541353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('2.50'))
4542353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Normal'
4543353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('0.1E-999'))
4544353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Subnormal'
4545353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('0'))
4546353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Zero'
4547353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-0'))
4548353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Zero'
4549353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-0.1E-999'))
4550353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Subnormal'
4551353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-1E-10'))
4552353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Normal'
4553353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-2.50'))
4554353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Normal'
4555353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-Infinity'))
4556353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Infinity'
4557353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('NaN'))
4558353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        'NaN'
4559353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-NaN'))
4560353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        'NaN'
4561353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('sNaN'))
4562353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        'sNaN'
4563353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4564353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.number_class(context=self)
4565353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
45667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def plus(self, a):
45677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Plus corresponds to unary prefix plus in Python.
45687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The operation is evaluated using the same rules as add; the
45707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        operation plus(a) is calculated as add('0', a) where the '0'
45717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        has the same exponent as the operand.
45727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45739ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.plus(Decimal('1.3'))
4574abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.3')
45759ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.plus(Decimal('-1.3'))
4576abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1.3')
45777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
45787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__pos__(context=self)
45797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def power(self, a, b, modulo=None):
45817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Raises a to the power of b, to modulo if given.
45827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4583353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        With two arguments, compute a**b.  If a is negative then b
4584353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        must be integral.  The result will be inexact unless b is
4585353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        integral and the result is finite and can be expressed exactly
4586353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        in 'precision' digits.
4587353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4588353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        With three arguments, compute (a**b) % modulo.  For the
4589353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        three argument form, the following restrictions on the
4590353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        arguments hold:
4591353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4592353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - all three arguments must be integral
4593353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - b must be nonnegative
4594353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - at least one of a or b must be nonzero
4595353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - modulo must be nonzero and have at most 'precision' digits
4596353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4597353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result of pow(a, b, modulo) is identical to the result
4598353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        that would be obtained by computing (a**b) % modulo with
4599353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        unbounded precision, but is computed more efficiently.  It is
4600353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        always exact.
4601353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4602353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4603353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4604353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4605353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('2'), Decimal('3'))
4606abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('8')
4607353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-2'), Decimal('3'))
4608abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-8')
4609353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('2'), Decimal('-3'))
4610abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.125')
4611353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('1.7'), Decimal('8'))
4612abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('69.7575744')
4613353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('10'), Decimal('0.301029996'))
4614abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.00000000')
4615353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('Infinity'), Decimal('-1'))
4616abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4617353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('Infinity'), Decimal('0'))
4618abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4619353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('Infinity'), Decimal('1'))
4620abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('Infinity')
4621353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-Infinity'), Decimal('-1'))
4622abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0')
4623353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-Infinity'), Decimal('0'))
4624abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4625353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-Infinity'), Decimal('1'))
4626abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-Infinity')
4627353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-Infinity'), Decimal('2'))
4628abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('Infinity')
4629353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('0'), Decimal('0'))
4630abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('NaN')
4631353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4632353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4633abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('11')
4634353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4635abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-11')
4636353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4637abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4638353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4639abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('11')
4640353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4641abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('11729830')
4642353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4643abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0')
4644353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4645abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
46467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
46477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__pow__(b, modulo, context=self)
46487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def quantize(self, a, b):
465059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
46517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The coefficient of the result is derived from that of the left-hand
465359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operand.  It may be rounded using the current rounding setting (if the
46547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exponent is being increased), multiplied by a positive power of ten (if
46557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        the exponent is being decreased), or is unchanged (if the exponent is
46567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        already equal to that of the right-hand operand).
46577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Unlike other operations, if the length of the coefficient after the
46597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        quantize operation would be greater than precision then an Invalid
466059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operation condition is raised.  This guarantees that, unless there is
466159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        an error condition, the exponent of the result of a quantize is always
46627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        equal to that of the right-hand operand.
46637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Also unlike other operations, quantize will never raise Underflow, even
46657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if the result is subnormal and inexact.
46667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46679ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
4668abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.170')
46699ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
4670abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.17')
46719ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
4672abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.2')
46739ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
4674abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2')
46759ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
4676abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0E+1')
46779ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
4678abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-Infinity')
46799ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
4680abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('NaN')
46819ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
4682abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0')
46839ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
4684abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0E+5')
46859ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
4686abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('NaN')
46879ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
4688abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('NaN')
46899ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
4690abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('217.0')
46919ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
4692abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('217')
46939ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
4694abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.2E+2')
46959ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
4696abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2E+2')
46977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
46987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.quantize(b, context=self)
46997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4700353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def radix(self):
4701353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Just returns 10, as this is Decimal, :)
4702353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4703353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.radix()
4704abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('10')
4705353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4706353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal(10)
4707353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
47087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def remainder(self, a, b):
47097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the remainder from integer division.
47107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The result is the residue of the dividend after the operation of
471259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        calculating integer division as described for divide-integer, rounded
47130d4c06e06e5ee1f3bb1fa8068114bd700d74864aNeal Norwitz        to precision digits if necessary.  The sign of the result, if
471459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        non-zero, is the same as that of the original dividend.
47157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        This operation will fail under the same conditions as integer division
47177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        (that is, if integer division on the same two operands would fail, the
47187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        remainder cannot be calculated).
47197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47209ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
4721abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.1')
47229ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
4723abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
47249ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
4725abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1')
47269ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
4727abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.2')
47289ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
4729abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.1')
47309ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
4731abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.0')
47327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
47337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__mod__(b, context=self)
47347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def remainder_near(self, a, b):
47367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns to be "a - b * n", where n is the integer nearest the exact
47377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        value of "x / b" (if two integers are equally near then the even one
473859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        is chosen).  If the result is equal to 0 then its sign will be the
47397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        sign of a.
47407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        This operation will fail under the same conditions as integer division
47427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        (that is, if integer division on the same two operands would fail, the
47437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        remainder cannot be calculated).
47447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47459ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
4746abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0.9')
47479ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
4748abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-2')
47499ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
4750abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
47519ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
4752abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1')
47539ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
4754abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.2')
47559ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
4756abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.1')
47579ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
4758abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0.3')
47597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
47607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.remainder_near(b, context=self)
47617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4762353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def rotate(self, a, b):
4763353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a rotated copy of a, b times.
4764353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4765353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The coefficient of the result is a rotated copy of the digits in
4766353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        the coefficient of the first operand.  The number of places of
4767353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotation is taken from the absolute value of the second operand,
4768353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        with the rotation being to the left if the second operand is
4769353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        positive or to the right otherwise.
4770353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4771353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4772abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('400000003')
4773353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4774abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('12')
4775353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4776abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('891234567')
4777353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4778abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('123456789')
4779353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4780abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('345678912')
4781353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4782353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.rotate(b, context=self)
4783353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
47847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def same_quantum(self, a, b):
47857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns True if the two operands have the same exponent.
47867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The result is never affected by either the sign or the coefficient of
47887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        either operand.
47897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47909ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
47917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        False
47929ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
47937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        True
47949ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
47957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        False
47969ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
47977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        True
47987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
47997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.same_quantum(b)
48007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4801353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def scaleb (self, a, b):
4802353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the first operand after adding the second value its exp.
4803353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4804353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4805abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.0750')
4806353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4807abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('7.50')
4808353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4809abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('7.50E+3')
4810353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4811353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.scaleb (b, context=self)
4812353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4813353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def shift(self, a, b):
4814353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a shifted copy of a, b times.
4815353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4816353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The coefficient of the result is a shifted copy of the digits
4817353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        in the coefficient of the first operand.  The number of places
4818353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        to shift is taken from the absolute value of the second operand,
4819353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        with the shift being to the left if the second operand is
4820353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        positive or to the right otherwise.  Digits shifted into the
4821353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        coefficient are zeros.
4822353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4823353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4824abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('400000000')
4825353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4826abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4827353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4828abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1234567')
4829353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4830abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('123456789')
4831353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4832abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('345678900')
4833353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4834353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.shift(b, context=self)
4835353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
48367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def sqrt(self, a):
483759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        """Square root of a non-negative number to context precision.
48387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
48397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the result must be inexact, it is rounded using the round-half-even
48407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        algorithm.
48417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
48429ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('0'))
4843abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
48449ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('-0'))
4845abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0')
48469ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('0.39'))
4847abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.624499800')
48489ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('100'))
4849abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('10')
48509ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('1'))
4851abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
48529ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('1.0'))
4853abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.0')
48549ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('1.00'))
4855abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.0')
48569ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('7'))
4857abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.64575131')
48589ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('10'))
4859abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('3.16227766')
48609ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.prec
48616ea484582238a65d44a76e3a831e3ba7c77a1a25Raymond Hettinger        9
48627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
48637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.sqrt(context=self)
48647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
48657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def subtract(self, a, b):
4866f33d01d304c349a7f555779c7c99930f1203adb7Georg Brandl        """Return the difference between the two operands.
48677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
48689ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
4869abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.23')
48709ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
4871abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.00')
48729ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
4873abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0.77')
48747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
48757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__sub__(b, context=self)
48767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
48777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def to_eng_string(self, a):
48787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Converts a number to a string, using scientific notation.
48797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
48807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The operation is not affected by the context.
48817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
48827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.to_eng_string(context=self)
48837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
48847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def to_sci_string(self, a):
48857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Converts a number to a string, using scientific notation.
48867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
48877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The operation is not affected by the context.
48887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
48897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__str__(context=self)
48907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4891353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def to_integral_exact(self, a):
4892353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds to an integer.
4893353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4894353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        When the operand has a negative exponent, the result is the same
4895353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        as using the quantize() operation using the given operand as the
4896353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4897353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        of the operand as the precision setting; Inexact and Rounded flags
4898353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        are allowed in this operation.  The rounding mode is taken from the
4899353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.
4900353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4901353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4902abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2')
4903353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('100'))
4904abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('100')
4905353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4906abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('100')
4907353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4908abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('102')
4909353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4910abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-102')
4911353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4912abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.0E+6')
4913353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4914abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('7.89E+77')
4915353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4916abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-Infinity')
4917353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4918353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.to_integral_exact(context=self)
4919353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4920353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def to_integral_value(self, a):
49217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Rounds to an integer.
49227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
49237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        When the operand has a negative exponent, the result is the same
49247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        as using the quantize() operation using the given operand as the
49257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        left-hand-operand, 1E+0 as the right-hand-operand, and the precision
49267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        of the operand as the precision setting, except that no flags will
492759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        be set.  The rounding mode is taken from the context.
49287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4929353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('2.1'))
4930abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2')
4931353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('100'))
4932abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('100')
4933353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('100.0'))
4934abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('100')
4935353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('101.5'))
4936abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('102')
4937353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
4938abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-102')
4939353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
4940abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.0E+6')
4941353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
4942abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('7.89E+77')
4943353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
4944abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-Infinity')
49457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
4946353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.to_integral_value(context=self)
4947353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4948353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # the method name changed, but we provide also the old one, for compatibility
4949353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    to_integral = to_integral_value
49507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
49517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass _WorkRep(object):
49527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __slots__ = ('sign','int','exp')
495317931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger    # sign: 0 or 1
4954636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    # int:  int or long
49557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    # exp:  None, int, or string
49567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
49577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __init__(self, value=None):
49587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if value is None:
49597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.sign = None
4960636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self.int = 0
49617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.exp = None
496217931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        elif isinstance(value, Decimal):
496317931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            self.sign = value._sign
496472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self.int = int(value._int)
49657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.exp = value._exp
496617931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        else:
496717931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            # assert isinstance(value, tuple)
49687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.sign = value[0]
49697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.int = value[1]
49707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.exp = value[2]
49717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
49727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __repr__(self):
49737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
49747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
49757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __str__ = __repr__
49767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
49777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
49787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4979e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batistadef _normalize(op1, op2, prec = 0):
49807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Normalizes op1, op2 to have the same exp and length of coefficient.
49817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
49827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Done during addition.
49837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
4984353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if op1.exp < op2.exp:
49857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        tmp = op2
49867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        other = op1
49877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    else:
49887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        tmp = op1
49897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        other = op2
49907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4991353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4992353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Then adding 10**exp to tmp has the same effect (after rounding)
4993353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # as adding any positive quantity smaller than 10**exp; similarly
4994353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # for subtraction.  So if other is smaller than 10**exp we replace
4995353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # it with 10**exp.  This avoids tmp.exp - other.exp getting too large.
4996e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista    tmp_len = len(str(tmp.int))
4997e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista    other_len = len(str(other.int))
4998e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista    exp = tmp.exp + min(-1, tmp_len - prec - 2)
4999e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista    if other_len + other.exp - 1 < exp:
5000e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        other.int = 1
5001e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        other.exp = exp
5002636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
5003353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    tmp.int *= 10 ** (tmp.exp - other.exp)
5004353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    tmp.exp = other.exp
50057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    return op1, op2
50067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
5007353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
5008353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5009353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# This function from Tim Peters was taken from here:
5010353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# http://mail.python.org/pipermail/python-list/1999-July/007758.html
5011353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# The correction being in the function definition is for speed, and
5012353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# the whole function is not resolved with math.log because of avoiding
5013353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# the use of floats.
5014353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _nbits(n, correction = {
5015353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '0': 4, '1': 3, '2': 2, '3': 2,
5016353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '4': 1, '5': 1, '6': 1, '7': 1,
5017353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '8': 0, '9': 0, 'a': 0, 'b': 0,
5018353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        'c': 0, 'd': 0, 'e': 0, 'f': 0}):
5019353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Number of bits in binary representation of the positive integer n,
5020353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    or 0 if n == 0.
5021353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
5022353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if n < 0:
5023353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        raise ValueError("The argument to _nbits should be nonnegative.")
5024353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    hex_n = "%x" % n
5025353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return 4*len(hex_n) - correction[hex_n[0]]
5026353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5027353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _sqrt_nearest(n, a):
5028353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Closest integer to the square root of the positive integer n.  a is
5029353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    an initial approximation to the square root.  Any positive integer
5030353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    will do for a, but the closer a is to the square root of n the
5031353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    faster convergence will be.
5032353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5033353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
5034353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if n <= 0 or a <= 0:
5035353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5036353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5037353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    b=0
5038353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    while a != b:
5039353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        b, a = a, a--n//a>>1
5040353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return a
5041353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5042353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _rshift_nearest(x, shift):
5043353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given an integer x and a nonnegative integer shift, return closest
5044353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    integer to x / 2**shift; use round-to-even in case of a tie.
5045353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5046353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
5047353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    b, q = 1L << shift, x >> shift
5048353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return q + (2*(x & (b-1)) + (q&1) > b)
5049353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5050353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _div_nearest(a, b):
5051353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Closest integer to a/b, a and b positive integers; rounds to even
5052353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    in the case of a tie.
5053353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5054353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
5055353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    q, r = divmod(a, b)
5056353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return q + (2*r + (q&1) > b)
5057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5058353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _ilog(x, M, L = 8):
5059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Integer approximation to M*log(x/M), with absolute error boundable
5060353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    in terms only of x/M.
5061353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5062353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    Given positive integers x and M, return an integer approximation to
5063353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    M * log(x/M).  For L = 8 and 0.1 <= x/M <= 10 the difference
5064353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    between the approximation and the exact result is at most 22.  For
5065353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15.  In
5066353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    both cases these are upper bounds on the error; it will usually be
5067353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    much smaller."""
5068353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5069353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # The basic algorithm is the following: let log1p be the function
5070353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # log1p(x) = log(1+x).  Then log(x/M) = log1p((x-M)/M).  We use
5071353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # the reduction
5072353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
5073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #    log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5074353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
5075353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # repeatedly until the argument to log1p is small (< 2**-L in
5076353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # absolute value).  For small y we can use the Taylor series
5077353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # expansion
5078353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
5079353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #    log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5080353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
5081353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # truncating at T such that y**T is small enough.  The whole
5082353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # computation is carried out in a form of fixed-point arithmetic,
5083353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # with a real number z being represented by an integer
5084353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # approximation to z*M.  To avoid loss of precision, the y below
5085353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # is actually an integer approximation to 2**R*y*M, where R is the
5086353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # number of reductions performed so far.
5087353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5088353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    y = x-M
5089353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # argument reduction; R = number of reductions performed
5090353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    R = 0
5091353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    while (R <= L and long(abs(y)) << L-R >= M or
5092353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista           R > L and abs(y) >> R-L >= M):
5093353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        y = _div_nearest(long(M*y) << 1,
5094353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                         M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5095353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        R += 1
5096353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5097353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Taylor series with T terms
5098353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    T = -int(-10*len(str(M))//(3*L))
5099353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    yshift = _rshift_nearest(y, R)
5100353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    w = _div_nearest(M, T)
5101353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    for k in xrange(T-1, 0, -1):
5102353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5103353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5104353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return _div_nearest(w*y, M)
5105353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5106353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _dlog10(c, e, p):
5107353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given integers c, e and p with c > 0, p >= 0, compute an integer
5108353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    approximation to 10**p * log10(c*10**e), with an absolute error of
5109353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    at most 1.  Assumes that c*10**e is not exactly 1."""
5110353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5111353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # increase precision by 2; compensate for this by dividing
5112353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # final result by 100
5113353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    p += 2
5114353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5115353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # write c*10**e as d*10**f with either:
5116353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #   f >= 0 and 1 <= d <= 10, or
5117353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #   f <= 0 and 0.1 <= d <= 1.
5118353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Thus for c*10**e close to 1, f = 0
5119353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    l = len(str(c))
5120353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    f = e+l - (e+l >= 1)
5121353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5122353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if p > 0:
5123353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        M = 10**p
5124353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        k = e+p-f
5125353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if k >= 0:
5126353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c *= 10**k
5127353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
5128353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = _div_nearest(c, 10**-k)
5129353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5130353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = _ilog(c, M) # error < 5 + 22 = 27
5131be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        log_10 = _log10_digits(p) # error < 1
5132353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = _div_nearest(log_d*M, log_10)
5133353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_tenpower = f*M # exact
5134353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
5135353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = 0  # error < 2.31
513618aa388ca084e1d40aa48c8c8f1b4f730c6fe059Neal Norwitz        log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
5137353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5138353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return _div_nearest(log_tenpower+log_d, 100)
5139353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5140353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _dlog(c, e, p):
5141353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given integers c, e and p with c > 0, compute an integer
5142353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    approximation to 10**p * log(c*10**e), with an absolute error of
5143353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    at most 1.  Assumes that c*10**e is not exactly 1."""
5144353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5145353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Increase precision by 2. The precision increase is compensated
5146353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # for at the end with a division by 100.
5147353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    p += 2
5148353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5149353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5150353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # or f <= 0 and 0.1 <= d <= 1.  Then we can compute 10**p * log(c*10**e)
5151353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # as 10**p * log(d) + 10**p*f * log(10).
5152353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    l = len(str(c))
5153353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    f = e+l - (e+l >= 1)
5154353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5155353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # compute approximation to 10**p*log(d), with error < 27
5156353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if p > 0:
5157353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        k = e+p-f
5158353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if k >= 0:
5159353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c *= 10**k
5160353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
5161353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = _div_nearest(c, 10**-k)  # error of <= 0.5 in c
5162353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5163353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # _ilog magnifies existing error in c by a factor of at most 10
5164353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5165353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
5166353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # p <= 0: just approximate the whole thing by 0; error < 2.31
5167353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = 0
5168353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5169be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    # compute approximation to f*10**p*log(10), with error < 11.
5170353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if f:
5171be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        extra = len(str(abs(f)))-1
5172be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        if p + extra >= 0:
5173be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5174be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5175be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
5176353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
5177353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            f_log_ten = 0
5178353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
5179353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        f_log_ten = 0
5180353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5181be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
5182353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return _div_nearest(f_log_ten + log_d, 100)
5183353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5184be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batistaclass _Log10Memoize(object):
5185be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    """Class to compute, store, and allow retrieval of, digits of the
5186be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    constant log(10) = 2.302585....  This constant is needed by
5187be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5188be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    def __init__(self):
5189be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        self.digits = "23025850929940456840179914546843642076011014886"
5190be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista
5191be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    def getdigits(self, p):
5192be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        """Given an integer p >= 0, return floor(10**p)*log(10).
5193be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista
5194be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        For example, self.getdigits(3) returns 2302.
5195be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        """
5196be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        # digits are stored as a string, for quick conversion to
5197be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        # integer in the case that we've already computed enough
5198be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        # digits; the stored digits should always be correct
5199be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        # (truncated, not rounded to nearest).
5200be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        if p < 0:
5201be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            raise ValueError("p should be nonnegative")
5202be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista
5203be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        if p >= len(self.digits):
5204be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # compute p+3, p+6, p+9, ... digits; continue until at
5205be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # least one of the extra digits is nonzero
5206be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            extra = 3
5207be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            while True:
5208be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                # compute p+extra digits, correct to within 1ulp
5209be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                M = 10**(p+extra+2)
5210be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                digits = str(_div_nearest(_ilog(10*M, M), 100))
5211be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                if digits[-extra:] != '0'*extra:
5212be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                    break
5213be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                extra += 3
5214be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # keep all reliable digits so far; remove trailing zeros
5215be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # and next nonzero digit
5216be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            self.digits = digits.rstrip('0')[:-1]
5217be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        return int(self.digits[:p+1])
5218be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista
5219be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista_log10_digits = _Log10Memoize().getdigits
5220be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista
5221353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _iexp(x, M, L=8):
5222353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given integers x and M, M > 0, such that x/M is small in absolute
5223353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    value, compute an integer approximation to M*exp(x/M).  For 0 <=
5224353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5225353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    is usually much smaller)."""
5226353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5227353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Algorithm: to compute exp(z) for a real number z, first divide z
5228353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # by a suitable power R of 2 so that |z/2**R| < 2**-L.  Then
5229353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5230353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # series
5231353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
5232353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #     expm1(x) = x + x**2/2! + x**3/3! + ...
5233353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
5234353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Now use the identity
5235353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
5236353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #     expm1(2x) = expm1(x)*(expm1(x)+2)
5237353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
5238353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # R times to compute the sequence expm1(z/2**R),
5239353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5240353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5241353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Find R such that x/2**R/M <= 2**-L
5242353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    R = _nbits((long(x)<<L)//M)
5243353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5244353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Taylor series.  (2**L)**T > M
5245353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    T = -int(-10*len(str(M))//(3*L))
5246353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    y = _div_nearest(x, T)
5247353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    Mshift = long(M)<<R
5248353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    for i in xrange(T-1, 0, -1):
5249353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        y = _div_nearest(x*(Mshift + y), Mshift * i)
5250353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5251353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Expansion
5252353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    for k in xrange(R-1, -1, -1):
5253353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Mshift = long(M)<<(k+2)
5254353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        y = _div_nearest(y*(y+Mshift), Mshift)
5255353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5256353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return M+y
5257353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5258353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _dexp(c, e, p):
5259353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Compute an approximation to exp(c*10**e), with p decimal places of
5260353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    precision.
5261353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5262be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    Returns integers d, f such that:
5263353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5264353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista      10**(p-1) <= d <= 10**p, and
5265353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista      (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5266353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5267353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    In other words, d*10**f is an approximation to exp(c*10**e) with p
5268353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    digits of precision, and with an error in d of at most 1.  This is
5269353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    almost, but not quite, the same as the error being < 1ulp: when d
5270353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    = 10**(p-1) the error could be up to 10 ulp."""
5271353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5272353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5273353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    p += 2
5274353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5275be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    # compute log(10) with extra precision = adjusted exponent of c*10**e
5276353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    extra = max(0, e + len(str(c)) - 1)
5277353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    q = p + extra
5278353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5279be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
5280353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # rounding down
5281353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    shift = e+q
5282353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if shift >= 0:
5283353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        cshift = c*10**shift
5284353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
5285353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        cshift = c//10**-shift
5286be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    quot, rem = divmod(cshift, _log10_digits(q))
5287353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5288353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # reduce remainder back to original precision
5289353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    rem = _div_nearest(rem, 10**extra)
5290353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5291353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # error in result of _iexp < 120;  error after division < 0.62
5292353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5293353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5294353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _dpower(xc, xe, yc, ye, p):
5295353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5296353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    y = yc*10**ye, compute x**y.  Returns a pair of integers (c, e) such that:
5297353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5298353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista      10**(p-1) <= c <= 10**p, and
5299353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista      (c-1)*10**e < x**y < (c+1)*10**e
5300353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5301353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    in other words, c*10**e is an approximation to x**y with p digits
5302353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    of precision, and with an error in c of at most 1.  (This is
5303353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    almost, but not quite, the same as the error being < 1ulp: when c
5304353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    == 10**(p-1) we can only guarantee error < 10ulp.)
5305353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5306353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    We assume that: x is positive and not equal to 1, and y is nonzero.
5307353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
5308353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5309353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Find b such that 10**(b-1) <= |y| <= 10**b
5310353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    b = len(str(abs(yc))) + ye
5311353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5312353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5313353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    lxc = _dlog(xc, xe, p+b+1)
5314353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5315353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5316353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    shift = ye-b
5317353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if shift >= 0:
5318353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        pc = lxc*yc*10**shift
5319353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
5320353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        pc = _div_nearest(lxc*yc, 10**-shift)
5321353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5322353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if pc == 0:
5323353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # we prefer a result that isn't exactly 1; this makes it
5324353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # easier to compute a correctly rounded result in __pow__
5325353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5326353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            coeff, exp = 10**(p-1)+1, 1-p
5327353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
5328353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            coeff, exp = 10**p-1, -p
5329353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
5330353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        coeff, exp = _dexp(pc, -(p+1), p+1)
5331353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        coeff = _div_nearest(coeff, 10)
5332353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exp += 1
5333353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5334353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return coeff, exp
5335353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5336353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _log10_lb(c, correction = {
5337353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5338353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '6': 23, '7': 16, '8': 10, '9': 5}):
5339353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Compute a lower bound for 100*log10(c) for a positive integer c."""
5340353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if c <= 0:
5341353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        raise ValueError("The argument to _log10_lb should be nonnegative.")
5342353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    str_c = str(c)
5343353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return 100*len(str_c) - correction[str_c[0]]
5344353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
534559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Helper Functions ####################################################
53467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
5347353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _convert_other(other, raiseit=False):
5348636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    """Convert other to Decimal.
5349636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
5350636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    Verifies that it's ok to use in an implicit construction.
5351636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    """
5352636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    if isinstance(other, Decimal):
5353636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        return other
5354636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    if isinstance(other, (int, long)):
5355636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        return Decimal(other)
5356353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if raiseit:
5357353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        raise TypeError("Unable to convert %s to Decimal" % other)
5358267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger    return NotImplemented
5359636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
536059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Setup Specific Contexts ############################################
53617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
53627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# The default context prototype used by Context()
5363fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger# Is mutable, so that new contexts can have different default values
53647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
53657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerDefaultContext = Context(
53666ea484582238a65d44a76e3a831e3ba7c77a1a25Raymond Hettinger        prec=28, rounding=ROUND_HALF_EVEN,
5367bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        traps=[DivisionByZero, Overflow, InvalidOperation],
5368bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        flags=[],
536999148e7eaad7741fbfb0822009b7c9b216ecc227Raymond Hettinger        Emax=999999999,
537099148e7eaad7741fbfb0822009b7c9b216ecc227Raymond Hettinger        Emin=-999999999,
5371e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger        capitals=1
53727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger)
53737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
53747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# Pre-made alternate contexts offered by the specification
53757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# Don't change these; the user should be able to select these
53767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# contexts and be able to reproduce results from other implementations
53777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# of the spec.
53787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
53799ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond HettingerBasicContext = Context(
53807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        prec=9, rounding=ROUND_HALF_UP,
5381bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5382bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        flags=[],
53837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger)
53847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
53859ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond HettingerExtendedContext = Context(
53866ea484582238a65d44a76e3a831e3ba7c77a1a25Raymond Hettinger        prec=9, rounding=ROUND_HALF_EVEN,
5387bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        traps=[],
5388bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        flags=[],
53897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger)
53907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
53917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
539259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### crud for parsing strings #############################################
53936a123cb7827859748a0096570dfbb5ceba0e59dcMark Dickinson#
539472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# Regular expression used for parsing numeric strings.  Additional
539572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# comments:
539672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista#
539772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
539872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# whitespace.  But note that the specification disallows whitespace in
539972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# a numeric string.
540072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista#
540172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# 2. For finite numbers (not infinities and NaNs) the body of the
540272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# number between the optional sign and the optional exponent must have
540372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# at least one decimal digit, possibly after the decimal point.  The
540472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# lookahead expression '(?=\d|\.\d)' checks this.
540572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista#
540672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# As the flag UNICODE is not enabled here, we're explicitly avoiding any
540772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# other meaning for \d than the numbers [0-9].
54087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
540972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batistaimport re
541070c3289085d08d97edbfaa626efc2d2c2ac21859Mark Dickinson_parser = re.compile(r"""        # A numeric string consists of:
54117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger#    \s*
541270c3289085d08d97edbfaa626efc2d2c2ac21859Mark Dickinson    (?P<sign>[-+])?              # an optional sign, followed by either...
54137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    (
541470c3289085d08d97edbfaa626efc2d2c2ac21859Mark Dickinson        (?=[0-9]|\.[0-9])        # ...a number (with at least one digit)
541570c3289085d08d97edbfaa626efc2d2c2ac21859Mark Dickinson        (?P<int>[0-9]*)          # having a (possibly empty) integer part
541670c3289085d08d97edbfaa626efc2d2c2ac21859Mark Dickinson        (\.(?P<frac>[0-9]*))?    # followed by an optional fractional part
541770c3289085d08d97edbfaa626efc2d2c2ac21859Mark Dickinson        (E(?P<exp>[-+]?[0-9]+))? # followed by an optional exponent, or...
54187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    |
541970c3289085d08d97edbfaa626efc2d2c2ac21859Mark Dickinson        Inf(inity)?              # ...an infinity, or...
542072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    |
542170c3289085d08d97edbfaa626efc2d2c2ac21859Mark Dickinson        (?P<signal>s)?           # ...an (optionally signaling)
542270c3289085d08d97edbfaa626efc2d2c2ac21859Mark Dickinson        NaN                      # NaN
542370c3289085d08d97edbfaa626efc2d2c2ac21859Mark Dickinson        (?P<diag>[0-9]*)         # with (possibly empty) diagnostic info.
54247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    )
54257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger#    \s*
542659bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson    \Z
542772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista""", re.VERBOSE | re.IGNORECASE).match
54287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
54292ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista_all_zeros = re.compile('0*$').match
54302ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista_exact_half = re.compile('50*$').match
54311ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
54321ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson##### PEP3101 support functions ##############################################
5433277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson# The functions in this section have little to do with the Decimal
5434277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson# class, and could potentially be reused or adapted for other pure
54351ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson# Python numeric classes that want to implement __format__
54361ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson#
54371ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson# A format specifier for Decimal looks like:
54381ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson#
5439277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson#   [[fill]align][sign][0][minimumwidth][,][.precision][type]
54401ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
54411ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson_parse_format_specifier_regex = re.compile(r"""\A
54421ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson(?:
54431ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson   (?P<fill>.)?
54441ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson   (?P<align>[<>=^])
54451ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson)?
54461ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson(?P<sign>[-+ ])?
54471ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson(?P<zeropad>0)?
54481ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson(?P<minimumwidth>(?!0)\d+)?
5449277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson(?P<thousands_sep>,)?
54501ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson(?:\.(?P<precision>0|(?!0)\d+))?
5451277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson(?P<type>[eEfFgGn%])?
54521ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson\Z
54531ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson""", re.VERBOSE)
54541ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
54557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerdel re
54567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
5457277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson# The locale module is only needed for the 'n' format specifier.  The
5458277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson# rest of the PEP 3101 code functions quite happily without it, so we
5459277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson# don't care too much if locale isn't present.
5460277859d5910782cc31bb27f2472893b8382ad391Mark Dickinsontry:
5461277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    import locale as _locale
5462277859d5910782cc31bb27f2472893b8382ad391Mark Dickinsonexcept ImportError:
5463277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    pass
5464277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5465277859d5910782cc31bb27f2472893b8382ad391Mark Dickinsondef _parse_format_specifier(format_spec, _localeconv=None):
54661ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    """Parse and validate a format specifier.
54671ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
54681ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    Turns a standard numeric format specifier into a dict, with the
54691ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    following entries:
54701ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
54711ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson      fill: fill character to pad field to minimum width
54721ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson      align: alignment type, either '<', '>', '=' or '^'
54731ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson      sign: either '+', '-' or ' '
54741ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson      minimumwidth: nonnegative integer giving minimum width
5475277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson      zeropad: boolean, indicating whether to pad with zeros
5476277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson      thousands_sep: string to use as thousands separator, or ''
5477277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson      grouping: grouping for thousands separators, in format
5478277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        used by localeconv
5479277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson      decimal_point: string to use for decimal point
54801ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson      precision: nonnegative integer giving precision, or None
54811ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson      type: one of the characters 'eEfFgG%', or None
5482277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson      unicode: boolean (always True for Python 3.x)
54831ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
54841ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    """
54851ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    m = _parse_format_specifier_regex.match(format_spec)
54861ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    if m is None:
54871ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        raise ValueError("Invalid format specifier: " + format_spec)
54881ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
54891ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    # get the dictionary
54901ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    format_dict = m.groupdict()
54911ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
5492277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    # zeropad; defaults for fill and alignment.  If zero padding
5493277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    # is requested, the fill and align fields should be absent.
54941ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    fill = format_dict['fill']
54951ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    align = format_dict['align']
5496277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    format_dict['zeropad'] = (format_dict['zeropad'] is not None)
5497277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    if format_dict['zeropad']:
5498277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        if fill is not None:
54991ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson            raise ValueError("Fill character conflicts with '0'"
55001ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson                             " in format specifier: " + format_spec)
5501277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        if align is not None:
55021ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson            raise ValueError("Alignment conflicts with '0' in "
55031ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson                             "format specifier: " + format_spec)
55041ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    format_dict['fill'] = fill or ' '
55051ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    format_dict['align'] = align or '<'
55061ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
5507277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    # default sign handling: '-' for negative, '' for positive
55081ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    if format_dict['sign'] is None:
55091ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        format_dict['sign'] = '-'
55101ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
55111ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    # minimumwidth defaults to 0; precision remains None if not given
55121ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
55131ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    if format_dict['precision'] is not None:
55141ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        format_dict['precision'] = int(format_dict['precision'])
55151ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
55161ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    # if format type is 'g' or 'G' then a precision of 0 makes little
55171ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    # sense; convert it to 1.  Same if format type is unspecified.
55181ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    if format_dict['precision'] == 0:
55191ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        if format_dict['type'] in 'gG' or format_dict['type'] is None:
55201ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson            format_dict['precision'] = 1
55211ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
5522277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    # determine thousands separator, grouping, and decimal separator, and
5523277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    # add appropriate entries to format_dict
5524277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    if format_dict['type'] == 'n':
5525277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        # apart from separators, 'n' behaves just like 'g'
5526277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        format_dict['type'] = 'g'
5527277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        if _localeconv is None:
5528277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson            _localeconv = _locale.localeconv()
5529277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        if format_dict['thousands_sep'] is not None:
5530277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson            raise ValueError("Explicit thousands separator conflicts with "
5531277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson                             "'n' type in format specifier: " + format_spec)
5532277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        format_dict['thousands_sep'] = _localeconv['thousands_sep']
5533277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        format_dict['grouping'] = _localeconv['grouping']
5534277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        format_dict['decimal_point'] = _localeconv['decimal_point']
5535277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    else:
5536277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        if format_dict['thousands_sep'] is None:
5537277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson            format_dict['thousands_sep'] = ''
5538277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        format_dict['grouping'] = [3, 0]
5539277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        format_dict['decimal_point'] = '.'
5540277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
55411ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    # record whether return type should be str or unicode
55421ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    format_dict['unicode'] = isinstance(format_spec, unicode)
55431ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
55441ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    return format_dict
55451ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
5546277859d5910782cc31bb27f2472893b8382ad391Mark Dickinsondef _format_align(sign, body, spec):
5547277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    """Given an unpadded, non-aligned numeric string 'body' and sign
5548277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    string 'sign', add padding and aligment conforming to the given
5549277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    format specifier dictionary 'spec' (as produced by
5550277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    parse_format_specifier).
55511ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
5552277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    Also converts result to unicode if necessary.
55531ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
55541ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    """
55551ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    # how much extra space do we have to play with?
5556277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    minimumwidth = spec['minimumwidth']
5557277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    fill = spec['fill']
5558277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    padding = fill*(minimumwidth - len(sign) - len(body))
55591ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
5560277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    align = spec['align']
55611ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    if align == '<':
55621ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        result = sign + body + padding
5563b065e52bc284c2c28a967c4e82aa7ece6d09c562Mark Dickinson    elif align == '>':
5564b065e52bc284c2c28a967c4e82aa7ece6d09c562Mark Dickinson        result = padding + sign + body
55651ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    elif align == '=':
55661ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        result = sign + padding + body
5567277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    elif align == '^':
55681ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        half = len(padding)//2
55691ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        result = padding[:half] + sign + body + padding[half:]
5570277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    else:
5571277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        raise ValueError('Unrecognised alignment field')
55721ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
55731ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    # make sure that result is unicode if necessary
5574277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    if spec['unicode']:
55751ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson        result = unicode(result)
55761ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson
55771ddf1d8482f4fd8ae034bfd0221696ee2068c144Mark Dickinson    return result
55780d4c06e06e5ee1f3bb1fa8068114bd700d74864aNeal Norwitz
5579277859d5910782cc31bb27f2472893b8382ad391Mark Dickinsondef _group_lengths(grouping):
5580277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    """Convert a localeconv-style grouping into a (possibly infinite)
5581277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    iterable of integers representing group lengths.
5582277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5583277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    """
5584277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    # The result from localeconv()['grouping'], and the input to this
5585277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    # function, should be a list of integers in one of the
5586277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    # following three forms:
5587277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    #
5588277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    #   (1) an empty list, or
5589277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    #   (2) nonempty list of positive integers + [0]
5590277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    #   (3) list of positive integers + [locale.CHAR_MAX], or
5591277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5592277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    from itertools import chain, repeat
5593277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    if not grouping:
5594277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        return []
5595277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    elif grouping[-1] == 0 and len(grouping) >= 2:
5596277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        return chain(grouping[:-1], repeat(grouping[-2]))
5597277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    elif grouping[-1] == _locale.CHAR_MAX:
5598277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        return grouping[:-1]
5599277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    else:
5600277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        raise ValueError('unrecognised format for grouping')
5601277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5602277859d5910782cc31bb27f2472893b8382ad391Mark Dickinsondef _insert_thousands_sep(digits, spec, min_width=1):
5603277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    """Insert thousands separators into a digit string.
5604277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5605277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    spec is a dictionary whose keys should include 'thousands_sep' and
5606277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    'grouping'; typically it's the result of parsing the format
5607277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    specifier using _parse_format_specifier.
5608277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5609277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    The min_width keyword argument gives the minimum length of the
5610277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    result, which will be padded on the left with zeros if necessary.
5611277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5612277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    If necessary, the zero padding adds an extra '0' on the left to
5613277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    avoid a leading thousands separator.  For example, inserting
5614277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    commas every three digits in '123456', with min_width=8, gives
5615277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    '0,123,456', even though that has length 9.
5616277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5617277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    """
5618277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5619277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    sep = spec['thousands_sep']
5620277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    grouping = spec['grouping']
5621277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5622277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    groups = []
5623277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    for l in _group_lengths(grouping):
5624277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        if l <= 0:
5625277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson            raise ValueError("group length should be positive")
5626277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        # max(..., 1) forces at least 1 digit to the left of a separator
5627277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        l = min(max(len(digits), min_width, 1), l)
5628277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        groups.append('0'*(l - len(digits)) + digits[-l:])
5629277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        digits = digits[:-l]
5630277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        min_width -= l
5631277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        if not digits and min_width <= 0:
5632277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson            break
5633b14514a153857141631d602cadf094bc932f12eeMark Dickinson        min_width -= len(sep)
5634277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    else:
5635277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        l = max(len(digits), min_width, 1)
5636277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        groups.append('0'*(l - len(digits)) + digits[-l:])
5637277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    return sep.join(reversed(groups))
5638277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5639277859d5910782cc31bb27f2472893b8382ad391Mark Dickinsondef _format_sign(is_negative, spec):
5640277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    """Determine sign character."""
5641277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5642277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    if is_negative:
5643277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        return '-'
5644277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    elif spec['sign'] in ' +':
5645277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        return spec['sign']
5646277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    else:
5647277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        return ''
5648277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5649277859d5910782cc31bb27f2472893b8382ad391Mark Dickinsondef _format_number(is_negative, intpart, fracpart, exp, spec):
5650277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    """Format a number, given the following data:
5651277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5652277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    is_negative: true if the number is negative, else false
5653277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    intpart: string of digits that must appear before the decimal point
5654277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    fracpart: string of digits that must come after the point
5655277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    exp: exponent, as an integer
5656277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    spec: dictionary resulting from parsing the format specifier
5657277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5658277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    This function uses the information in spec to:
5659277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson      insert separators (decimal separator and thousands separators)
5660277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson      format the sign
5661277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson      format the exponent
5662277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson      add trailing '%' for the '%' type
5663277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson      zero-pad if necessary
5664277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson      fill and align if necessary
5665277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    """
5666277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5667277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    sign = _format_sign(is_negative, spec)
5668277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5669277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    if fracpart:
5670277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        fracpart = spec['decimal_point'] + fracpart
5671277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5672277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    if exp != 0 or spec['type'] in 'eE':
5673277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
5674277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        fracpart += "{0}{1:+}".format(echar, exp)
5675277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    if spec['type'] == '%':
5676277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        fracpart += '%'
5677277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5678277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    if spec['zeropad']:
5679277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
5680277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    else:
5681277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson        min_width = 0
5682277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    intpart = _insert_thousands_sep(intpart, spec, min_width)
5683277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5684277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson    return _format_align(sign, intpart+fracpart, spec)
5685277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
5686277859d5910782cc31bb27f2472893b8382ad391Mark Dickinson
568772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista##### Useful Constants (internal use only) ################################
56887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
568972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# Reusable defaults
5690b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger_Infinity = Decimal('Inf')
5691b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger_NegativeInfinity = Decimal('-Inf')
5692c5de0969ca2a82c66efd30bb675f03c2324a3b27Mark Dickinson_NaN = Decimal('NaN')
5693b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger_Zero = Decimal(0)
5694b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger_One = Decimal(1)
5695b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger_NegativeOne = Decimal(-1)
5696c5de0969ca2a82c66efd30bb675f03c2324a3b27Mark Dickinson
5697b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger# _SignedInfinity[sign] is infinity w/ that sign
5698b7e835b820fc7d17a02dc4cdf3b745bb993952adRaymond Hettinger_SignedInfinity = (_Infinity, _NegativeInfinity)
56997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
57007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
57017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
57027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerif __name__ == '__main__':
57037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    import doctest, sys
57047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    doctest.testmod(sys.modules[__name__])
5705