decimal.py revision bd2fe839db886de6ce9631acd8aa9796b413a565
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
387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond 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)
457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerDecimal("0")
467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> Decimal("1")
477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerDecimal("1")
487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> Decimal("-.0123")
497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerDecimal("-0.0123")
507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> Decimal(123456)
517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerDecimal("123456")
527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> Decimal("123.45e12345678901234567890")
537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerDecimal("1.2345E+12345678901234567892")
547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> Decimal("1.33") + Decimal("1.27")
557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerDecimal("2.60")
567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41")
577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond 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))
947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond 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
137eb2608415ee4eb8aaea746f6a313937e264d0cdaRaymond Hettingerimport copy as _copy
1387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista# Rounding
1400ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_DOWN = 'ROUND_DOWN'
1410ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_HALF_UP = 'ROUND_HALF_UP'
1420ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
1430ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_CEILING = 'ROUND_CEILING'
1440ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_FLOOR = 'ROUND_FLOOR'
1450ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_UP = 'ROUND_UP'
1460ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
147353750c405c9099d0be69c6af1d17037b38c4ddfFacundo BatistaROUND_05UP = 'ROUND_05UP'
1487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista# Rounding decision (not part of the public API)
1500ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerNEVER_ROUND = 'NEVER_ROUND'    # Round in division (non-divmod), sqrt ONLY
1510ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerALWAYS_ROUND = 'ALWAYS_ROUND'  # Every operation rounds at end.
1527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
15359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista# Errors
1547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass DecimalException(ArithmeticError):
1565aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger    """Base exception class.
1577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Used exceptions derive from this.
1597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    If an exception derives from another exception besides this (such as
1607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
1617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    called if the others are present.  This isn't actually used for
1627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    anything, though.
1637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
164cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis    handle  -- Called when context._raise_error is called and the
165cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis               trap_enabler is set.  First argument is self, second is the
166cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis               context.  More arguments can be given, those being after
167cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis               the explanation in _raise_error (For example,
168cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis               context._raise_error(NewError, '(-x)!', self._sign) would
169cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis               call NewError().handle(context, self._sign).)
170cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
1717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    To define a new exception, it should be sufficient to have it derive
1727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    from DecimalException.
1737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
1747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, *args):
1757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        pass
1767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Clamped(DecimalException):
1797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Exponent of a 0 changed to fit bounds.
1807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals clamped if the exponent of a result has been
1827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    altered in order to fit the constraints of a specific concrete
18359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    representation.  This may occur when the exponent of a zero result would
18459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    be outside the bounds of a representation, or when a large normal
18559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    number would have an encoded exponent that cannot be represented.  In
1867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    this latter case, the exponent is reduced to fit and the corresponding
1877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    number of zero digits are appended to the coefficient ("fold-down").
1887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
1897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass InvalidOperation(DecimalException):
1927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """An invalid operation was performed.
1937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Various bad things cause this:
1957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Something creates a signaling NaN
1977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    -INF + INF
19859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    0 * (+-)INF
19959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    (+-)INF / (+-)INF
2007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    x % 0
2017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    (+-)INF % x
2027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    x._rescale( non-integer )
2037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    sqrt(-x) , x > 0
2047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    0 ** 0
2057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    x ** (non-integer)
2067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    x ** (+-)INF
2077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    An operand is invalid
208353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
209353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    The result of the operation after these is a quiet positive NaN,
210353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    except when the cause is a signaling NaN, in which case the result is
211353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    also a quiet NaN, but with the original sign, and an optional
212353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    diagnostic information.
2137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
2147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, *args):
2157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if args:
21659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            if args[0] == 1:  # sNaN, must drop 's' but keep diagnostics
217353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                ans = Decimal((args[1]._sign, args[1]._int, 'n'))
218353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return ans._fix_nan(context)
219353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            elif args[0] == 2:
220353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Decimal( (args[1], args[2], 'n') )
2217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return NaN
2227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
223353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass ConversionSyntax(InvalidOperation):
2257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Trying to convert badly formed string.
2267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals invalid-operation if an string is being
2287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    converted to a number and it does not conform to the numeric string
22959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    syntax.  The result is [0,qNaN].
2307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
231cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis    def handle(self, context, *args):
232353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return NaN
2337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass DivisionByZero(DecimalException, ZeroDivisionError):
2357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Division by 0.
2367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals division-by-zero if division of a finite number
2387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    by zero was attempted (during a divide-integer or divide operation, or a
2397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    power operation with negative right-hand operand), and the dividend was
2407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    not zero.
2417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The result of the operation is [sign,inf], where sign is the exclusive
2437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    or of the signs of the operands for divide, or is 1 for an odd power of
2447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    -0, for power.
2457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
246cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
2477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, sign, double = None, *args):
2487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if double is not None:
2497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return (Infsign[sign],)*2
2507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return Infsign[sign]
2517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass DivisionImpossible(InvalidOperation):
2537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Cannot perform the division adequately.
2547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals invalid-operation if the integer result of a
2567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    divide-integer or remainder operation had too many digits (would be
25759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    longer than precision).  The result is [0,qNaN].
2587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
259cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
2607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, *args):
2617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return (NaN, NaN)
2627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass DivisionUndefined(InvalidOperation, ZeroDivisionError):
2647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Undefined result of division.
2657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals invalid-operation if division by zero was
2677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    attempted (during a divide-integer, divide, or remainder operation), and
26859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    the dividend is also zero.  The result is [0,qNaN].
2697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
270cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
2717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, tup=None, *args):
2727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if tup is not None:
27359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            return (NaN, NaN)  # for 0 %0, 0 // 0
2747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return NaN
2757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Inexact(DecimalException):
2777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Had to round, losing information.
2787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals inexact whenever the result of an operation is
2807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    not exact (that is, it needed to be rounded and any discarded digits
28159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    were non-zero), or if an overflow or underflow condition occurs.  The
2827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    result in all cases is unchanged.
2837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The inexact signal may be tested (or trapped) to determine if a given
2857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    operation (or sequence of operations) was inexact.
2867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
2875aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger    pass
2887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass InvalidContext(InvalidOperation):
2907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Invalid context.  Unknown rounding, for example.
2917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals invalid-operation if an invalid context was
29359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    detected during an operation.  This can occur if contexts are not checked
2947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    on creation and either the precision exceeds the capability of the
2957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    underlying concrete representation or an unknown or unsupported rounding
29659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    was specified.  These aspects of the context need only be checked when
29759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    the values are required to be used.  The result is [0,qNaN].
2987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
299cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
3007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, *args):
3017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return NaN
3027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Rounded(DecimalException):
3047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Number got rounded (not  necessarily changed during rounding).
3057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals rounded whenever the result of an operation is
3077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    rounded (that is, some zero or non-zero digits were discarded from the
30859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    coefficient), or if an overflow or underflow condition occurs.  The
3097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    result in all cases is unchanged.
3107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The rounded signal may be tested (or trapped) to determine if a given
3127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    operation (or sequence of operations) caused a loss of precision.
3137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
3145aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger    pass
3157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Subnormal(DecimalException):
3177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Exponent < Emin before rounding.
3187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals subnormal whenever the result of a conversion or
3207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    operation is subnormal (that is, its adjusted exponent is less than
32159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    Emin, before any rounding).  The result in all cases is unchanged.
3227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The subnormal signal may be tested (or trapped) to determine if a given
3247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    or operation (or sequence of operations) yielded a subnormal result.
3257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
3267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    pass
3277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Overflow(Inexact, Rounded):
3297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Numerical overflow.
3307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals overflow if the adjusted exponent of a result
3327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    (from a conversion or from an operation that is not an attempt to divide
3337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    by zero), after rounding, would be greater than the largest value that
3347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    can be handled by the implementation (the value Emax).
3357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The result depends on the rounding mode:
3377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    For round-half-up and round-half-even (and for round-half-down and
3397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    round-up, if implemented), the result of the operation is [sign,inf],
34059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    where sign is the sign of the intermediate result.  For round-down, the
3417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    result is the largest finite number that can be represented in the
34259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    current precision, with the sign of the intermediate result.  For
3437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    round-ceiling, the result is the same as for round-down if the sign of
34459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    the intermediate result is 1, or is [0,inf] otherwise.  For round-floor,
3457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    the result is the same as for round-down if the sign of the intermediate
34659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    result is 0, or is [1,inf] otherwise.  In all cases, Inexact and Rounded
3477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    will also be raised.
348cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis   """
349cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
3507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, sign, *args):
3517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
352353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                ROUND_HALF_DOWN, ROUND_UP):
3537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return Infsign[sign]
3547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if sign == 0:
3557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if context.rounding == ROUND_CEILING:
3567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return Infsign[sign]
3577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return Decimal((sign, (9,)*context.prec,
3587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                            context.Emax-context.prec+1))
3597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if sign == 1:
3607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if context.rounding == ROUND_FLOOR:
3617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return Infsign[sign]
3627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return Decimal( (sign, (9,)*context.prec,
3637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                             context.Emax-context.prec+1))
3647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Underflow(Inexact, Rounded, Subnormal):
3677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Numerical underflow with result rounded to 0.
3687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals underflow if a result is inexact and the
3707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    adjusted exponent of the result would be smaller (more negative) than
3717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    the smallest value that can be handled by the implementation (the value
37259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    Emin).  That is, the result is both inexact and subnormal.
3737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The result after an underflow will be a subnormal number rounded, if
37559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    necessary, so that its exponent is not less than Etiny.  This may result
3767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    in 0 with the sign of the intermediate result and an exponent of Etiny.
3777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    In all cases, Inexact, Rounded, and Subnormal will also be raised.
3797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
3807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3815aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger# List of public traps and flags
382fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
383cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis           Underflow, InvalidOperation, Subnormal]
3847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3855aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger# Map conditions (per the spec) to signals
3865aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger_condition_map = {ConversionSyntax:InvalidOperation,
3875aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger                  DivisionImpossible:InvalidOperation,
3885aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger                  DivisionUndefined:InvalidOperation,
3895aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger                  InvalidContext:InvalidOperation}
3907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
39159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Context Functions ##################################################
3927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
393ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger# The getcontext() and setcontext() function manage access to a thread-local
394ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger# current context.  Py2.4 offers direct support for thread locals.  If that
395ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger# is not available, use threading.currentThread() which is slower but will
3967e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger# work for older Pythons.  If threads are not part of the build, create a
397cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis# mock threading object with threading.local() returning the module namespace.
3987e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger
3997e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettingertry:
4007e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    import threading
4017e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettingerexcept ImportError:
4027e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    # Python was compiled without threads; create a mock object instead
4037e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    import sys
40459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    class MockThreading(object):
4057e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger        def local(self, sys=sys):
4067e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger            return sys.modules[__name__]
4077e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    threading = MockThreading()
4087e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    del sys, MockThreading
409ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
410ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettingertry:
411ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    threading.local
412ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
413ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettingerexcept AttributeError:
414ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
41559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # To fix reloading, force it to create a new context
41659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # Old contexts have different exceptions in their dicts, making problems.
417ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    if hasattr(threading.currentThread(), '__decimal_context__'):
418ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        del threading.currentThread().__decimal_context__
419ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
420ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    def setcontext(context):
421ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """Set this thread's context to context."""
422ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        if context in (DefaultContext, BasicContext, ExtendedContext):
4239fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger            context = context.copy()
42461992efc4bb413ae7a19752215eca5af09be6b6dRaymond Hettinger            context.clear_flags()
4257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        threading.currentThread().__decimal_context__ = context
426ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
427ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    def getcontext():
428ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """Returns this thread's context.
429ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
430ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        If this thread does not yet have a context, returns
431ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        a new context and sets this thread's context.
432ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        New contexts are copies of DefaultContext.
433ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """
434ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        try:
435ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            return threading.currentThread().__decimal_context__
436ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        except AttributeError:
437ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            context = Context()
438ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            threading.currentThread().__decimal_context__ = context
439ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            return context
440ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
441ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettingerelse:
442ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
443ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    local = threading.local()
4449fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger    if hasattr(local, '__decimal_context__'):
4459fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        del local.__decimal_context__
446ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
447ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    def getcontext(_local=local):
448ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """Returns this thread's context.
449ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
450ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        If this thread does not yet have a context, returns
451ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        a new context and sets this thread's context.
452ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        New contexts are copies of DefaultContext.
453ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """
454ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        try:
455ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            return _local.__decimal_context__
456ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        except AttributeError:
457ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            context = Context()
458ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            _local.__decimal_context__ = context
459ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            return context
460ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
461ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    def setcontext(context, _local=local):
462ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """Set this thread's context to context."""
463ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        if context in (DefaultContext, BasicContext, ExtendedContext):
4649fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger            context = context.copy()
46561992efc4bb413ae7a19752215eca5af09be6b6dRaymond Hettinger            context.clear_flags()
466ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        _local.__decimal_context__ = context
467ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
468cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis    del threading, local        # Don't contaminate the namespace
4697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4708b6999b4c5fab174090be263ba90f193bdede141Nick Coghlandef localcontext(ctx=None):
4718b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """Return a context manager for a copy of the supplied context
4728b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan
4738b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    Uses a copy of the current context if no context is specified
4748b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    The returned context manager creates a local decimal context
4758b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    in a with statement:
4768b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan        def sin(x):
4778b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan             with localcontext() as ctx:
4788b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 ctx.prec += 2
4798b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # Rest of sin calculation algorithm
4808b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # uses a precision 2 greater than normal
48159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista             return +s  # Convert result to normal precision
4828b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan
4838b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan         def sin(x):
4848b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan             with localcontext(ExtendedContext):
4858b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # Rest of sin calculation algorithm
4868b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # uses the Extended Context from the
4878b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # General Decimal Arithmetic Specification
48859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista             return +s  # Convert result to normal context
4898b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan
4908b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """
491681d86743c21773bb00508dbacb05ed9012388d8Neal Norwitz    # The string below can't be included in the docstring until Python 2.6
4928b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    # as the doctest module doesn't understand __future__ statements
4938b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """
4948b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> from __future__ import with_statement
4958b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> print getcontext().prec
4968b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    28
4978b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> with localcontext():
4988b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...     ctx = getcontext()
499495df4716fce4156c1eb110f9342297164eecbb6Raymond Hettinger    ...     ctx.prec += 2
5008b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...     print ctx.prec
5018b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...
5028b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    30
5038b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> with localcontext(ExtendedContext):
5048b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...     print getcontext().prec
5058b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...
5068b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    9
5078b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> print getcontext().prec
5088b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    28
5098b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """
510ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlan    if ctx is None: ctx = getcontext()
511ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlan    return _ContextManager(ctx)
5128b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan
5137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Decimal class #######################################################
5157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
5167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Decimal(object):
5177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Floating point class for decimal arithmetic."""
5187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
519636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    __slots__ = ('_exp','_int','_sign', '_is_special')
520636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    # Generally, the value of the Decimal instance is given by
521636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    #  (-1)**_sign * _int * 10**_exp
522636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    # Special values are signified by _is_special == True
5237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
524dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger    # We're immutable, so use __new__ not __init__
525636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    def __new__(cls, value="0", context=None):
5267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Create a decimal point instance.
5277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
5287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        >>> Decimal('3.14')              # string input
5297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3.14")
53059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        >>> Decimal((0, (3, 1, 4), -2))  # tuple (sign, digit_tuple, exponent)
5317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3.14")
5327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        >>> Decimal(314)                 # int or long
5337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("314")
5347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        >>> Decimal(Decimal(314))        # another decimal instance
5357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("314")
5367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
5377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
538636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        self = object.__new__(cls)
539636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        self._is_special = False
540636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
541636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        # From an internal working value
542636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if isinstance(value, _WorkRep):
54317931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            self._sign = value.sign
544636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self._int = tuple(map(int, str(value.int)))
545636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self._exp = int(value.exp)
546636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return self
547636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
548636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        # From another decimal
549636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if isinstance(value, Decimal):
550636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self._exp  = value._exp
551636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self._sign = value._sign
552636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self._int  = value._int
553636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self._is_special  = value._is_special
554636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return self
555636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
556636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        # From an integer
5577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if isinstance(value, (int,long)):
558636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if value >= 0:
559636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                self._sign = 0
560636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            else:
561636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                self._sign = 1
562636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self._exp = 0
563636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self._int = tuple(map(int, str(abs(value))))
564636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return self
565636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
566636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        # tuple/list conversion (possibly from as_tuple())
567636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if isinstance(value, (list,tuple)):
568636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if len(value) != 3:
56959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                raise ValueError('Invalid arguments')
570dbecd93b7203cd187c1978de1207c29d3a9a686cRaymond Hettinger            if value[0] not in (0,1):
57159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                raise ValueError('Invalid sign')
572636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            for digit in value[1]:
573636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if not isinstance(digit, (int,long)) or digit < 0:
574353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    raise ValueError("The second value in the tuple must be "
57559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                                "composed of non negative integer elements.")
576636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self._sign = value[0]
577636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self._int  = tuple(value[1])
578636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if value[2] in ('F','n','N'):
579636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                self._exp = value[2]
580636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                self._is_special = True
581636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            else:
582636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                self._exp  = int(value[2])
583636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return self
584636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
585636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if isinstance(value, float):
586636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            raise TypeError("Cannot convert float to Decimal.  " +
587636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                            "First convert the float to a string")
5887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
589636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        # Other argument types may require the context during interpretation
590636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
591636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
592636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
593636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        # From a string
5947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # REs insist on real strings, so we can too.
5957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if isinstance(value, basestring):
5960ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettinger            if _isinfinity(value):
5977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                self._exp = 'F'
5987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                self._int = (0,)
599636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                self._is_special = True
600636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if _isinfinity(value) == 1:
6017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    self._sign = 0
6027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                else:
6037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    self._sign = 1
604636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return self
6050ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettinger            if _isnan(value):
6060ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettinger                sig, sign, diag = _isnan(value)
607636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                self._is_special = True
6087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                if sig == 1:
60959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                    self._exp = 'n'  # qNaN
61059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                else:  # sig == 2
61159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                    self._exp = 'N'  # sNaN
6127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                self._sign = sign
61359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                self._int = tuple(map(int, diag))  # Diagnostic info
614636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return self
615d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger            try:
616d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger                self._sign, self._int, self._exp = _string2exact(value)
617d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger            except ValueError:
618636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                self._is_special = True
619353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(ConversionSyntax,
620353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                   "Invalid literal for Decimal: %r" % value)
621636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return self
6227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
623636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        raise TypeError("Cannot convert %r to Decimal" % value)
6247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _isnan(self):
6267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns whether the number is not actually one.
6277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        0 if a number
629353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        1 if NaN  (it could be a normal quiet NaN or a phantom one)
6307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        2 if sNaN
6317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
632636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
633636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            exp = self._exp
634636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if exp == 'n':
635636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return 1
636636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            elif exp == 'N':
637636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return 2
6387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return 0
6397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _isinfinity(self):
6417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns whether the number is infinite
6427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        0 if finite or not a number
6447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        1 if +INF
6457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        -1 if -INF
6467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
6477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._exp == 'F':
6487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if self._sign:
6497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return -1
6507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return 1
6517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return 0
6527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
653353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _check_nans(self, other=None, context=None):
6547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns whether the number is not actually one.
6557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self, other are sNaN, signal
6577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self, other are NaN return nan
6587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return 0
6597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Done before operations.
6617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
6627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
663636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        self_is_nan = self._isnan()
664636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if other is None:
665636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            other_is_nan = False
666636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        else:
667636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            other_is_nan = other._isnan()
668636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
669636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self_is_nan or other_is_nan:
670636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if context is None:
671636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                context = getcontext()
672636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
673636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self_is_nan == 2:
674636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return context._raise_error(InvalidOperation, 'sNaN',
675636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                                        1, self)
676636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if other_is_nan == 2:
677636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return context._raise_error(InvalidOperation, 'sNaN',
678636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                                        1, other)
679636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self_is_nan:
680353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self._fix_nan(context)
681636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
682353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return other._fix_nan(context)
6837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return 0
6847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __nonzero__(self):
6867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Is the number non-zero?
6877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        0 if self == 0
6897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        1 if self != 0
6907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
691636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
692353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return True
693636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        return sum(self._int) != 0
6947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
695353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def __cmp__(self, other):
696636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
697267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
698353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # Never return NotImplemented
699353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return 1
7007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
701636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
702353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # check for nans, without raising on a signaling nan
703353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self._isnan() or other._isnan():
70459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                return 1  # Comparison involving NaN's always reports self > other
705636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
706636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            # INF = INF
707636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return cmp(self._isinfinity(), other._isinfinity())
7087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
709353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # check for zeros;  note that cmp(0, -0) should return 0
710353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
711353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if not other:
712353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return 0
713353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
714353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return -((-1)**other._sign)
715353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other:
716353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return (-1)**self._sign
7177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
71859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # If different signs, neg one is less
7197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if other._sign < self._sign:
7207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return -1
7217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign < other._sign:
7227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return 1
7237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
724636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        self_adjusted = self.adjusted()
725636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other_adjusted = other.adjusted()
726353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_adjusted == other_adjusted:
727353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            self_padded = self._int + (0,)*(self._exp - other._exp)
728353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            other_padded = other._int + (0,)*(other._exp - self._exp)
729353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return cmp(self_padded, other_padded) * (-1)**self._sign
730353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif self_adjusted > other_adjusted:
7317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return (-1)**self._sign
732353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else: # self_adjusted < other_adjusted
7337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return -((-1)**self._sign)
7347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7350aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger    def __eq__(self, other):
7360aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger        if not isinstance(other, (Decimal, int, long)):
737267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return NotImplemented
7380aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger        return self.__cmp__(other) == 0
7390aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger
7400aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger    def __ne__(self, other):
7410aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger        if not isinstance(other, (Decimal, int, long)):
742267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return NotImplemented
7430aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger        return self.__cmp__(other) != 0
7440aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger
7457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def compare(self, other, context=None):
7467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Compares one to another.
7477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        -1 => a < b
7497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        0  => a = b
7507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        1  => a > b
7517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        NaN => one is NaN
7527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Like __cmp__, but returns Decimal instances.
7537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
754353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
7557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
75659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # Compare(NaN, NaN) = NaN
757636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if (self._is_special or other and other._is_special):
758636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
759636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
760636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
7617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
762353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal(self.__cmp__(other))
7637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __hash__(self):
7657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """x.__hash__() <==> hash(x)"""
7667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Decimal integers must hash the same as the ints
7677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Non-integer decimals are normalized and hashed as strings
7681fb9f528bd69efa135bacda917ec7bb166068d5dGeorg Brandl        # Normalization assures that hash(100E-1) == hash(10)
769bea3f6f5c788eb4f0f7639913ff89654152864c0Raymond Hettinger        if self._is_special:
770bea3f6f5c788eb4f0f7639913ff89654152864c0Raymond Hettinger            if self._isnan():
771bea3f6f5c788eb4f0f7639913ff89654152864c0Raymond Hettinger                raise TypeError('Cannot hash a NaN value.')
772bea3f6f5c788eb4f0f7639913ff89654152864c0Raymond Hettinger            return hash(str(self))
7737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        i = int(self)
7747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self == Decimal(i):
7757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return hash(i)
7767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        assert self.__nonzero__()   # '-0' handled by integer case
7777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return hash(str(self.normalize()))
7787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def as_tuple(self):
7807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Represents the number as a triple tuple.
7817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        To show the internals exactly as they are.
7837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
7847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return (self._sign, self._int, self._exp)
7857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __repr__(self):
7877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Represents the number as an instance of Decimal."""
7887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Invariant:  eval(repr(d)) == d
7897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return 'Decimal("%s")' % str(self)
7907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
791353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def __str__(self, eng=False, context=None):
7927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return string representation of the number in scientific notation.
7937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Captures all of the information in the underlying representation.
7957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
7967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
797e5a0a9609faea9afdc6f81f1f6dfa07b1437e3aeRaymond Hettinger        if self._is_special:
798e5a0a9609faea9afdc6f81f1f6dfa07b1437e3aeRaymond Hettinger            if self._isnan():
799e5a0a9609faea9afdc6f81f1f6dfa07b1437e3aeRaymond Hettinger                minus = '-'*self._sign
800e5a0a9609faea9afdc6f81f1f6dfa07b1437e3aeRaymond Hettinger                if self._int == (0,):
801e5a0a9609faea9afdc6f81f1f6dfa07b1437e3aeRaymond Hettinger                    info = ''
802e5a0a9609faea9afdc6f81f1f6dfa07b1437e3aeRaymond Hettinger                else:
803e5a0a9609faea9afdc6f81f1f6dfa07b1437e3aeRaymond Hettinger                    info = ''.join(map(str, self._int))
804e5a0a9609faea9afdc6f81f1f6dfa07b1437e3aeRaymond Hettinger                if self._isnan() == 2:
805e5a0a9609faea9afdc6f81f1f6dfa07b1437e3aeRaymond Hettinger                    return minus + 'sNaN' + info
806e5a0a9609faea9afdc6f81f1f6dfa07b1437e3aeRaymond Hettinger                return minus + 'NaN' + info
807e5a0a9609faea9afdc6f81f1f6dfa07b1437e3aeRaymond Hettinger            if self._isinfinity():
808e5a0a9609faea9afdc6f81f1f6dfa07b1437e3aeRaymond Hettinger                minus = '-'*self._sign
809e5a0a9609faea9afdc6f81f1f6dfa07b1437e3aeRaymond Hettinger                return minus + 'Infinity'
8107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
8127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
8137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        tmp = map(str, self._int)
8157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        numdigits = len(self._int)
8167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        leftdigits = self._exp + numdigits
81759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        if eng and not self:  # self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
81859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            if self._exp < 0 and self._exp >= -6:  # short, no need for e/E
8197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                s = '-'*self._sign + '0.' + '0'*(abs(self._exp))
8207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return s
82159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # exp is closest mult. of 3 >= self._exp
8227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            exp = ((self._exp - 1)// 3 + 1) * 3
8237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if exp != self._exp:
8247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                s = '0.'+'0'*(exp - self._exp)
8257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            else:
8267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                s = '0'
8277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if exp != 0:
8287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                if context.capitals:
8297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    s += 'E'
8307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                else:
8317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    s += 'e'
8327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                if exp > 0:
83359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                    s += '+'  # 0.0e+3, not 0.0e3
8347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                s += str(exp)
8357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            s = '-'*self._sign + s
8367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return s
8377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if eng:
8387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            dotplace = (leftdigits-1)%3+1
8397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            adjexp = leftdigits -1 - (leftdigits-1)%3
8407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
8417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            adjexp = leftdigits-1
8427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            dotplace = 1
8437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._exp == 0:
8447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            pass
8457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        elif self._exp < 0 and adjexp >= 0:
8467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            tmp.insert(leftdigits, '.')
8477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        elif self._exp < 0 and adjexp >= -6:
8487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            tmp[0:0] = ['0'] * int(-leftdigits)
8497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            tmp.insert(0, '0.')
8507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
8517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if numdigits > dotplace:
8527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                tmp.insert(dotplace, '.')
8537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            elif numdigits < dotplace:
8547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                tmp.extend(['0']*(dotplace-numdigits))
8557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if adjexp:
8567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                if not context.capitals:
8577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    tmp.append('e')
8587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                else:
8597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    tmp.append('E')
8607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    if adjexp > 0:
8617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                        tmp.append('+')
8627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                tmp.append(str(adjexp))
8637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if eng:
8647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            while tmp[0:1] == ['0']:
8657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                tmp[0:1] = []
8667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e':
8677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                tmp[0:0] = ['0']
8687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign:
8697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            tmp.insert(0, '-')
8707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ''.join(tmp)
8727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def to_eng_string(self, context=None):
8747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Convert to engineering-type string.
8757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Engineering notation has an exponent which is a multiple of 3, so there
8777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        are up to 3 digits left of the decimal place.
8787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Same rules for when in exponential and when as a value as in __str__.
8807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
881353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self.__str__(eng=True, context=context)
8827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __neg__(self, context=None):
8847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns a copy with the sign switched.
8857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Rounds, if it has reason.
8877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
888636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
889636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
890636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
891636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
8927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
8947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            # -Decimal('0') is Decimal('0'), not Decimal('-0')
895353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.copy_sign(Dec_0)
8967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
897353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.copy_negate()
898636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
899636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
900636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
9017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context._rounding_decision == ALWAYS_ROUND:
902353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
903353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
9047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __pos__(self, context=None):
9067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns a copy, unless it is a sNaN.
9077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Rounds the number (if more then precision digits)
9097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
910636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
911636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
912636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
913636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
9147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
9167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            # + (-0) = 0
917353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.copy_sign(Dec_0)
918353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
919353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal(self)
9207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
921636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
922636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
9237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context._rounding_decision == ALWAYS_ROUND:
924353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
9257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
9267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __abs__(self, round=1, context=None):
9287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the absolute value of self.
9297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the second argument is 0, do not round.
9317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
932636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
933636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
934636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
935636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
9367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not round:
938636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if context is None:
939636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                context = getcontext()
9409fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger            context = context._shallow_copy()
9417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context._set_rounding_decision(NEVER_ROUND)
9427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign:
9447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = self.__neg__(context=context)
9457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
9467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = self.__pos__(context=context)
9477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
9497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __add__(self, other, context=None):
9517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns self + other.
9527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        -INF + INF (or the reverse) cause InvalidOperation errors.
9547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
955636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
956267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
957267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
958636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
9597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
9607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
9617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
962636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
963636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
964636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
965636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
9667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
967636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity():
96859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                # If both INF, same sign => same as both, opposite => error.
969636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if self._sign != other._sign and other._isinfinity():
970636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    return context._raise_error(InvalidOperation, '-INF + INF')
971636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Decimal(self)
972636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if other._isinfinity():
97359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                return Decimal(other)  # Can't both be infinity here
9747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        shouldround = context._rounding_decision == ALWAYS_ROUND
9767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exp = min(self._exp, other._exp)
9787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        negativezero = 0
9797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context.rounding == ROUND_FLOOR and self._sign != other._sign:
98059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If the answer is 0, the sign should be negative, in this case.
9817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            negativezero = 1
9827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self and not other:
9847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            sign = min(self._sign, other._sign)
9857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if negativezero:
9867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                sign = 1
987353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal( (sign, (0,), exp))
988353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if shouldround:
989353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                ans = ans._fix(context)
990353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
9917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
99299b5548298ffc2ae5f03bd9ef873ce45a9844f0eFacundo Batista            exp = max(exp, other._exp - context.prec-1)
993353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = other._rescale(exp, context.rounding)
9947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if shouldround:
995dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger                ans = ans._fix(context)
9967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
9977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not other:
99899b5548298ffc2ae5f03bd9ef873ce45a9844f0eFacundo Batista            exp = max(exp, self._exp - context.prec-1)
999353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._rescale(exp, context.rounding)
10007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if shouldround:
1001dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger                ans = ans._fix(context)
10027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
10037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        op1 = _WorkRep(self)
10057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        op2 = _WorkRep(other)
10067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        op1, op2 = _normalize(op1, op2, shouldround, context.prec)
10077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        result = _WorkRep()
10097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if op1.sign != op2.sign:
10107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            # Equal and opposite
101117931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            if op1.int == op2.int:
1012353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                ans = Decimal((negativezero, (0,), exp))
1013353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if shouldround:
1014353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    ans = ans._fix(context)
1015353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return ans
101617931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            if op1.int < op2.int:
10177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                op1, op2 = op2, op1
101859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                # OK, now abs(op1) > abs(op2)
101917931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            if op1.sign == 1:
102017931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger                result.sign = 1
10217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                op1.sign, op2.sign = op2.sign, op1.sign
10227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            else:
102317931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger                result.sign = 0
102459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                # So we know the sign, and op1 > 0.
102517931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        elif op1.sign == 1:
10267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            result.sign = 1
102717931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            op1.sign, op2.sign = (0, 0)
102817931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        else:
102917931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            result.sign = 0
103059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # Now, op1 > abs(op2) > 0
10317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
103217931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        if op2.sign == 0:
1033636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            result.int = op1.int + op2.int
10347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
1035636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            result.int = op1.int - op2.int
10367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        result.exp = op1.exp
10387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        ans = Decimal(result)
10397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if shouldround:
1040dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger            ans = ans._fix(context)
10417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
10427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __radd__ = __add__
10447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __sub__(self, other, context=None):
1046353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return self - other"""
1047636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1048267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1049267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
10507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1051636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
1052636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context=context)
1053636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
1054636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
10557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1056353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self - other is computed as self + other.copy_negate()
1057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self.__add__(other.copy_negate(), context=context)
10587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rsub__(self, other, context=None):
1060353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return other - self"""
1061636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1062267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1063267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
10647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1065353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return other.__sub__(self, context=context)
10667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1067353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _increment(self):
10687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Special case of add, adding 1eExponent
10697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Since it is common, (rounding, for example) this adds
10717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        (sign)*one E self._exp to the number more efficiently than add.
10727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Assumes that self is nonspecial.
1074353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
10757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        For example:
10767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal('5.624e10')._increment() == Decimal('5.625e10')
10777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
10787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        L = list(self._int)
10797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        L[-1] += 1
10807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        spot = len(L)-1
10817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        while L[spot] == 10:
10827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            L[spot] = 0
10837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if spot == 0:
10847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                L[0:0] = [1]
10857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                break
10867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            L[spot-1] += 1
10877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            spot -= 1
1088353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal((self._sign, L, self._exp))
10897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __mul__(self, other, context=None):
10917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return self * other.
10927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        (+-) INF * 0 (or its reverse) raise InvalidOperation.
10947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1095636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1096267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1097267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
1098636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
10997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
11007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
11017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1102d87ac8f24da5dce860b559b69e6af59edd2c3eecRaymond Hettinger        resultsign = self._sign ^ other._sign
11037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1104636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
1105636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
1106636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
1107636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
1108636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1109636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity():
1110636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if not other:
1111636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    return context._raise_error(InvalidOperation, '(+-)INF * 0')
1112636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Infsign[resultsign]
1113636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1114636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if other._isinfinity():
1115636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if not self:
1116636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    return context._raise_error(InvalidOperation, '0 * (+-)INF')
1117636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Infsign[resultsign]
11187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        resultexp = self._exp + other._exp
11207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        shouldround = context._rounding_decision == ALWAYS_ROUND
11217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Special case for multiplying by zero
11237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self or not other:
11247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = Decimal((resultsign, (0,), resultexp))
11257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if shouldround:
112659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                # Fixing in case the exponent is out of bounds
1127dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger                ans = ans._fix(context)
11287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
11297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Special case for multiplying by power of 10
11317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._int == (1,):
11327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = Decimal((resultsign, other._int, resultexp))
11337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if shouldround:
1134dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger                ans = ans._fix(context)
11357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
11367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if other._int == (1,):
11377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = Decimal((resultsign, self._int, resultexp))
11387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if shouldround:
1139dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger                ans = ans._fix(context)
11407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
11417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1142636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        op1 = _WorkRep(self)
1143636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        op2 = _WorkRep(other)
1144636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
114559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        ans = Decimal((resultsign, map(int, str(op1.int * op2.int)), resultexp))
11467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if shouldround:
1147dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger            ans = ans._fix(context)
11487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
11507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __rmul__ = __mul__
11517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __div__(self, other, context=None):
11537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return self / other."""
11547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return self._divide(other, context=context)
11557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __truediv__ = __div__
11567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _divide(self, other, divmod = 0, context=None):
11587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return a / b, to context.prec precision.
11597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        divmod:
11617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        0 => true division
11627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        1 => (a //b, a%b)
11637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        2 => a //b
11647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        3 => a%b
11657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Actually, if divmod is 2 or 3 a tuple is returned, but errors for
11677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        computing the other value are not raised.
11687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1169636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1170267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1171267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            if divmod in (0, 1):
1172267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger                return NotImplemented
1173267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return (NotImplemented, NotImplemented)
1174636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
11757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
11767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
11777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1178353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        shouldround = context._rounding_decision == ALWAYS_ROUND
1179353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1180636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        sign = self._sign ^ other._sign
1181636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1182636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
1183636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
1184636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
1185636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if divmod:
1186636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    return (ans, ans)
11877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return ans
11887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1189636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity() and other._isinfinity():
1190636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if divmod:
1191353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    reloco = (context._raise_error(InvalidOperation,
1192636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                                            '(+-)INF // (+-)INF'),
1193636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                            context._raise_error(InvalidOperation,
1194636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                                            '(+-)INF % (+-)INF'))
1195353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return reloco
11967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
11977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if self._isinfinity():
11997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                if divmod == 1:
12007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    return (Infsign[sign],
12017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                            context._raise_error(InvalidOperation, 'INF % x'))
12027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                elif divmod == 2:
12037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    return (Infsign[sign], NaN)
12047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                elif divmod == 3:
12057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    return (Infsign[sign],
12067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                            context._raise_error(InvalidOperation, 'INF % x'))
1207636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Infsign[sign]
1208636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1209636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if other._isinfinity():
1210636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if divmod:
1211353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    otherside = Decimal(self)
1212353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if shouldround and (divmod == 1 or divmod == 3):
1213353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        otherside = otherside._fix(context)
1214353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return (Decimal((sign, (0,), 0)), otherside)
1215636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                context._raise_error(Clamped, 'Division by infinity')
1216636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Decimal((sign, (0,), context.Etiny()))
1217636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1218636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        # Special cases for zeroes
1219636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if not self and not other:
1220636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if divmod:
1221636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return context._raise_error(DivisionUndefined, '0 / 0', 1)
1222636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return context._raise_error(DivisionUndefined, '0 / 0')
1223636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1224636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if not self:
1225636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if divmod:
1226353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                otherside = Decimal((self._sign, (0,), min(self._exp, other._exp)))
1227353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if shouldround and (divmod == 1 or divmod == 3):
1228353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    otherside = otherside._fix(context)
12297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return (Decimal((sign, (0,), 0)),  otherside)
1230636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            exp = self._exp - other._exp
1231353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal((sign, (0,), exp))
1232353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = ans._fix(context)
1233353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
12347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1235636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if not other:
1236636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if divmod:
12377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return context._raise_error(DivisionByZero, 'divmod(x,0)',
12387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                                           sign, 1)
1239636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return context._raise_error(DivisionByZero, 'x / 0', sign)
12407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
124159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # OK, so neither = 0, INF or NaN
12427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
124359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # If we're dividing into ints, and self < other, stop.
124459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # self.__abs__(0) does not round.
12457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if divmod and (self.__abs__(0, context) < other.__abs__(0, context)):
12467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if divmod == 1 or divmod == 3:
12487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                exp = min(self._exp, other._exp)
1249353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                ans2 = self._rescale(exp, context.rounding)
12507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                if shouldround:
1251dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger                    ans2 = ans2._fix(context)
12527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return (Decimal( (sign, (0,), 0) ),
12537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                        ans2)
12547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            elif divmod == 2:
125659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                # Don't round the mod part, if we don't need it.
12577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return (Decimal( (sign, (0,), 0) ), Decimal(self))
12587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        op1 = _WorkRep(self)
12607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        op2 = _WorkRep(other)
12617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        op1, op2, adjust = _adjust_coefficients(op1, op2)
1262636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        res = _WorkRep( (sign, 0, (op1.exp - op2.exp)) )
12637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if divmod and res.exp > context.prec + 1:
12647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return context._raise_error(DivisionImpossible)
12657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1266636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        prec_limit = 10 ** context.prec
12677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        while 1:
1268636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            while op2.int <= op1.int:
1269636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                res.int += 1
1270636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                op1.int -= op2.int
12717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if res.exp == 0 and divmod:
1272636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if res.int >= prec_limit and shouldround:
12737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    return context._raise_error(DivisionImpossible)
12747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                otherside = Decimal(op1)
12757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                exp = min(self._exp, other._exp)
1276353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                otherside = otherside._rescale(exp, context.rounding)
1277353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if shouldround and (divmod == 1 or divmod == 3):
1278dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger                    otherside = otherside._fix(context)
12797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return (Decimal(res), otherside)
12807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1281636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if op1.int == 0 and adjust >= 0 and not divmod:
12827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                break
1283636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if res.int >= prec_limit and shouldround:
12847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                if divmod:
12857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    return context._raise_error(DivisionImpossible)
12867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                shouldround=1
12877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                # Really, the answer is a bit higher, so adding a one to
12887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                # the end will make sure the rounding is right.
1289636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if op1.int != 0:
1290636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    res.int *= 10
1291636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    res.int += 1
12927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    res.exp -= 1
12937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                break
1295636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            res.int *= 10
12967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            res.exp -= 1
12977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            adjust += 1
1298636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            op1.int *= 10
12997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            op1.exp -= 1
13007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        ans = Decimal(res)
13027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if shouldround:
1303dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger            ans = ans._fix(context)
13047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
13057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rdiv__(self, other, context=None):
13077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Swaps self/other and returns __div__."""
1308636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1309267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1310267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
13117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return other.__div__(self, context=context)
13127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __rtruediv__ = __rdiv__
13137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __divmod__(self, other, context=None):
13157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
13167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        (self // other, self % other)
13177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
13187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return self._divide(other, 1, context)
13197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rdivmod__(self, other, context=None):
13217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Swaps self/other and returns __divmod__."""
1322636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1323267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1324267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
13257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return other.__divmod__(self, context=context)
13267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __mod__(self, other, context=None):
13287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
13297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self % other
13307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1331636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1332267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1333267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
13347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1335636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
1336636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
1337636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
1338636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
13397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self and not other:
13417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return context._raise_error(InvalidOperation, 'x % 0')
13427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return self._divide(other, 3, context)[1]
13447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rmod__(self, other, context=None):
13467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Swaps self/other and returns __mod__."""
1347636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1348267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1349267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
13507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return other.__mod__(self, context=context)
13517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def remainder_near(self, other, context=None):
13537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
13547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Remainder nearest to 0-  abs(remainder-near) <= other/2
13557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1356636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
1357636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
13587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1359353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
13607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1361353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
1362353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
1363353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
13647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1365353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self == +/-infinity -> InvalidOperation
1366353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
1367353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1368353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'remainder_near(infinity, x)')
13697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1370353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # other == 0 -> either InvalidOperation or DivisionUndefined
1371353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other:
1372353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self:
1373353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation,
1374353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                            'remainder_near(x, 0)')
1375353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1376353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(DivisionUndefined,
1377353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                            'remainder_near(0, 0)')
13787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1379353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # other = +/-infinity -> remainder = self
1380353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._isinfinity():
1381353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal(self)
1382353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
13837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1384353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self = 0 -> remainder = self, with ideal exponent
1385353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ideal_exponent = min(self._exp, other._exp)
1386353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
1387353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal((self._sign, (0,), ideal_exponent))
1388353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
13897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1390353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # catch most cases of large or small quotient
1391353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        expdiff = self.adjusted() - other.adjusted()
1392353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if expdiff >= context.prec + 1:
1393353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # expdiff >= prec+1 => abs(self/other) > 10**prec
1394353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(DivisionImpossible)[0]
1395353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if expdiff <= -2:
1396353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # expdiff <= -2 => abs(self/other) < 0.1
1397353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._rescale(ideal_exponent, context.rounding)
1398353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
13997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1400353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # adjust both arguments to have the same exponent, then divide
1401353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op1 = _WorkRep(self)
1402353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op2 = _WorkRep(other)
1403353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if op1.exp >= op2.exp:
1404353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            op1.int *= 10**(op1.exp - op2.exp)
14057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
1406353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            op2.int *= 10**(op2.exp - op1.exp)
1407353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        q, r = divmod(op1.int, op2.int)
1408353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # remainder is r*10**ideal_exponent; other is +/-op2.int *
1409353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 10**ideal_exponent.   Apply correction to ensure that
1410353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # abs(remainder) <= abs(other)/2
1411353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if 2*r + (q&1) > op2.int:
1412353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            r -= op2.int
1413353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            q += 1
1414353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1415353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if q >= 10**context.prec:
1416353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(DivisionImpossible)[0]
1417353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1418353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # result has same sign as self unless r is negative
1419353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        sign = self._sign
1420353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if r < 0:
1421353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sign = 1-sign
1422353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            r = -r
14237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1424353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = Decimal((sign, map(int, str(r)), ideal_exponent))
1425353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans._fix(context)
14267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __floordiv__(self, other, context=None):
14287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """self // other"""
14297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return self._divide(other, 2, context)[0]
14307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rfloordiv__(self, other, context=None):
14327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Swaps self/other and returns __floordiv__."""
1433636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1434267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1435267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
14367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return other.__floordiv__(self, context=context)
14377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __float__(self):
14397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Float representation."""
14407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return float(str(self))
14417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __int__(self):
144346b0802ccd9a9c47b27a285526fbb2a8bee5b8cbBrett Cannon        """Converts self to an int, truncating if necessary."""
1444636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
1445636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isnan():
1446636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                context = getcontext()
1447636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return context._raise_error(InvalidContext)
1448636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            elif self._isinfinity():
144959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                raise OverflowError("Cannot convert infinity to long")
1450353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        s = (-1)**self._sign
14517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._exp >= 0:
1452353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return s*int(''.join(map(str, self._int)))*10**self._exp
1453605ed0248375bbf87bbd1d80afc7c6918fd3ce2bRaymond Hettinger        else:
1454353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return s*int(''.join(map(str, self._int))[:self._exp] or '0')
14557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __long__(self):
14577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Converts to a long.
14587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Equivalent to long(int(self))
14607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
14617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return long(self.__int__())
14627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1463353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _fix_nan(self, context):
1464353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Decapitate the payload of a NaN to fit the context"""
1465353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        payload = self._int
1466353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1467353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # maximum length of payload is precision if _clamp=0,
1468353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # precision-1 if _clamp=1.
1469353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        max_payload_len = context.prec - context._clamp
1470353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if len(payload) > max_payload_len:
1471353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            pos = len(payload)-max_payload_len
1472353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while pos < len(payload) and payload[pos] == 0:
1473353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                pos += 1
1474353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            payload = payload[pos:]
1475353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Decimal((self._sign, payload, self._exp))
1476353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self
1477353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1478dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger    def _fix(self, context):
14797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Round if it is necessary to keep self within prec precision.
14807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Rounds and fixes the exponent.  Does not raise on a sNaN.
14827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Arguments:
14847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self - Decimal instance
14857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        context - context used.
14867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1487636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
14887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
14897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
14907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1491353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
1492353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self._isnan():
1493353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # decapitate payload if necessary
1494353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self._fix_nan(context)
1495353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1496353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # self is +/-Infinity; return unaltered
1497353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self
14987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1499353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if self is zero then exponent should be between Etiny and
1500353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1501353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Etiny = context.Etiny()
1502353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Etop = context.Etop()
15037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
1504353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            exp_max = [context.Emax, Etop][context._clamp]
1505353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            new_exp = min(max(self._exp, Etiny), exp_max)
1506353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if new_exp != self._exp:
1507353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Clamped)
1508353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Decimal((self._sign, (0,), new_exp))
15097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            else:
1510353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self
15117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1512353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp_min is the smallest allowable exponent of the result,
1513353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # equal to max(self.adjusted()-context.prec+1, Etiny)
1514353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exp_min = len(self._int) + self._exp - context.prec
1515353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if exp_min > Etop:
1516353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # overflow: exp_min > Etop iff self.adjusted() > Emax
1517353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
1518353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Rounded)
1519353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(Overflow, 'above Emax', self._sign)
1520353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_is_subnormal = exp_min < Etiny
1521353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_is_subnormal:
1522353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Subnormal)
1523353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            exp_min = Etiny
15247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1525353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # round if self has too many digits
1526353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp < exp_min:
15277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context._raise_error(Rounded)
1528353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._rescale(exp_min, context.rounding)
1529353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans != self:
1530353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Inexact)
1531353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_is_subnormal:
1532353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    context._raise_error(Underflow)
1533353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if not ans:
1534353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        # raise Clamped on underflow to 0
1535353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        context._raise_error(Clamped)
1536353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                elif len(ans._int) == context.prec+1:
1537353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    # we get here only if rescaling rounds the
1538353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    # cofficient up to exactly 10**context.prec
1539353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if ans._exp < Etop:
1540353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        ans = Decimal((ans._sign, ans._int[:-1], ans._exp+1))
1541353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    else:
1542353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        # Inexact and Rounded have already been raised
1543353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        ans = context._raise_error(Overflow, 'above Emax',
1544353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                                   self._sign)
15457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
15467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1547353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # fold down if _clamp == 1 and self has too few digits
1548353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context._clamp == 1 and self._exp > Etop:
1549353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Clamped)
1550353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            self_padded = self._int + (0,)*(self._exp - Etop)
1551353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Decimal((self._sign, self_padded, Etop))
15527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1553353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # here self was representable to begin with; return unchanged
1554353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self
15557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
15567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    _pick_rounding_function = {}
15577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1558353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # for each of the rounding functions below:
1559353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #   self is a finite, nonzero Decimal
1560353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #   prec is an integer satisfying 0 <= prec < len(self._int)
1561353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # the rounded result will have exponent self._exp + len(self._int) - prec;
15627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1563353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_down(self, prec):
1564353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Also known as round-towards-0, truncate."""
1565353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        newexp = self._exp + len(self._int) - prec
1566353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal((self._sign, self._int[:prec] or (0,), newexp))
15677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1568353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_up(self, prec):
1569353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds away from 0."""
1570353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        newexp = self._exp + len(self._int) - prec
1571353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        tmp = Decimal((self._sign, self._int[:prec] or (0,), newexp))
1572353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        for digit in self._int[prec:]:
1573353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if digit != 0:
1574353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return tmp._increment()
15757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return tmp
15767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1577353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_half_up(self, prec):
1578353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds 5 up (away from 0)"""
1579353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._int[prec] >= 5:
1580353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_up(prec)
1581353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
1582353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_down(prec)
15837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1584353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_half_down(self, prec):
15857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Round 5 down"""
1586353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._int[prec] == 5:
15877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            for digit in self._int[prec+1:]:
15887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                if digit != 0:
15897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    break
1590353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1591353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self._round_down(prec)
1592353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self._round_half_up(prec)
15937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1594353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_half_even(self, prec):
1595353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Round 5 to even, rest to nearest."""
1596353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if prec and self._int[prec-1] & 1:
1597353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_half_up(prec)
1598353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
1599353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_half_down(prec)
16007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1601353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_ceiling(self, prec):
16027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Rounds up (not away from 0 if negative.)"""
16037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign:
1604353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_down(prec)
16057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
1606353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_up(prec)
16077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1608353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_floor(self, prec):
16097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Rounds down (not towards 0 if negative)"""
16107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self._sign:
1611353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_down(prec)
16127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
1613353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_up(prec)
16147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1615353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_05up(self, prec):
1616353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Round down unless digit prec-1 is 0 or 5."""
1617353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if prec == 0 or self._int[prec-1] in (0, 5):
1618353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_up(prec)
1619353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
1620353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_down(prec)
1621353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1622353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def fma(self, other, third, context=None):
1623353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Fused multiply-add.
16247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1625353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Returns self*other+third with no rounding of the intermediate
1626353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        product self*other.
1627353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1628353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self and other are multiplied together, with no rounding of
1629353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        the result.  The third operand is then added to the result,
1630353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        and a single final rounding is performed.
16317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1632353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1633353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
1634353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        third = _convert_other(third, raiseit=True)
1635636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
16367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
16377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
16387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1639353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # do self*other in fresh context with no traps and no rounding
1640353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        mul_context = Context(traps=[], flags=[],
1641353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                              _rounding_decision=NEVER_ROUND)
1642353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        product = self.__mul__(other, mul_context)
16437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1644353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if mul_context.flags[InvalidOperation]:
1645353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # reraise in current context
1646353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1647353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'invalid multiplication in fma',
1648353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, product)
16497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1650353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = product.__add__(third, context)
1651353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
16527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1653353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _power_modulo(self, other, modulo, context=None):
1654353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Three argument version of __pow__"""
16557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1656353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if can't convert other and modulo to Decimal, raise
1657353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # TypeError; there's no point returning NotImplemented (no
1658353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # equivalent of __rpow__ for three argument pow)
1659353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
1660353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        modulo = _convert_other(modulo, raiseit=True)
16617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1662353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
1663353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
16647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1665353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # deal with NaNs: if there are any sNaNs then first one wins,
1666353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (i.e. behaviour for NaNs is identical to that of fma)
1667353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_is_nan = self._isnan()
1668353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other_is_nan = other._isnan()
1669353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        modulo_is_nan = modulo._isnan()
1670353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_is_nan or other_is_nan or modulo_is_nan:
1671353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self_is_nan == 2:
1672353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation, 'sNaN',
1673353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, self)
1674353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other_is_nan == 2:
1675353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation, 'sNaN',
1676353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, other)
1677353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if modulo_is_nan == 2:
1678353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation, 'sNaN',
1679353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, modulo)
1680353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self_is_nan:
1681353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self
1682353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other_is_nan:
1683353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return other
1684353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return modulo
1685353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1686353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # check inputs: we apply same restrictions as Python's pow()
1687353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (self._isinteger() and
1688353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                other._isinteger() and
1689353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                modulo._isinteger()):
1690353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1691353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'pow() 3rd argument not allowed '
1692353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'unless all arguments are integers')
1693353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other < 0:
1694353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1695353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'pow() 2nd argument cannot be '
1696353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'negative when 3rd argument specified')
1697353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not modulo:
1698353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1699353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'pow() 3rd argument cannot be 0')
1700353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1701353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # additional restriction for decimal: the modulus must be less
1702353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # than 10**prec in absolute value
1703353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if modulo.adjusted() >= context.prec:
1704353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1705353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'insufficient precision: pow() 3rd '
1706353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'argument must not have more than '
1707353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'precision digits')
1708353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1709353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # define 0**0 == NaN, for consistency with two-argument pow
1710353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (even though it hurts!)
1711353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other and not self:
1712353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1713353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'at least one of pow() 1st argument '
1714353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'and 2nd argument must be nonzero ;'
1715353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        '0**0 is not defined')
1716353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1717353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute sign of result
1718353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._iseven():
1719353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sign = 0
1720353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
1721353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sign = self._sign
1722353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1723353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # convert modulo to a Python integer, and self and other to
1724353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Decimal integers (i.e. force their exponents to be >= 0)
1725353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        modulo = abs(int(modulo))
1726353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        base = _WorkRep(self.to_integral_value())
1727353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exponent = _WorkRep(other.to_integral_value())
1728353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1729353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute result using integer pow()
1730353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1731353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        for i in xrange(exponent.exp):
1732353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            base = pow(base, 10, modulo)
1733353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        base = pow(base, exponent.int, modulo)
1734353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1735353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal((sign, map(int, str(base)), 0))
1736353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1737353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _power_exact(self, other, p):
1738353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Attempt to compute self**other exactly.
1739353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1740353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Given Decimals self and other and an integer p, attempt to
1741353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        compute an exact result for the power self**other, with p
1742353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        digits of precision.  Return None if self**other is not
1743353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exactly representable in p digits.
1744353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1745353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Assumes that elimination of special cases has already been
1746353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        performed: self and other must both be nonspecial; self must
1747353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        be positive and not numerically equal to 1; other must be
1748353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        nonzero.  For efficiency, other._exp should not be too large,
1749353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        so that 10**abs(other._exp) is a feasible calculation."""
1750353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1751353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # In the comments below, we write x for the value of self and
1752353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # y for the value of other.  Write x = xc*10**xe and y =
1753353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # yc*10**ye.
1754353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1755353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # The main purpose of this method is to identify the *failure*
1756353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # of x**y to be exactly representable with as little effort as
1757353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # possible.  So we look for cheap and easy tests that
1758353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # eliminate the possibility of x**y being exact.  Only if all
1759353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # these tests are passed do we go on to actually compute x**y.
1760353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1761353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Here's the main idea.  First normalize both x and y.  We
1762353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # express y as a rational m/n, with m and n relatively prime
1763353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # and n>0.  Then for x**y to be exactly representable (at
1764353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # *any* precision), xc must be the nth power of a positive
1765353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # integer and xe must be divisible by n.  If m is negative
1766353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # then additionally xc must be a power of either 2 or 5, hence
1767353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # a power of 2**n or 5**n.
1768353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1769353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # There's a limit to how small |y| can be: if y=m/n as above
1770353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # then:
1771353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1772353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #  (1) if xc != 1 then for the result to be representable we
1773353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      need xc**(1/n) >= 2, and hence also xc**|y| >= 2.  So
1774353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1775353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      2**(1/|y|), hence xc**|y| < 2 and the result is not
1776353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      representable.
1777353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1778353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #  (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1.  Hence if
1779353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      |y| < 1/|xe| then the result is not representable.
1780353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1781353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Note that since x is not equal to 1, at least one of (1) and
1782353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (2) must apply.  Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1783353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1784353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1785353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # There's also a limit to how large y can be, at least if it's
1786353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # positive: the normalized result will have coefficient xc**y,
1787353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # so if it's representable then xc**y < 10**p, and y <
1788353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # p/log10(xc).  Hence if y*log10(xc) >= p then the result is
1789353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # not exactly representable.
1790353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1791353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1792353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # so |y| < 1/xe and the result is not representable.
1793353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1794353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # < 1/nbits(xc).
1795353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1796353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        x = _WorkRep(self)
1797353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        xc, xe = x.int, x.exp
1798353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while xc % 10 == 0:
1799353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xc //= 10
1800353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xe += 1
1801353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1802353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        y = _WorkRep(other)
1803353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        yc, ye = y.int, y.exp
1804353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while yc % 10 == 0:
1805353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            yc //= 10
1806353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ye += 1
1807353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1808353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # case where xc == 1: result is 10**(xe*y), with xe*y
1809353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # required to be an integer
1810353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if xc == 1:
1811353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ye >= 0:
1812353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exponent = xe*yc*10**ye
1813353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1814353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exponent, remainder = divmod(xe*yc, 10**-ye)
1815353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if remainder:
1816353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1817353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if y.sign == 1:
1818353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exponent = -exponent
1819353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # if other is a nonnegative integer, use ideal exponent
1820353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._isinteger() and other._sign == 0:
1821353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                ideal_exponent = self._exp*int(other)
1822353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                zeros = min(exponent-ideal_exponent, p-1)
1823353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1824353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                zeros = 0
1825353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Decimal((0, (1,) + (0,)*zeros, exponent-zeros))
1826353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1827353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # case where y is negative: xc must be either a power
1828353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # of 2 or a power of 5.
1829353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if y.sign == 1:
1830353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            last_digit = xc % 10
1831353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if last_digit in (2,4,6,8):
1832353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # quick test for power of 2
1833353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if xc & -xc != xc:
1834353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1835353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # now xc is a power of 2; e is its exponent
1836353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                e = _nbits(xc)-1
1837353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # find e*y and xe*y; both must be integers
1838353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if ye >= 0:
1839353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    y_as_int = yc*10**ye
1840353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e = e*y_as_int
1841353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xe = xe*y_as_int
1842353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                else:
1843353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    ten_pow = 10**-ye
1844353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e, remainder = divmod(e*yc, ten_pow)
1845353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if remainder:
1846353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return None
1847353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xe, remainder = divmod(xe*yc, ten_pow)
1848353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if remainder:
1849353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return None
1850353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1851353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if e*65 >= p*93: # 93/65 > log(10)/log(5)
1852353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1853353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                xc = 5**e
1854353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1855353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            elif last_digit == 5:
1856353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # e >= log_5(xc) if xc is a power of 5; we have
1857353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # equality all the way up to xc=5**2658
1858353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                e = _nbits(xc)*28//65
1859353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                xc, remainder = divmod(5**e, xc)
1860353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if remainder:
1861353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1862353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                while xc % 5 == 0:
1863353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xc //= 5
1864353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e -= 1
1865353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if ye >= 0:
1866353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    y_as_integer = yc*10**ye
1867353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e = e*y_as_integer
1868353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xe = xe*y_as_integer
1869353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                else:
1870353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    ten_pow = 10**-ye
1871353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e, remainder = divmod(e*yc, ten_pow)
1872353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if remainder:
1873353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return None
1874353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xe, remainder = divmod(xe*yc, ten_pow)
1875353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if remainder:
1876353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return None
1877353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if e*3 >= p*10: # 10/3 > log(10)/log(2)
1878353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1879353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                xc = 2**e
1880353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1881353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
18827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1883353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if xc >= 10**p:
1884353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1885353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xe = -e-xe
1886353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Decimal((0, map(int, str(xc)), xe))
18877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1888353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # now y is positive; find m and n such that y = m/n
1889353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ye >= 0:
1890353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            m, n = yc*10**ye, 1
1891353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
1892353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1893353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1894353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xc_bits = _nbits(xc)
1895353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1896353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1897353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            m, n = yc, 10**(-ye)
1898353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while m % 2 == n % 2 == 0:
1899353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                m //= 2
1900353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n //= 2
1901353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while m % 5 == n % 5 == 0:
1902353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                m //= 5
1903353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n //= 5
1904353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1905353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute nth root of xc*10**xe
1906353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if n > 1:
1907353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # if 1 < xc < 2**n then xc isn't an nth power
1908353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if xc != 1 and xc_bits <= n:
1909353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1910353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1911353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xe, rem = divmod(xe, n)
1912353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if rem != 0:
1913353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1914353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1915353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # compute nth root of xc using Newton's method
1916353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            a = 1L << -(-_nbits(xc)//n) # initial estimate
1917353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while True:
1918353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                q, r = divmod(xc, a**(n-1))
1919353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if a <= q:
1920353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
1921353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                else:
1922353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    a = (a*(n-1) + q)//n
1923353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if not (a == q and r == 0):
1924353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1925353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xc = a
1926353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1927353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # now xc*10**xe is the nth root of the original xc*10**xe
1928353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute mth power of xc*10**xe
1929353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1930353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1931353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 10**p and the result is not representable.
1932353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if xc > 1 and m > p*100//_log10_lb(xc):
1933353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return None
1934353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        xc = xc**m
1935353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        xe *= m
1936353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if xc > 10**p:
1937353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return None
1938353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1939353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # by this point the result *is* exactly representable
1940353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # adjust the exponent to get as close as possible to the ideal
1941353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exponent, if necessary
1942353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        str_xc = str(xc)
1943353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._isinteger() and other._sign == 0:
1944353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ideal_exponent = self._exp*int(other)
1945353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            zeros = min(xe-ideal_exponent, p-len(str_xc))
1946353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
1947353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            zeros = 0
1948353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal((0, map(int, str_xc)+[0,]*zeros, xe-zeros))
1949cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
1950353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def __pow__(self, other, modulo=None, context=None):
1951353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return self ** other [ % modulo].
19527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1953353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        With two arguments, compute self**other.
19547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1955353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        With three arguments, compute (self**other) % modulo.  For the
1956353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        three argument form, the following restrictions on the
1957353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        arguments hold:
19587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1959353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - all three arguments must be integral
1960353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - other must be nonnegative
1961353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - either self or other (or both) must be nonzero
1962353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - modulo must be nonzero and must have at most p digits,
1963353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista           where p is the context precision.
19647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1965353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        If any of these restrictions is violated the InvalidOperation
1966353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        flag is raised.
1967353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1968353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result of pow(self, other, modulo) is identical to the
1969353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        result that would be obtained by computing (self**other) %
1970353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        modulo with unbounded precision, but is computed more
1971353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        efficiently.  It is always exact.
1972353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
1973353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1974353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if modulo is not None:
1975353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._power_modulo(other, modulo, context)
19767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1977636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1978267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1979267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
19807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1981353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
1982353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
19837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1984353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # either argument is a NaN => result is NaN
1985353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
1986353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
1987353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
19887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1989353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
1990353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other:
1991353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if not self:
1992353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation, '0 ** 0')
1993353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1994353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_p1
19957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1996353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # result has sign 1 iff self._sign is 1 and other is an odd integer
1997353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        result_sign = 0
1998353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign == 1:
1999353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._isinteger():
2000353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if not other._iseven():
2001353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    result_sign = 1
2002353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2003353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # -ve**noninteger = NaN
2004353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # (-0)**noninteger = 0**noninteger
2005353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self:
2006353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return context._raise_error(InvalidOperation,
2007353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        'x ** y with x negative and y not an integer')
2008353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # negate self, without doing any unwanted rounding
2009353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            self = Decimal((0, self._int, self._exp))
2010353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2011353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2012353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2013353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._sign == 0:
2014353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Decimal((result_sign, (0,), 0))
2015353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2016353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Infsign[result_sign]
2017353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2018353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
2019353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
2020353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._sign == 0:
2021353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Infsign[result_sign]
2022353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2023353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Decimal((result_sign, (0,), 0))
2024353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2025353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 1**other = 1, but the choice of exponent and the flags
2026353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # depend on the exponent of self, and on whether other is a
2027353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # positive integer, a negative integer, or neither
2028353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self == Dec_p1:
2029353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._isinteger():
2030353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # exp = max(self._exp*max(int(other), 0),
2031353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # 1-context.prec) but evaluating int(other) directly
2032353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # is dangerous until we know other is small (other
2033353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # could be 1e999999999)
2034353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other._sign == 1:
2035353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    multiplier = 0
2036353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                elif other > context.prec:
2037353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    multiplier = context.prec
2038353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                else:
2039353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    multiplier = int(other)
2040353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2041353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exp = self._exp * multiplier
2042353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if exp < 1-context.prec:
2043353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    exp = 1-context.prec
2044353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    context._raise_error(Rounded)
2045353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2046353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Inexact)
2047353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Rounded)
2048353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exp = 1-context.prec
2049353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2050353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Decimal((result_sign, (1,)+(0,)*-exp, exp))
2051353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2052353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute adjusted exponent of self
2053353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_adj = self.adjusted()
2054353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2055353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self ** infinity is infinity if self > 1, 0 if self < 1
2056353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self ** -infinity is infinity if self < 1, 0 if self > 1
2057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._isinfinity():
2058353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if (other._sign == 0) == (self_adj < 0):
2059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Decimal((result_sign, (0,), 0))
2060353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2061353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Infsign[result_sign]
2062353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2063353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # from here on, the result always goes through the call
2064353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # to _fix at the end of this function.
2065353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = None
2066353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2067353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # crude test to catch cases of extreme overflow/underflow.  If
2068353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2069353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2070353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self**other >= 10**(Emax+1), so overflow occurs.  The test
2071353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # for underflow is similar.
2072353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        bound = self._log10_exp_bound() + other.adjusted()
2073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if (self_adj >= 0) == (other._sign == 0):
2074353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # self > 1 and other +ve, or self < 1 and other -ve
2075353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # possibility of overflow
2076353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if bound >= len(str(context.Emax)):
2077353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                ans = Decimal((result_sign, (1,), context.Emax+1))
2078353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2079353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # self > 1 and other -ve, or self < 1 and other +ve
2080353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # possibility of underflow to 0
2081353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            Etiny = context.Etiny()
2082353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if bound >= len(str(-Etiny)):
2083353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                ans = Decimal((result_sign, (1,), Etiny-1))
2084353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2085353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # try for an exact result with precision +1
2086353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans is None:
2087353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._power_exact(other, context.prec + 1)
2088353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans is not None and result_sign == 1:
2089353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                ans = Decimal((1, ans._int, ans._exp))
2090353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2091353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # usual case: inexact result, x**y computed directly as exp(y*log(x))
2092353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans is None:
2093353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            p = context.prec
2094353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            x = _WorkRep(self)
2095353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xc, xe = x.int, x.exp
2096353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            y = _WorkRep(other)
2097353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            yc, ye = y.int, y.exp
2098353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if y.sign == 1:
2099353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                yc = -yc
2100353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2101353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # compute correctly rounded result:  start with precision +3,
2102353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # then increase precision until result is unambiguously roundable
2103353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            extra = 3
2104353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while True:
2105353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2106353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if coeff % (5*10**(len(str(coeff))-p-1)):
2107353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
2108353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                extra += 3
2109353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2110353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal((result_sign, map(int, str(coeff)), exp))
2111353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2112353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the specification says that for non-integer other we need to
2113353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # raise Inexact, even when the result is actually exact.  In
2114353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the same way, we need to raise Underflow here if the result
2115353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # is subnormal.  (The call to _fix will take care of raising
2116353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Rounded and Subnormal, as usual.)
2117353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other._isinteger():
2118353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
2119353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # pad with zeros up to length context.prec+1 if necessary
2120353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if len(ans._int) <= context.prec:
2121353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                expdiff = context.prec+1 - len(ans._int)
2122353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                ans = Decimal((ans._sign, ans._int+(0,)*expdiff, ans._exp-expdiff))
2123353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans.adjusted() < context.Emin:
2124353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Underflow)
2125353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2126353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # unlike exp, ln and log10, the power function respects the
2127353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # rounding mode; no need to use ROUND_HALF_EVEN here
2128353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2129353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
2130353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2131353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def __rpow__(self, other, context=None):
2132353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Swaps self/other and returns __pow__."""
2133353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other)
2134353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other is NotImplemented:
2135353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return other
2136353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return other.__pow__(self, context=context)
2137353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2138353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def normalize(self, context=None):
2139353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
2140353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2141353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2142353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2143353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2144353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
2145353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._check_nans(context=context)
2146353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans:
2147353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return ans
2148353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2149353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        dup = self._fix(context)
2150353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if dup._isinfinity():
2151353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return dup
2152353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2153353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not dup:
2154353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Decimal( (dup._sign, (0,), 0) )
2155353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exp_max = [context.Emax, context.Etop()][context._clamp]
2156353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        end = len(dup._int)
21577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exp = dup._exp
2158353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while dup._int[end-1] == 0 and exp < exp_max:
21597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            exp += 1
21607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            end -= 1
21617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return Decimal( (dup._sign, dup._int[:end], exp) )
21627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2163bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista    def quantize(self, exp, rounding=None, context=None, watchexp=True):
21647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Quantize self so its exponent is the same as that of exp.
21657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
21667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Similar to self._rescale(exp._exp) but with error checking.
21677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2168bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista        exp = _convert_other(exp, raiseit=True)
2169bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista
2170353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2171353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2172353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if rounding is None:
2173353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rounding = context.rounding
2174353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2175636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or exp._is_special:
2176636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(exp, context)
2177636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
2178636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
21797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2180636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if exp._isinfinity() or self._isinfinity():
2181636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if exp._isinfinity() and self._isinfinity():
218259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                    return self  # if both are inf, it is OK
2183636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return context._raise_error(InvalidOperation,
2184636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                                        'quantize with one INF')
2185353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2186bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista        # if we're not watching exponents, do a simple rescale
2187bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista        if not watchexp:
2188bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista            ans = self._rescale(exp._exp, rounding)
2189bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista            # raise Inexact and Rounded where appropriate
2190bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista            if ans._exp > self._exp:
2191bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista                context._raise_error(Rounded)
2192bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista                if ans != self:
2193bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista                    context._raise_error(Inexact)
2194bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista            return ans
2195bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista
2196353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp._exp should be between Etiny and Emax
2197353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (context.Etiny() <= exp._exp <= context.Emax):
2198353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2199353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                   'target exponent out of bounds in quantize')
2200353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2201353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2202353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal((self._sign, (0,), exp._exp))
2203353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
2204353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2205353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_adjusted = self.adjusted()
2206353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_adjusted > context.Emax:
2207353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2208353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'exponent of quantize result too large for current context')
2209353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_adjusted - exp._exp + 1 > context.prec:
2210353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2211353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'quantize result has too many digits for current context')
2212353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2213353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._rescale(exp._exp, rounding)
2214353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans.adjusted() > context.Emax:
2215353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2216353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'exponent of quantize result too large for current context')
2217353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if len(ans._int) > context.prec:
2218353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2219353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'quantize result has too many digits for current context')
2220353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2221353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # raise appropriate flags
2222353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans._exp > self._exp:
2223353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Rounded)
2224353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans != self:
2225353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Inexact)
2226353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans and ans.adjusted() < context.Emin:
2227353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Subnormal)
2228353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2229353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # call to fix takes care of any necessary folddown
2230353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2231353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
22327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
22337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def same_quantum(self, other):
22347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Test whether self and other have the same exponent.
22357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
22367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        same as self._exp == other._exp, except NaN == sNaN
22377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2238636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
2239636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isnan() or other._isnan():
2240636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return self._isnan() and other._isnan() and True
2241636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity() or other._isinfinity():
2242636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return self._isinfinity() and other._isinfinity() and True
22437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return self._exp == other._exp
22447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2245353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _rescale(self, exp, rounding):
2246353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rescale self so that the exponent is exp, either by padding with zeros
2247353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        or by truncating digits, using the given rounding mode.
2248353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2249353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Specials are returned without change.  This operation is
2250353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        quiet: it raises no flags, and uses no information from the
2251353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.
22527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
22537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exp = exp to scale to (an integer)
2254353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = rounding mode
22557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2256636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
2257353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self
22587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
2259353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Decimal((self._sign, (0,), exp))
22607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2261353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp >= exp:
2262353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # pad answer with zeros if necessary
2263353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Decimal((self._sign, self._int + (0,)*(self._exp - exp), exp))
22647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2265353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # too many digits; round and lose data.  If self.adjusted() <
2266353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp-1, replace self by 10**(exp-1) before rounding
2267353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        digits = len(self._int) + self._exp - exp
22687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if digits < 0:
2269353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            self = Decimal((self._sign, (1,), exp-1))
2270353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            digits = 0
2271353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        this_function = getattr(self, self._pick_rounding_function[rounding])
2272353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return this_function(digits)
22737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2274353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def to_integral_exact(self, rounding=None, context=None):
2275353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds to a nearby integer.
22767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2277353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        If no rounding mode is specified, take the rounding mode from
2278353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        the context.  This method raises the Rounded and Inexact flags
2279353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        when appropriate.
22807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2281353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        See also: to_integral_value, which does exactly the same as
2282353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        this method except that it doesn't raise Inexact or Rounded.
2283353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2284636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
2285636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
2286636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
2287636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
2288353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self
22897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._exp >= 0:
22907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return self
2291353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2292353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Decimal((self._sign, (0,), 0))
2293636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
2294636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
2295353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if rounding is None:
2296353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rounding = context.rounding
2297353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._raise_error(Rounded)
2298353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._rescale(0, rounding)
2299353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans != self:
2300353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
23017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
23027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2303353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def to_integral_value(self, rounding=None, context=None):
2304353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds to the nearest integer, without raising inexact, rounded."""
2305353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2306353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2307353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if rounding is None:
2308353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rounding = context.rounding
2309353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
2310353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._check_nans(context=context)
2311353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans:
2312353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return ans
2313353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self
2314353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp >= 0:
2315353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self
2316353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2317353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._rescale(0, rounding)
23187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2319353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # the method name changed, but we provide also the old one, for compatibility
2320353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    to_integral = to_integral_value
2321353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2322353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def sqrt(self, context=None):
2323353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return the square root of self."""
2324636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
2325636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
2326636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
2327636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
23287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2329636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity() and self._sign == 0:
2330636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Decimal(self)
23317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
23327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
2333353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # exponent = self._exp // 2.  sqrt(-0) = -0
2334353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal((self._sign, (0,), self._exp // 2))
2335353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
23367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2337636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
2338636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
2339636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
23407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign == 1:
23417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
23427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2343353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # At this point self represents a positive number.  Let p be
2344353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the desired precision and express self in the form c*100**e
2345353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # with c a positive real number and e an integer, c and e
2346353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # being chosen so that 100**(p-1) <= c < 100**p.  Then the
2347353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2348353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # <= sqrt(c) < 10**p, so the closest representable Decimal at
2349353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # precision p is n*10**e where n = round_half_even(sqrt(c)),
2350353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the closest integer to sqrt(c) with the even integer chosen
2351353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # in the case of a tie.
2352353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
2353353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # To ensure correct rounding in all cases, we use the
2354353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # following trick: we compute the square root to an extra
2355353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # place (precision p+1 instead of precision p), rounding down.
2356353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Then, if the result is inexact and its last digit is 0 or 5,
2357353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # we increase the last digit to 1 or 6 respectively; if it's
2358353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exact we leave the last digit alone.  Now the final round to
2359353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # p places (or fewer in the case of underflow) will round
2360353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # correctly and raise the appropriate flags.
2361353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2362353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # use an extra digit of precision
2363353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        prec = context.prec+1
2364353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2365353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # write argument in the form c*100**e where e = self._exp//2
2366353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # is the 'ideal' exponent, to be used if the square root is
2367353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exactly representable.  l is the number of 'digits' of c in
2368353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # base 100, so that 100**(l-1) <= c < 100**l.
2369353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op = _WorkRep(self)
2370353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        e = op.exp >> 1
2371353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if op.exp & 1:
2372353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = op.int * 10
2373353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            l = (len(self._int) >> 1) + 1
23747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
2375353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = op.int
2376353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            l = len(self._int)+1 >> 1
2377353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2378353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # rescale so that c has exactly prec base 100 'digits'
2379353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        shift = prec-l
2380353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if shift >= 0:
2381353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c *= 100**shift
2382353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            exact = True
23837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
2384353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c, remainder = divmod(c, 100**-shift)
2385353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            exact = not remainder
2386353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        e -= shift
2387353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2388353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # find n = floor(sqrt(c)) using Newton's method
2389353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        n = 10**prec
2390353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while True:
2391353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            q = c//n
2392353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if n <= q:
23937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                break
2394353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2395353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n = n + q >> 1
2396353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exact = exact and n*n == c
2397353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2398353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if exact:
2399353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # result is exact; rescale to use ideal exponent e
2400353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if shift >= 0:
2401353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # assert n % 10**shift == 0
2402353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n //= 10**shift
2403353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2404353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n *= 10**-shift
2405353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            e += shift
24067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
2407353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # result is not exact; fix last digit as described above
2408353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if n % 5 == 0:
2409353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n += 1
24107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2411353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = Decimal((0, map(int, str(n)), e))
24127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2413353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # round, and fit to current context
2414353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context._shallow_copy()
2415353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = context._set_rounding(ROUND_HALF_EVEN)
2416dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger        ans = ans._fix(context)
2417353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.rounding = rounding
24187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2419353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
24207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
24217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def max(self, other, context=None):
24227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the larger value.
24237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2424353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Like max(self, other) except if one is not a number, returns
24257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        NaN (and signals if one is sNaN).  Also rounds.
24267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2427353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
2428636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
2429636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
243059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If one operand is a quiet NaN and the other is number, then the
2431636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            # number is always returned
2432636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            sn = self._isnan()
2433636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            on = other._isnan()
2434636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if sn or on:
2435636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if on == 1 and sn != 2:
2436636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    return self
2437636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if sn == 1 and on != 2:
2438636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    return other
2439636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return self._check_nans(other, context)
24407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2441d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        c = self.__cmp__(other)
2442d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        if c == 0:
244359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If both operands are finite and equal in numerical value
2444d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger            # then an ordering is applied:
2445d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger            #
244659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If the signs differ then max returns the operand with the
2447d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger            # positive sign and min returns the operand with the negative sign
2448d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger            #
244959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If the signs are the same then the exponent is used to select
2450353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # the result.  This is exactly the ordering used in compare_total.
2451353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = self.compare_total(other)
2452353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2453353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == -1:
24547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = other
2455353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2456353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self
2457636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
2458636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
2459636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
246076e60d687dde9d987f39e16f8fe7814daf1f1e26Raymond Hettinger        if context._rounding_decision == ALWAYS_ROUND:
246176e60d687dde9d987f39e16f8fe7814daf1f1e26Raymond Hettinger            return ans._fix(context)
246276e60d687dde9d987f39e16f8fe7814daf1f1e26Raymond Hettinger        return ans
24637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
24647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def min(self, other, context=None):
24657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the smaller value.
24667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
246759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        Like min(self, other) except if one is not a number, returns
24687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        NaN (and signals if one is sNaN).  Also rounds.
24697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2470353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
2471636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
2472636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
247359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If one operand is a quiet NaN and the other is number, then the
2474636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            # number is always returned
2475636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            sn = self._isnan()
2476636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            on = other._isnan()
2477636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if sn or on:
2478636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if on == 1 and sn != 2:
2479636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    return self
2480636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if sn == 1 and on != 2:
2481636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    return other
2482636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return self._check_nans(other, context)
24837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2484d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        c = self.__cmp__(other)
2485d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        if c == 0:
2486353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = self.compare_total(other)
2487353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2488353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == -1:
2489353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self
2490353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
24917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = other
2492636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
2493636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
2494636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
249576e60d687dde9d987f39e16f8fe7814daf1f1e26Raymond Hettinger        if context._rounding_decision == ALWAYS_ROUND:
249676e60d687dde9d987f39e16f8fe7814daf1f1e26Raymond Hettinger            return ans._fix(context)
249776e60d687dde9d987f39e16f8fe7814daf1f1e26Raymond Hettinger        return ans
24987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
24997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _isinteger(self):
25007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns whether self is an integer"""
2501353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
2502353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return False
25037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._exp >= 0:
25047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return True
25057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rest = self._int[self._exp:]
25067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return rest == (0,)*len(rest)
25077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
25087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _iseven(self):
2509353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns True if self is even.  Assumes self is an integer."""
2510353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self or self._exp > 0:
2511353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return True
251261992efc4bb413ae7a19752215eca5af09be6b6dRaymond Hettinger        return self._int[-1+self._exp] & 1 == 0
25137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
25147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def adjusted(self):
25157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return the adjusted exponent of self"""
25167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        try:
25177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return self._exp + len(self._int) - 1
251859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # If NaN or Infinity, self._exp is string
25197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        except TypeError:
25207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return 0
25217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2522353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def canonical(self, context=None):
2523353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the same Decimal object.
2524353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2525353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        As we do not have different encodings for the same number, the
2526353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        received object already is in its canonical form.
2527353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2528353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self
2529353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2530353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_signal(self, other, context=None):
2531353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares self to the other operand numerically.
2532353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2533353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        It's pretty much like compare(), but all NaNs signal, with signaling
2534353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        NaNs taking precedence over quiet NaNs.
2535353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2536353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2537353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2538353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2539353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_is_nan = self._isnan()
2540353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other_is_nan = other._isnan()
2541353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_is_nan == 2:
2542353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation, 'sNaN',
2543353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, self)
2544353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other_is_nan == 2:
2545353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation, 'sNaN',
2546353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, other)
2547353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_is_nan:
2548353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2549353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, self)
2550353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other_is_nan:
2551353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2552353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, other)
2553353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self.compare(other, context=context)
2554353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2555353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_total(self, other):
2556353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares self to other using the abstract representations.
2557353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2558353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        This is not like the standard compare, which use their numerical
2559353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        value. Note that a total ordering is defined for all possible abstract
2560353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        representations.
2561353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2562353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if one is negative and the other is positive, it's easy
2563353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign and not other._sign:
2564353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_n1
2565353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self._sign and other._sign:
2566353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_p1
2567353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        sign = self._sign
2568353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2569353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # let's handle both NaN types
2570353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_nan = self._isnan()
2571353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other_nan = other._isnan()
2572353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_nan or other_nan:
2573353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self_nan == other_nan:
2574353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self._int < other._int:
2575353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if sign:
2576353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return Dec_p1
2577353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    else:
2578353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return Dec_n1
2579353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self._int > other._int:
2580353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if sign:
2581353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return Dec_n1
2582353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    else:
2583353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return Dec_p1
2584353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_0
2585353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2586353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sign:
2587353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_nan == 1:
2588353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_n1
2589353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other_nan == 1:
2590353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_p1
2591353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_nan == 2:
2592353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_n1
2593353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other_nan == 2:
2594353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_p1
2595353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2596353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_nan == 1:
2597353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_p1
2598353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other_nan == 1:
2599353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_n1
2600353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_nan == 2:
2601353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_p1
2602353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other_nan == 2:
2603353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_n1
2604353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2605353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self < other:
2606353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_n1
2607353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self > other:
2608353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_p1
2609353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2610353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp < other._exp:
2611353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sign:
2612353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_p1
2613353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2614353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_n1
2615353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp > other._exp:
2616353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sign:
2617353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_n1
2618353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2619353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_p1
2620353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Dec_0
2621353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2622353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2623353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_total_mag(self, other):
2624353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares self to other using abstract repr., ignoring sign.
2625353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2626353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Like compare_total, but with operand's sign ignored and assumed to be 0.
2627353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2628353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        s = self.copy_abs()
2629353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        o = other.copy_abs()
2630353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return s.compare_total(o)
2631353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2632353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_abs(self):
2633353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy with the sign set to 0. """
2634353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal((0, self._int, self._exp))
2635353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2636353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_negate(self):
2637353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy with the sign inverted."""
2638353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign:
2639353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Decimal((0, self._int, self._exp))
2640353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2641353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Decimal((1, self._int, self._exp))
2642353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2643353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_sign(self, other):
2644353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns self with the sign of other."""
2645353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal((other._sign, self._int, self._exp))
2646353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2647353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def exp(self, context=None):
2648353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns e ** self."""
2649353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2650353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2651353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2652353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2653353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp(NaN) = NaN
2654353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
2655353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
2656353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
2657353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2658353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp(-Infinity) = 0
2659353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == -1:
2660353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_0
2661353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2662353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp(0) = 1
2663353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2664353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_p1
2665353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2666353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp(Infinity) = Infinity
2667353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
2668353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Decimal(self)
2669353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2670353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the result is now guaranteed to be inexact (the true
2671353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # mathematical result is transcendental). There's no need to
2672353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # raise Rounded and Inexact here---they'll always be raised as
2673353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # a result of the call to _fix.
2674353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        p = context.prec
2675353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        adj = self.adjusted()
2676353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2677353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # we only need to do any computation for quite a small range
2678353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # of adjusted exponents---for example, -29 <= adj <= 10 for
2679353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the default context.  For smaller exponent the result is
2680353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # indistinguishable from 1 at the given precision, while for
2681353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # larger exponent the result either overflows or underflows.
2682353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2683353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # overflow
2684353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal((0, (1,), context.Emax+1))
2685353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2686353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # underflow to 0
2687353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal((0, (1,), context.Etiny()-1))
2688353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif self._sign == 0 and adj < -p:
2689353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # p+1 digits; final round will raise correct flags
2690353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal((0, (1,) + (0,)*(p-1) + (1,), -p))
2691353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif self._sign == 1 and adj < -p-1:
2692353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # p+1 digits; final round will raise correct flags
2693353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal((0, (9,)*(p+1), -p-1))
2694353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # general case
2695353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2696353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            op = _WorkRep(self)
2697353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c, e = op.int, op.exp
2698353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if op.sign == 1:
2699353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                c = -c
2700353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2701353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # compute correctly rounded result: increase precision by
2702353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # 3 digits at a time until we get an unambiguously
2703353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # roundable result
2704353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            extra = 3
2705353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while True:
2706353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                coeff, exp = _dexp(c, e, p+extra)
2707353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if coeff % (5*10**(len(str(coeff))-p-1)):
2708353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
2709353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                extra += 3
2710353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2711353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal((0, map(int, str(coeff)), exp))
2712353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2713353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # at this stage, ans should round correctly with *any*
2714353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # rounding mode, not just with ROUND_HALF_EVEN
2715353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context._shallow_copy()
2716353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = context._set_rounding(ROUND_HALF_EVEN)
2717353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2718353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.rounding = rounding
2719353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2720353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
2721353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2722353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_canonical(self):
2723353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns 1 if self is canonical; otherwise returns 0."""
2724353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Dec_p1
2725353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2726353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_finite(self):
2727353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns 1 if self is finite, otherwise returns 0.
2728353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2729353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        For it to be finite, it must be neither infinite nor a NaN.
2730353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2731353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
2732353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_0
2733353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2734353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_p1
2735353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2736353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_infinite(self):
2737353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns 1 if self is an Infinite, otherwise returns 0."""
2738353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
2739353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_p1
2740353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2741353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_0
2742353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2743353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_nan(self):
2744353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns 1 if self is qNaN or sNaN, otherwise returns 0."""
2745353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isnan():
2746353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_p1
2747353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2748353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_0
2749353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2750353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_normal(self, context=None):
2751353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns 1 if self is a normal number, otherwise returns 0."""
2752353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
2753353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_0
2754353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2755353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_0
2756353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2757353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2758353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context.Emin <= self.adjusted() <= context.Emax:
2759353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_p1
2760353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2761353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_0
2762353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2763353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_qnan(self):
2764353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns 1 if self is a quiet NaN, otherwise returns 0."""
2765353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isnan() == 1:
2766353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_p1
2767353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2768353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_0
2769353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2770353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_signed(self):
2771353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns 1 if self is negative, otherwise returns 0."""
2772353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal(self._sign)
2773353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2774353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_snan(self):
2775353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns 1 if self is a signaling NaN, otherwise returns 0."""
2776353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isnan() == 2:
2777353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_p1
2778353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2779353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_0
2780353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2781353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_subnormal(self, context=None):
2782353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns 1 if self is subnormal, otherwise returns 0."""
2783353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
2784353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_0
2785353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2786353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_0
2787353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2788353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2789353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2790353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        r = self._exp + len(self._int)
2791353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if r <= context.Emin:
2792353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_p1
2793353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Dec_0
2794353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2795353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_zero(self):
2796353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns 1 if self is a zero, otherwise returns 0."""
2797353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self:
2798353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_0
2799353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2800353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_p1
2801353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2802353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _ln_exp_bound(self):
2803353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compute a lower bound for the adjusted exponent of self.ln().
2804353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        In other words, compute r such that self.ln() >= 10**r.  Assumes
2805353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        that self is finite and positive and that self != 1.
2806353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2807353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2808353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2809353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        adj = self._exp + len(self._int) - 1
2810353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj >= 1:
2811353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2812353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(str(adj*23//10)) - 1
2813353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj <= -2:
2814353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # argument <= 0.1
2815353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(str((-1-adj)*23//10)) - 1
2816353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op = _WorkRep(self)
2817353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c, e = op.int, op.exp
2818353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj == 0:
2819353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # 1 < self < 10
2820353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            num = str(c-10**-e)
2821353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            den = str(c)
2822353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(num) - len(den) - (num < den)
2823353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # adj == -1, 0.1 <= self < 1
2824353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return e + len(str(10**-e - c)) - 1
2825353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2826353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2827353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def ln(self, context=None):
2828353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the natural (base e) logarithm of self."""
2829353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2830353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2831353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2832353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2833353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(NaN) = NaN
2834353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
2835353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
2836353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
2837353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2838353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(0.0) == -Infinity
2839353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2840353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return negInf
2841353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2842353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(Infinity) = Infinity
2843353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
2844353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Inf
2845353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2846353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(1.0) == 0.0
2847353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self == Dec_p1:
2848353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_0
2849353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2850353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(negative) raises InvalidOperation
2851353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign == 1:
2852353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2853353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'ln of a negative value')
2854353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2855353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # result is irrational, so necessarily inexact
2856353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op = _WorkRep(self)
2857353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c, e = op.int, op.exp
2858353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        p = context.prec
2859353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2860353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # correctly rounded result: repeatedly increase precision by 3
2861353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # until we get an unambiguously roundable result
2862353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        places = p - self._ln_exp_bound() + 2 # at least p+3 places
2863353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while True:
2864353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            coeff = _dlog(c, e, places)
2865353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # assert len(str(abs(coeff)))-p >= 1
2866353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2867353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                break
2868353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            places += 3
2869353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = Decimal((int(coeff<0), map(int, str(abs(coeff))), -places))
2870353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2871353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context._shallow_copy()
2872353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = context._set_rounding(ROUND_HALF_EVEN)
2873353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2874353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.rounding = rounding
2875353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
2876353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2877353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _log10_exp_bound(self):
2878353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compute a lower bound for the adjusted exponent of self.log10().
2879353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        In other words, find r such that self.log10() >= 10**r.
2880353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Assumes that self is finite and positive and that self != 1.
2881353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2882353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2883353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # For x >= 10 or x < 0.1 we only need a bound on the integer
2884353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # part of log10(self), and this comes directly from the
2885353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exponent of x.  For 0.1 <= x <= 10 we use the inequalities
2886353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2887353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (1-1/x)/2.31 > 0.  If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2888353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2889353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        adj = self._exp + len(self._int) - 1
2890353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj >= 1:
2891353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # self >= 10
2892353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(str(adj))-1
2893353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj <= -2:
2894353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # self < 0.1
2895353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(str(-1-adj))-1
2896353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op = _WorkRep(self)
2897353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c, e = op.int, op.exp
2898353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj == 0:
2899353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # 1 < self < 10
2900353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            num = str(c-10**-e)
2901353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            den = str(231*c)
2902353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(num) - len(den) - (num < den) + 2
2903353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # adj == -1, 0.1 <= self < 1
2904353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        num = str(10**-e-c)
2905353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return len(num) + e - (num < "231") - 1
2906353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2907353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def log10(self, context=None):
2908353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the base 10 logarithm of self."""
2909353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2910353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2911353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2912353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2913353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(NaN) = NaN
2914353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
2915353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
2916353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
2917353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2918353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(0.0) == -Infinity
2919353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2920353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return negInf
2921353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2922353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(Infinity) = Infinity
2923353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
2924353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Inf
2925353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2926353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(negative or -Infinity) raises InvalidOperation
2927353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign == 1:
2928353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2929353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'log10 of a negative value')
2930353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2931353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(10**n) = n
2932353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._int[0] == 1 and self._int[1:] == (0,)*(len(self._int) - 1):
2933353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # answer may need rounding
2934353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal(self._exp + len(self._int) - 1)
2935353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2936353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # result is irrational, so necessarily inexact
2937353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            op = _WorkRep(self)
2938353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c, e = op.int, op.exp
2939353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            p = context.prec
2940353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2941353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # correctly rounded result: repeatedly increase precision
2942353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # until result is unambiguously roundable
2943353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            places = p-self._log10_exp_bound()+2
2944353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while True:
2945353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                coeff = _dlog10(c, e, places)
2946353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # assert len(str(abs(coeff)))-p >= 1
2947353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2948353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
2949353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                places += 3
2950353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal((int(coeff<0), map(int, str(abs(coeff))), -places))
2951353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2952353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context._shallow_copy()
2953353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = context._set_rounding(ROUND_HALF_EVEN)
2954353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2955353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.rounding = rounding
2956353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
2957353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2958353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logb(self, context=None):
2959353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """ Returns the exponent of the magnitude of self's MSD.
2960353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2961353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result is the integer which is the exponent of the magnitude
2962353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        of the most significant digit of self (as though it were truncated
2963353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        to a single digit while maintaining the value of that digit and
2964353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        without limiting the resulting exponent).
2965353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2966353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # logb(NaN) = NaN
2967353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
2968353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
2969353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
2970353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2971353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2972353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2973353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2974353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # logb(+/-Inf) = +Inf
2975353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
2976353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Inf
2977353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2978353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # logb(0) = -Inf, DivisionByZero
2979353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2980353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(DivisionByZero, 'logb(0)', -1)
2981353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2982353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # otherwise, simply return the adjusted exponent of self, as a
2983353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Decimal.  Note that no attempt is made to fit the result
2984353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # into the current context.
2985353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal(self.adjusted())
2986353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2987353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _islogical(self):
2988353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return True if self is a logical operand.
2989353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2990353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        For being logical, it must be a finite numbers with a sign of 0,
2991353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        an exponent of 0, and a coefficient whose digits must all be
2992353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        either 0 or 1.
2993353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2994353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign != 0 or self._exp != 0:
2995353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return False
2996353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        for dig in self._int:
2997353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if dig not in (0, 1):
2998353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return False
2999353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return True
3000353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3001353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _fill_logical(self, context, opa, opb):
3002353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        dif = context.prec - len(opa)
3003353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if dif > 0:
3004353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            opa = (0,)*dif + opa
3005353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif dif < 0:
3006353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            opa = opa[-context.prec:]
3007353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        dif = context.prec - len(opb)
3008353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if dif > 0:
3009353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            opb = (0,)*dif + opb
3010353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif dif < 0:
3011353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            opb = opb[-context.prec:]
3012353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return opa, opb
3013353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3014353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_and(self, other, context=None):
3015353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies an 'and' operation between self and other's digits."""
3016353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3017353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3018353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self._islogical() or not other._islogical():
3019353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3020353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3021353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # fill to context.prec
3022353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        (opa, opb) = self._fill_logical(context, self._int, other._int)
3023353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3024353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # make the operation, and clean starting zeroes
3025353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        result = [a&b for a,b in zip(opa,opb)]
3026353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        for i,d in enumerate(result):
3027353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if d == 1:
3028353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                break
3029353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        result = tuple(result[i:])
3030353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3031353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if empty, we must have at least a zero
3032353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not result:
3033353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            result = (0,)
3034353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal((0, result, 0))
3035353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3036353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_invert(self, context=None):
3037353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Invert all its digits."""
3038353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3039353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3040353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self.logical_xor(Decimal((0,(1,)*context.prec,0)), context)
3041353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3042353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_or(self, other, context=None):
3043353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies an 'or' operation between self and other's digits."""
3044353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3045353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3046353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self._islogical() or not other._islogical():
3047353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3048353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3049353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # fill to context.prec
3050353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        (opa, opb) = self._fill_logical(context, self._int, other._int)
3051353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3052353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # make the operation, and clean starting zeroes
3053353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        result = [a|b for a,b in zip(opa,opb)]
3054353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        for i,d in enumerate(result):
3055353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if d == 1:
3056353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                break
3057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        result = tuple(result[i:])
3058353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if empty, we must have at least a zero
3060353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not result:
3061353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            result = (0,)
3062353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal((0, result, 0))
3063353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3064353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_xor(self, other, context=None):
3065353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies an 'xor' operation between self and other's digits."""
3066353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3067353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3068353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self._islogical() or not other._islogical():
3069353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3070353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3071353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # fill to context.prec
3072353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        (opa, opb) = self._fill_logical(context, self._int, other._int)
3073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3074353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # make the operation, and clean starting zeroes
3075353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        result = [a^b for a,b in zip(opa,opb)]
3076353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        for i,d in enumerate(result):
3077353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if d == 1:
3078353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                break
3079353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        result = tuple(result[i:])
3080353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3081353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if empty, we must have at least a zero
3082353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not result:
3083353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            result = (0,)
3084353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal((0, result, 0))
3085353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3086353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def max_mag(self, other, context=None):
3087353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values numerically with their sign ignored."""
3088353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
3089353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3090353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special or other._is_special:
3091353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # If one operand is a quiet NaN and the other is number, then the
3092353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # number is always returned
3093353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sn = self._isnan()
3094353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            on = other._isnan()
3095353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sn or on:
3096353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if on == 1 and sn != 2:
3097353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return self
3098353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if sn == 1 and on != 2:
3099353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return other
3100353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self._check_nans(other, context)
3101353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3102353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c = self.copy_abs().__cmp__(other.copy_abs())
3103353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == 0:
3104353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = self.compare_total(other)
3105353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3106353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == -1:
3107353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = other
3108353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
3109353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self
3110353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3111353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3112353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3113353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context._rounding_decision == ALWAYS_ROUND:
3114353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
3115353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
3116353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3117353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def min_mag(self, other, context=None):
3118353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values numerically with their sign ignored."""
3119353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
3120353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3121353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special or other._is_special:
3122353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # If one operand is a quiet NaN and the other is number, then the
3123353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # number is always returned
3124353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sn = self._isnan()
3125353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            on = other._isnan()
3126353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sn or on:
3127353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if on == 1 and sn != 2:
3128353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return self
3129353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if sn == 1 and on != 2:
3130353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return other
3131353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self._check_nans(other, context)
3132353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3133353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c = self.copy_abs().__cmp__(other.copy_abs())
3134353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == 0:
3135353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = self.compare_total(other)
3136353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3137353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == -1:
3138353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self
3139353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
3140353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = other
3141353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3142353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3143353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3144353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context._rounding_decision == ALWAYS_ROUND:
3145353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
3146353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
3147353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3148353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_minus(self, context=None):
3149353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the largest representable number smaller than itself."""
3150353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3151353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3152353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3153353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
3154353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3155353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3156353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3157353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == -1:
3158353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return negInf
3159353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
3160353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Decimal((0, (9,)*context.prec, context.Etop()))
3161353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3162353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context.copy()
3163353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._set_rounding(ROUND_FLOOR)
3164353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._ignore_all_flags()
3165353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        new_self = self._fix(context)
3166353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if new_self != self:
3167353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return new_self
3168353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self.__sub__(Decimal((0, (1,), context.Etiny()-1)), context)
3169353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3170353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_plus(self, context=None):
3171353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the smallest representable number larger than itself."""
3172353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3173353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3174353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3175353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
3176353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3177353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3178353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3179353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
3180353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Inf
3181353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == -1:
3182353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Decimal((1, (9,)*context.prec, context.Etop()))
3183353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3184353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context.copy()
3185353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._set_rounding(ROUND_CEILING)
3186353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._ignore_all_flags()
3187353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        new_self = self._fix(context)
3188353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if new_self != self:
3189353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return new_self
3190353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self.__add__(Decimal((0, (1,), context.Etiny()-1)), context)
3191353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3192353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_toward(self, other, context=None):
3193353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the number closest to self, in the direction towards other.
3194353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3195353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result is the closest representable number to self
3196353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        (excluding self) that is in the direction towards other,
3197353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        unless both have the same value.  If the two operands are
3198353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        numerically equal, then the result is a copy of self with the
3199353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        sign set to be the same as the sign of other.
3200353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3201353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
3202353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3203353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3204353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3205353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3206353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
3207353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3208353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3209353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3210353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        comparison = self.__cmp__(other)
3211353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if comparison == 0:
3212353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Decimal((other._sign, self._int, self._exp))
3213353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3214353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if comparison == -1:
3215353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.next_plus(context)
3216353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else: # comparison == 1
3217353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.next_minus(context)
3218353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3219353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # decide which flags to raise using value of ans
3220353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans._isinfinity():
3221353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Overflow,
3222353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                 'Infinite result from next_toward',
3223353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                 ans._sign)
3224353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Rounded)
3225353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
3226353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif ans.adjusted() < context.Emin:
3227353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Underflow)
3228353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Subnormal)
3229353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Rounded)
3230353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
3231353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # if precision == 1 then we don't raise Clamped for a
3232353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # result 0E-Etiny.
3233353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if not ans:
3234353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Clamped)
3235353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3236353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
3237353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3238353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def number_class(self, context=None):
3239353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns an indication of the class of self.
3240353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3241353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The class is one of the following strings:
3242353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -sNaN
3243353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -NaN
3244353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Infinity
3245353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Normal
3246353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Subnormal
3247353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Zero
3248353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Zero
3249353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Subnormal
3250353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Normal
3251353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Infinity
3252353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3253353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self.is_snan():
3254353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "sNaN"
3255353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self.is_qnan():
3256353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "NaN"
3257353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        inf = self._isinfinity()
3258353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if inf == 1:
3259353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "+Infinity"
3260353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if inf == -1:
3261353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "-Infinity"
3262353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self.is_zero():
3263353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self._sign:
3264353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return "-Zero"
3265353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
3266353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return "+Zero"
3267353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3268353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3269353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self.is_subnormal(context=context):
3270353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self._sign:
3271353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return "-Subnormal"
3272353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
3273353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return "+Subnormal"
3274353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # just a normal, regular, boring number, :)
3275353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign:
3276353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "-Normal"
3277353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
3278353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "+Normal"
3279353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3280353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def radix(self):
3281353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Just returns 10, as this is Decimal, :)"""
3282353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal(10)
3283353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3284353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def rotate(self, other, context=None):
3285353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a rotated copy of self, value-of-other times."""
3286353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3287353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3288353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3289353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
3290353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3291353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3292353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3293353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._exp != 0:
3294353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3295353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (-context.prec <= int(other) <= context.prec):
3296353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3297353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3298353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
3299353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self
3300353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3301353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # get values, pad if necessary
3302353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        torot = int(other)
3303353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotdig = self._int
3304353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        topad = context.prec - len(rotdig)
3305353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if topad:
3306353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rotdig = ((0,)*topad) + rotdig
3307353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3308353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # let's rotate!
3309353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotated = rotdig[torot:] + rotdig[:torot]
3310353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3311353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # clean starting zeroes
3312353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        for i,d in enumerate(rotated):
3313353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if d != 0:
3314353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                break
3315353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotated = rotated[i:]
3316353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3317353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal((self._sign, rotated, self._exp))
3318353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3319353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3320353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def scaleb (self, other, context=None):
3321353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns self operand after adding the second value to its exp."""
3322353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3323353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3324353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3325353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
3326353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3327353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3328353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3329353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._exp != 0:
3330353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3331353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        liminf = -2 * (context.Emax + context.prec)
3332353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        limsup =  2 * (context.Emax + context.prec)
3333353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (liminf <= int(other) <= limsup):
3334353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3335353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3336353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
3337353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self
3338353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3339353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        d = Decimal((self._sign, self._int, self._exp + int(other)))
3340353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        d = d._fix(context)
3341353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return d
3342353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3343353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def shift(self, other, context=None):
3344353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a shifted copy of self, value-of-other times."""
3345353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3346353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3347353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3348353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
3349353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3350353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3351353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3352353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._exp != 0:
3353353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3354353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (-context.prec <= int(other) <= context.prec):
3355353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3356353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3357353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
3358353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self
3359353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3360353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # get values, pad if necessary
3361353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        torot = int(other)
3362353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not torot:
3363353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self
3364353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotdig = self._int
3365353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        topad = context.prec - len(rotdig)
3366353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if topad:
3367353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rotdig = ((0,)*topad) + rotdig
3368353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3369353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # let's shift!
3370353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if torot < 0:
3371353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rotated = rotdig[:torot]
3372353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
3373353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rotated = (rotdig + ((0,) * torot))
3374353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rotated = rotated[-context.prec:]
3375353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3376353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # clean starting zeroes
3377353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if rotated:
3378353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            for i,d in enumerate(rotated):
3379353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if d != 0:
3380353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
3381353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rotated = rotated[i:]
3382353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
3383353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rotated = (0,)
3384353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3385353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal((self._sign, rotated, self._exp))
3386353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3387353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
338859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # Support for pickling, copy, and deepcopy
33897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __reduce__(self):
33907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return (self.__class__, (str(self),))
33917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
33927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __copy__(self):
33937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if type(self) == Decimal:
3394cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis            return self     # I'm immutable; therefore I am my own clone
33957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return self.__class__(str(self))
33967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
33977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __deepcopy__(self, memo):
33987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if type(self) == Decimal:
3399cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis            return self     # My components are also immutable
34007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return self.__class__(str(self))
34017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
340259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Context class #######################################################
3403cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
34047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3405cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis# get rounding method function:
340659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batistarounding_functions = [name for name in Decimal.__dict__.keys()
340759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                                    if name.startswith('_round_')]
34087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerfor name in rounding_functions:
340959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
34107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    globalname = name[1:].upper()
34117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    val = globals()[globalname]
34127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Decimal._pick_rounding_function[val] = name
34137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
34149ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettingerdel name, val, globalname, rounding_functions
34157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3416ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlanclass _ContextManager(object):
34178b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """Context manager class to support localcontext().
34181a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum
3419ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlan      Sets a copy of the supplied context in __enter__() and restores
34208b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan      the previous decimal context in __exit__()
34218b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """
34221a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum    def __init__(self, new_context):
3423ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlan        self.new_context = new_context.copy()
34241a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum    def __enter__(self):
34251a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum        self.saved_context = getcontext()
34261a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum        setcontext(self.new_context)
34271a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum        return self.new_context
34281a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum    def __exit__(self, t, v, tb):
34291a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum        setcontext(self.saved_context)
34301a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum
34317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Context(object):
34327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Contains the context for a Decimal instance.
34337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
34347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Contains:
34357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    prec - precision (for use in rounding, division, square roots..)
343659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    rounding - rounding type (how you round)
34377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
3438bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger    traps - If traps[exception] = 1, then the exception is
34397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    raised when it is caused.  Otherwise, a value is
34407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    substituted in.
34417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    flags  - When an exception is caused, flags[exception] is incremented.
34427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger             (Whether or not the trap_enabler is set)
34437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger             Should be reset by user of Decimal instance.
34440ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettinger    Emin -   Minimum exponent
34450ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettinger    Emax -   Maximum exponent
34467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    capitals -      If 1, 1*10^1 is printed as 1E+1.
34477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    If 0, printed as 1e1
3448e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger    _clamp - If 1, change exponents if too high (Default 0)
34497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
34509ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger
34517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __init__(self, prec=None, rounding=None,
3452abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger                 traps=None, flags=None,
34537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                 _rounding_decision=None,
34540ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettinger                 Emin=None, Emax=None,
3455e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger                 capitals=None, _clamp=0,
3456abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger                 _ignored_flags=None):
3457abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger        if flags is None:
3458abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger            flags = []
3459abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger        if _ignored_flags is None:
3460abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger            _ignored_flags = []
3461bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        if not isinstance(flags, dict):
3462fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger            flags = dict([(s,s in flags) for s in _signals])
3463b91af521fddac47b14c57cd9ba736775334e6379Raymond Hettinger            del s
3464bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        if traps is not None and not isinstance(traps, dict):
3465fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger            traps = dict([(s,s in traps) for s in _signals])
3466b91af521fddac47b14c57cd9ba736775334e6379Raymond Hettinger            del s
34677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        for name, val in locals().items():
34687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if val is None:
3469eb2608415ee4eb8aaea746f6a313937e264d0cdaRaymond Hettinger                setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
34707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            else:
34717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                setattr(self, name, val)
34727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        del self.self
34737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3474b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger    def __repr__(self):
3475bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        """Show the current context."""
3476b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger        s = []
347759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
347859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
347959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                 % vars(self))
348059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        names = [f.__name__ for f, v in self.flags.items() if v]
348159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        s.append('flags=[' + ', '.join(names) + ']')
348259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        names = [t.__name__ for t, v in self.traps.items() if v]
348359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        s.append('traps=[' + ', '.join(names) + ']')
3484b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger        return ', '.join(s) + ')'
3485b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger
3486d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger    def clear_flags(self):
3487d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger        """Reset all flags to zero"""
3488d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger        for flag in self.flags:
3489b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger            self.flags[flag] = 0
3490d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger
34919fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger    def _shallow_copy(self):
34929fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        """Returns a shallow copy from self."""
3493bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        nc = Context(self.prec, self.rounding, self.traps, self.flags,
34947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                         self._rounding_decision, self.Emin, self.Emax,
34957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                         self.capitals, self._clamp, self._ignored_flags)
34967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return nc
34979fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger
34989fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger    def copy(self):
34999fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        """Returns a deep copy from self."""
350059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        nc = Context(self.prec, self.rounding, self.traps.copy(),
350159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                self.flags.copy(), self._rounding_decision, self.Emin,
350259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                self.Emax, self.capitals, self._clamp, self._ignored_flags)
35039fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        return nc
35049ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger    __copy__ = copy
35057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35065aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger    def _raise_error(self, condition, explanation = None, *args):
35077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Handles an error
35087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the flag is in _ignored_flags, returns the default response.
35107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Otherwise, it increments the flag, then, if the corresponding
35117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        trap_enabler is set, it reaises the exception.  Otherwise, it returns
35127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        the default value after incrementing the flag.
35137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
35145aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger        error = _condition_map.get(condition, condition)
35157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if error in self._ignored_flags:
351659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # Don't touch the flag
35177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return error().handle(self, *args)
35187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self.flags[error] += 1
3520bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        if not self.traps[error]:
352159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # The errors define how to handle themselves.
35225aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger            return condition().handle(self, *args)
35237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Errors should only be risked on copies of the context
352559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # self._ignored_flags = []
35267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        raise error, explanation
35277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _ignore_all_flags(self):
35297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Ignore all flags, if they are raised"""
3530fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger        return self._ignore_flags(*_signals)
35317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _ignore_flags(self, *flags):
35337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Ignore the flags, if they are raised"""
35347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Do not mutate-- This way, copies of a context leave the original
35357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # alone.
35367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self._ignored_flags = (self._ignored_flags + list(flags))
35377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return list(flags)
35387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _regard_flags(self, *flags):
35407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Stop ignoring the flags, if they are raised"""
35417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if flags and isinstance(flags[0], (tuple,list)):
35427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            flags = flags[0]
35437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        for flag in flags:
35447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self._ignored_flags.remove(flag)
35457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35465aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger    def __hash__(self):
35475aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger        """A Context cannot be hashed."""
35485aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger        # We inherit object.__hash__, so we must deny this explicitly
354959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        raise TypeError("Cannot hash a Context.")
35505aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger
35517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def Etiny(self):
35527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns Etiny (= Emin - prec + 1)"""
35537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return int(self.Emin - self.prec + 1)
35547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def Etop(self):
3556e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger        """Returns maximum exponent (= Emax - prec + 1)"""
35577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return int(self.Emax - self.prec + 1)
35587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _set_rounding_decision(self, type):
35607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Sets the rounding decision.
35617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Sets the rounding decision, and returns the current (previous)
35637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding decision.  Often used like:
35647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35659fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        context = context._shallow_copy()
35667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # That so you don't change the calling context
35677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # if an error occurs in the middle (say DivisionImpossible is raised).
35687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding = context._set_rounding_decision(NEVER_ROUND)
35707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        instance = instance / Decimal(2)
35717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        context._set_rounding_decision(rounding)
35727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        This will make it not round for that operation.
35747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
3575cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
35767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding = self._rounding_decision
35777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self._rounding_decision = type
35787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return rounding
35797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _set_rounding(self, type):
35817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Sets the rounding type.
35827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Sets the rounding type, and returns the current (previous)
35847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding type.  Often used like:
35857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        context = context.copy()
35877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # so you don't change the calling context
35887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # if an error occurs in the middle.
35897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding = context._set_rounding(ROUND_UP)
35907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        val = self.__sub__(other, context=context)
35917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        context._set_rounding(rounding)
35927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        This will make it round up for that operation.
35947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
35957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding = self.rounding
35967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self.rounding= type
35977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return rounding
35987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3599fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger    def create_decimal(self, num='0'):
36007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Creates a new Decimal instance but using self as context."""
36017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        d = Decimal(num, context=self)
3602353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if d._isnan() and len(d._int) > self.prec - self._clamp:
3603353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._raise_error(ConversionSyntax,
3604353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                     "diagnostic info too long in NaN")
3605dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger        return d._fix(self)
36067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
360759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # Methods
36087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def abs(self, a):
36097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the absolute value of the operand.
36107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the operand is negative, the result is the same as using the minus
361259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operation on the operand.  Otherwise, the result is the same as using
36137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        the plus operation on the operand.
36147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36159ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.abs(Decimal('2.1'))
36167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.1")
36179ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.abs(Decimal('-100'))
36187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("100")
36199ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.abs(Decimal('101.5'))
36207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("101.5")
36219ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.abs(Decimal('-101.5'))
36227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("101.5")
36237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
36247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__abs__(context=self)
36257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def add(self, a, b):
36277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return the sum of the two operands.
36287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36299ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
36307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("19.00")
36319ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
36327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.02E+4")
36337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
36347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__add__(b, context=self)
36357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _apply(self, a):
3637dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger        return str(a._fix(self))
36387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3639353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def canonical(self, a):
3640353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the same Decimal object.
3641353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3642353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        As we do not have different encodings for the same number, the
3643353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        received object already is in its canonical form.
3644353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3645353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.canonical(Decimal('2.50'))
3646353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.50")
3647353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3648353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.canonical(context=self)
3649353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
36507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def compare(self, a, b):
36517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Compares values numerically.
36527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the signs of the operands differ, a value representing each operand
36547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        ('-1' if the operand is less than zero, '0' if the operand is zero or
36557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        negative zero, or '1' if the operand is greater than zero) is used in
36567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        place of that operand for the comparison instead of the actual
36577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        operand.
36587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The comparison is then effected by subtracting the second operand from
36607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        the first and then returning a value according to the result of the
36617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        subtraction: '-1' if the result is less than zero, '0' if the result is
36627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        zero or negative zero, or '1' if the result is greater than zero.
36637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36649ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
36657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1")
36669ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
36677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0")
36689ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
36697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0")
36709ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
36717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
36729ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
36737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
36749ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
36757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1")
36767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
36777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.compare(b, context=self)
36787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3679353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_signal(self, a, b):
3680353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values of the two operands numerically.
3681353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3682353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        It's pretty much like compare(), but all NaNs signal, with signaling
3683353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        NaNs taking precedence over quiet NaNs.
3684353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3685353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext
3686353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3687353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1")
3688353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3689353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3690353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.flags[InvalidOperation] = 0
3691353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> print c.flags[InvalidOperation]
3692353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        0
3693353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3694353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("NaN")
3695353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> print c.flags[InvalidOperation]
3696353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        1
3697353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.flags[InvalidOperation] = 0
3698353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> print c.flags[InvalidOperation]
3699353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        0
3700353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3701353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("NaN")
3702353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> print c.flags[InvalidOperation]
3703353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        1
3704353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3705353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.compare_signal(b, context=self)
3706353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3707353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_total(self, a, b):
3708353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares two operands using their abstract representation.
3709353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3710353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        This is not like the standard compare, which use their numerical
3711353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        value. Note that a total ordering is defined for all possible abstract
3712353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        representations.
3713353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3714353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3715353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1")
3716353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('-127'),  Decimal('12'))
3717353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1")
3718353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3719353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1")
3720353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3721353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3722353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('12.300'))
3723353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3724353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('NaN'))
3725353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1")
3726353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3727353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.compare_total(b)
3728353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3729353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_total_mag(self, a, b):
3730353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares two operands using their abstract representation ignoring sign.
3731353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3732353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Like compare_total, but with operand's sign ignored and assumed to be 0.
3733353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3734353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.compare_total_mag(b)
3735353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3736353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_abs(self, a):
3737353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy of the operand with the sign set to 0.
3738353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3739353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_abs(Decimal('2.1'))
3740353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.1")
3741353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_abs(Decimal('-100'))
3742353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("100")
3743353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3744353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.copy_abs()
3745353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3746353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_decimal(self, a):
3747353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy of the decimal objet.
3748353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3749353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3750353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.1")
3751353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3752353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.00")
3753353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3754353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a
3755353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3756353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_negate(self, a):
3757353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy of the operand with the sign inverted.
3758353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3759353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_negate(Decimal('101.5'))
3760353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-101.5")
3761353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3762353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("101.5")
3763353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3764353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.copy_negate()
3765353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3766353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_sign(self, a, b):
3767353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Copies the second operand's sign to the first one.
3768353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3769353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        In detail, it returns a copy of the first operand with the sign
3770353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        equal to the sign of the second operand.
3771353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3772353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3773353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.50")
3774353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3775353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.50")
3776353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3777353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.50")
3778353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3779353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.50")
3780353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3781353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.copy_sign(b)
3782353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
37837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def divide(self, a, b):
37847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Decimal division in a specified context.
37857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37869ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
37877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.333333333")
37889ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
37897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.666666667")
37909ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
37917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.5")
37929ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
37937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.1")
37949ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
37957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
37969ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
37977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("4.00")
37989ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
37997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.20")
38009ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
38017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("10")
38029ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
38037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1000")
38049ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
38057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.20E+6")
38067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
38077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__div__(b, context=self)
38087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
38097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def divide_int(self, a, b):
38107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Divides two numbers and returns the integer part of the result.
38117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
38129ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
38137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0")
38149ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
38157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3")
38169ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
38177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3")
38187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
38197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__floordiv__(b, context=self)
38207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
38217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def divmod(self, a, b):
38227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__divmod__(b, context=self)
38237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3824353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def exp(self, a):
3825353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns e ** a.
3826353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3827353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
3828353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
3829353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
3830353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('-Infinity'))
3831353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3832353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('-1'))
3833353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0.367879441")
3834353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('0'))
3835353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3836353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('1'))
3837353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.71828183")
3838353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('0.693147181'))
3839353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.00000000")
3840353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('+Infinity'))
3841353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("Infinity")
3842353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3843353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.exp(context=self)
3844353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3845353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def fma(self, a, b, c):
3846353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a multiplied by b, plus c.
3847353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3848353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The first two operands are multiplied together, using multiply,
3849353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        the third operand is then added to the result of that
3850353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        multiplication, using add, all with only one final rounding.
3851353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3852353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3853353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("22")
3854353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3855353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-8")
3856353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3857353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.38435736E+12")
3858353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3859353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.fma(b, c, context=self)
3860353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3861353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_canonical(self, a):
3862353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns 1 if the operand is canonical; otherwise returns 0.
3863353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3864353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_canonical(Decimal('2.50'))
3865353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3866353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3867353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Dec_p1
3868353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3869353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_finite(self, a):
3870353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns 1 if the operand is finite, otherwise returns 0.
3871353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3872353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        For it to be finite, it must be neither infinite nor a NaN.
3873353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3874353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('2.50'))
3875353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3876353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('-0.3'))
3877353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3878353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('0'))
3879353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3880353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('Inf'))
3881353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3882353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('NaN'))
3883353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3884353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3885353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_finite()
3886353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3887353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_infinite(self, a):
3888353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns 1 if the operand is an Infinite, otherwise returns 0.
3889353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3890353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_infinite(Decimal('2.50'))
3891353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3892353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_infinite(Decimal('-Inf'))
3893353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3894353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_infinite(Decimal('NaN'))
3895353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3896353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3897353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_infinite()
3898353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3899353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_nan(self, a):
3900353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns 1 if the operand is qNaN or sNaN, otherwise returns 0.
3901353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3902353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_nan(Decimal('2.50'))
3903353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3904353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_nan(Decimal('NaN'))
3905353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3906353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_nan(Decimal('-sNaN'))
3907353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3908353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3909353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_nan()
3910353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3911353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_normal(self, a):
3912353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns 1 if the operand is a normal number, otherwise returns 0.
3913353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3914353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
3915353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
3916353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
3917353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('2.50'))
3918353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3919353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('0.1E-999'))
3920353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3921353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('0.00'))
3922353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3923353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('-Inf'))
3924353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3925353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('NaN'))
3926353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3927353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3928353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_normal(context=self)
3929353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3930353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_qnan(self, a):
3931353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns 1 if the operand is a quiet NaN, otherwise returns 0.
3932353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3933353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_qnan(Decimal('2.50'))
3934353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3935353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_qnan(Decimal('NaN'))
3936353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3937353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_qnan(Decimal('sNaN'))
3938353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3939353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3940353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_qnan()
3941353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3942353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_signed(self, a):
3943353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns 1 if the operand is negative, otherwise returns 0.
3944353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3945353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_signed(Decimal('2.50'))
3946353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3947353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_signed(Decimal('-12'))
3948353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3949353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_signed(Decimal('-0'))
3950353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3951353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3952353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_signed()
3953353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3954353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_snan(self, a):
3955353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns 1 if the operand is a signaling NaN, otherwise returns 0.
3956353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3957353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_snan(Decimal('2.50'))
3958353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3959353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_snan(Decimal('NaN'))
3960353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3961353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_snan(Decimal('sNaN'))
3962353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3963353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3964353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_snan()
3965353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3966353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_subnormal(self, a):
3967353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns 1 if the operand is subnormal, otherwise returns 0.
3968353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3969353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
3970353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
3971353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
3972353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('2.50'))
3973353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3974353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('0.1E-999'))
3975353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3976353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('0.00'))
3977353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3978353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('-Inf'))
3979353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3980353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('NaN'))
3981353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3982353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3983353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_subnormal(context=self)
3984353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3985353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_zero(self, a):
3986353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns 1 if the operand is a zero, otherwise returns 0.
3987353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3988353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_zero(Decimal('0'))
3989353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3990353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_zero(Decimal('2.50'))
3991353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3992353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_zero(Decimal('-0E+2'))
3993353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3994353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3995353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_zero()
3996353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3997353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def ln(self, a):
3998353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the natural (base e) logarithm of the operand.
3999353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4000353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4001353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4002353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4003353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('0'))
4004353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-Infinity")
4005353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('1.000'))
4006353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4007353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('2.71828183'))
4008353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.00000000")
4009353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('10'))
4010353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.30258509")
4011353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('+Infinity'))
4012353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("Infinity")
4013353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4014353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.ln(context=self)
4015353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4016353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def log10(self, a):
4017353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the base 10 logarithm of the operand.
4018353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4019353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4020353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4021353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4022353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('0'))
4023353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-Infinity")
4024353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('0.001'))
4025353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-3")
4026353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('1.000'))
4027353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4028353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('2'))
4029353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0.301029996")
4030353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('10'))
4031353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4032353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('70'))
4033353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.84509804")
4034353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('+Infinity'))
4035353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("Infinity")
4036353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4037353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.log10(context=self)
4038353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4039353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logb(self, a):
4040353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """ Returns the exponent of the magnitude of the operand's MSD.
4041353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4042353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result is the integer which is the exponent of the magnitude
4043353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        of the most significant digit of the operand (as though the
4044353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        operand were truncated to a single digit while maintaining the
4045353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        value of that digit and without limiting the resulting exponent).
4046353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4047353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logb(Decimal('250'))
4048353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2")
4049353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logb(Decimal('2.50'))
4050353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4051353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logb(Decimal('0.03'))
4052353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-2")
4053353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logb(Decimal('0'))
4054353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-Infinity")
4055353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4056353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logb(context=self)
4057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4058353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_and(self, a, b):
4059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies the logical operation 'and' between each operand's digits.
4060353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4061353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The operands must be both logical numbers.
4062353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4063353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4064353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4065353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4066353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4067353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4068353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4069353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4070353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4071353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4072353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1000")
4073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4074353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("10")
4075353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4076353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logical_and(b, context=self)
4077353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4078353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_invert(self, a):
4079353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Invert all the digits in the operand.
4080353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4081353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The operand must be a logical number.
4082353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4083353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_invert(Decimal('0'))
4084353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("111111111")
4085353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_invert(Decimal('1'))
4086353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("111111110")
4087353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_invert(Decimal('111111111'))
4088353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4089353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_invert(Decimal('101010101'))
4090353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("10101010")
4091353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4092353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logical_invert(context=self)
4093353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4094353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_or(self, a, b):
4095353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies the logical operation 'or' between each operand's digits.
4096353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4097353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The operands must be both logical numbers.
4098353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4099353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4100353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4101353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4102353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4103353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4104353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4105353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4106353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4107353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4108353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1110")
4109353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4110353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1110")
4111353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4112353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logical_or(b, context=self)
4113353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4114353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_xor(self, a, b):
4115353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies the logical operation 'xor' between each operand's digits.
4116353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4117353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The operands must be both logical numbers.
4118353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4119353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4120353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4121353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4122353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4123353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4124353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4125353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4126353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4127353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4128353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("110")
4129353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4130353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1101")
4131353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4132353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logical_xor(b, context=self)
4133353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
41347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def max(self, a,b):
41357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """max compares two values numerically and returns the maximum.
41367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If either operand is a NaN then the general rules apply.
41387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Otherwise, the operands are compared as as though by the compare
413959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operation.  If they are numerically equal then the left-hand operand
414059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        is chosen as the result.  Otherwise the maximum (closer to positive
41417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        infinity) of the two operands is chosen as the result.
41427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41439ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
41447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3")
41459ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
41467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3")
41479ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
4148d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        Decimal("1")
4149d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4150d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        Decimal("7")
41517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
41527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.max(b, context=self)
41537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4154353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def max_mag(self, a, b):
4155353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values numerically with their sign ignored."""
4156353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.max_mag(b, context=self)
4157353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
41587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def min(self, a,b):
41597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """min compares two values numerically and returns the minimum.
41607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If either operand is a NaN then the general rules apply.
41627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Otherwise, the operands are compared as as though by the compare
416359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operation.  If they are numerically equal then the left-hand operand
416459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        is chosen as the result.  Otherwise the minimum (closer to negative
41657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        infinity) of the two operands is chosen as the result.
41667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41679ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
41687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2")
41699ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
41707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-10")
41719ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
41727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.0")
4173d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4174d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        Decimal("7")
41757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
41767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.min(b, context=self)
41777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4178353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def min_mag(self, a, b):
4179353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values numerically with their sign ignored."""
4180353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.min_mag(b, context=self)
4181353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
41827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def minus(self, a):
41837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Minus corresponds to unary prefix minus in Python.
41847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The operation is evaluated using the same rules as subtract; the
41867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        operation minus(a) is calculated as subtract('0', a) where the '0'
41877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        has the same exponent as the operand.
41887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41899ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.minus(Decimal('1.3'))
41907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1.3")
41919ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.minus(Decimal('-1.3'))
41927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.3")
41937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
41947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__neg__(context=self)
41957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def multiply(self, a, b):
41977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """multiply multiplies two operands.
41987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4199cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis        If either operand is a special value then the general rules apply.
4200cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis        Otherwise, the operands are multiplied together ('long multiplication'),
4201cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis        resulting in a number which may be as long as the sum of the lengths
4202cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis        of the two operands.
42037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
42049ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
42057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3.60")
42069ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
42077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("21")
42089ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
42097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.72")
42109ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
42117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0.0")
42129ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
42137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("4.28135971E+11")
42147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
42157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__mul__(b, context=self)
42167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4217353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_minus(self, a):
4218353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the largest representable number smaller than a.
4219353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4220353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4221353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4222353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4223353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.next_minus(Decimal('1'))
4224353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0.999999999")
4225353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_minus(Decimal('1E-1007'))
4226353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0E-1007")
4227353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4228353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.00000004")
4229353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_minus(Decimal('Infinity'))
4230353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("9.99999999E+999")
4231353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4232353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.next_minus(context=self)
4233353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4234353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_plus(self, a):
4235353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the smallest representable number larger than a.
4236353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4237353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4238353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4239353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4240353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.next_plus(Decimal('1'))
4241353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.00000001")
4242353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_plus(Decimal('-1E-1007'))
4243353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-0E-1007")
4244353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4245353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.00000002")
4246353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_plus(Decimal('-Infinity'))
4247353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-9.99999999E+999")
4248353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4249353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.next_plus(context=self)
4250353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4251353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_toward(self, a, b):
4252353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the number closest to a, in direction towards b.
4253353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4254353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result is the closest representable number from the first
4255353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        operand (but not the first operand) that is in the direction
4256353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        towards the second operand, unless the operands have the same
4257353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        value.
4258353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4259353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4260353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4261353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4262353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('1'), Decimal('2'))
4263353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.00000001")
4264353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4265353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-0E-1007")
4266353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4267353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.00000002")
4268353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('1'), Decimal('0'))
4269353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0.999999999")
4270353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4271353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0E-1007")
4272353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4273353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.00000004")
4274353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4275353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-0.00")
4276353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4277353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.next_toward(b, context=self)
4278353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
42797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def normalize(self, a):
4280e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger        """normalize reduces an operand to its simplest form.
42817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
42827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Essentially a plus operation with all trailing zeros removed from the
42837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        result.
42847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
42859ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('2.1'))
42867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.1")
42879ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('-2.0'))
42887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-2")
42899ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('1.200'))
42907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.2")
42919ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('-120'))
42927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1.2E+2")
42939ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('120.00'))
42947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.2E+2")
42959ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('0.00'))
42967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0")
42977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
42987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.normalize(context=self)
42997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4300353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def number_class(self, a):
4301353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns an indication of the class of the operand.
4302353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4303353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The class is one of the following strings:
4304353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -sNaN
4305353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -NaN
4306353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Infinity
4307353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Normal
4308353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Subnormal
4309353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Zero
4310353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Zero
4311353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Subnormal
4312353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Normal
4313353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Infinity
4314353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4315353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = Context(ExtendedContext)
4316353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4317353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4318353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('Infinity'))
4319353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Infinity'
4320353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('1E-10'))
4321353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Normal'
4322353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('2.50'))
4323353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Normal'
4324353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('0.1E-999'))
4325353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Subnormal'
4326353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('0'))
4327353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Zero'
4328353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-0'))
4329353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Zero'
4330353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-0.1E-999'))
4331353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Subnormal'
4332353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-1E-10'))
4333353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Normal'
4334353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-2.50'))
4335353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Normal'
4336353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-Infinity'))
4337353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Infinity'
4338353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('NaN'))
4339353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        'NaN'
4340353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-NaN'))
4341353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        'NaN'
4342353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('sNaN'))
4343353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        'sNaN'
4344353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4345353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.number_class(context=self)
4346353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
43477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def plus(self, a):
43487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Plus corresponds to unary prefix plus in Python.
43497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
43507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The operation is evaluated using the same rules as add; the
43517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        operation plus(a) is calculated as add('0', a) where the '0'
43527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        has the same exponent as the operand.
43537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
43549ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.plus(Decimal('1.3'))
43557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.3")
43569ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.plus(Decimal('-1.3'))
43577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1.3")
43587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
43597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__pos__(context=self)
43607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
43617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def power(self, a, b, modulo=None):
43627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Raises a to the power of b, to modulo if given.
43637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4364353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        With two arguments, compute a**b.  If a is negative then b
4365353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        must be integral.  The result will be inexact unless b is
4366353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        integral and the result is finite and can be expressed exactly
4367353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        in 'precision' digits.
4368353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4369353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        With three arguments, compute (a**b) % modulo.  For the
4370353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        three argument form, the following restrictions on the
4371353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        arguments hold:
4372353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4373353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - all three arguments must be integral
4374353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - b must be nonnegative
4375353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - at least one of a or b must be nonzero
4376353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - modulo must be nonzero and have at most 'precision' digits
4377353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4378353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result of pow(a, b, modulo) is identical to the result
4379353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        that would be obtained by computing (a**b) % modulo with
4380353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        unbounded precision, but is computed more efficiently.  It is
4381353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        always exact.
4382353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4383353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4384353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4385353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4386353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('2'), Decimal('3'))
43877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("8")
4388353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-2'), Decimal('3'))
4389353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-8")
4390353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('2'), Decimal('-3'))
43917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.125")
4392353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('1.7'), Decimal('8'))
43937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("69.7575744")
4394353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('10'), Decimal('0.301029996'))
4395353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.00000000")
4396353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('Infinity'), Decimal('-1'))
43977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0")
4398353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('Infinity'), Decimal('0'))
43997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
4400353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('Infinity'), Decimal('1'))
44017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("Infinity")
4402353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-Infinity'), Decimal('-1'))
44037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0")
4404353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-Infinity'), Decimal('0'))
44057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
4406353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-Infinity'), Decimal('1'))
44077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-Infinity")
4408353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-Infinity'), Decimal('2'))
44097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("Infinity")
4410353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('0'), Decimal('0'))
44117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("NaN")
4412353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4413353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4414353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("11")
4415353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4416353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-11")
4417353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4418353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4419353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4420353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("11")
4421353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4422353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("11729830")
4423353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4424353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-0")
4425353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4426353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
44277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
44287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__pow__(b, modulo, context=self)
44297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def quantize(self, a, b):
443159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
44327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The coefficient of the result is derived from that of the left-hand
443459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operand.  It may be rounded using the current rounding setting (if the
44357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exponent is being increased), multiplied by a positive power of ten (if
44367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        the exponent is being decreased), or is unchanged (if the exponent is
44377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        already equal to that of the right-hand operand).
44387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Unlike other operations, if the length of the coefficient after the
44407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        quantize operation would be greater than precision then an Invalid
444159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operation condition is raised.  This guarantees that, unless there is
444259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        an error condition, the exponent of the result of a quantize is always
44437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        equal to that of the right-hand operand.
44447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Also unlike other operations, quantize will never raise Underflow, even
44467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if the result is subnormal and inexact.
44477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44489ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
44497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.170")
44509ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
44517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.17")
44529ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
44537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.2")
44549ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
44557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2")
44569ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
44577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0E+1")
44589ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
44597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-Infinity")
44609ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
44617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("NaN")
44629ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
44637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0")
44649ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
44657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0E+5")
44669ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
44677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("NaN")
44689ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
44697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("NaN")
44709ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
44717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("217.0")
44729ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
44737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("217")
44749ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
44757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.2E+2")
44769ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
44777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2E+2")
44787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
44797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.quantize(b, context=self)
44807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4481353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def radix(self):
4482353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Just returns 10, as this is Decimal, :)
4483353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4484353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.radix()
4485353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("10")
4486353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4487353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal(10)
4488353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
44897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def remainder(self, a, b):
44907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the remainder from integer division.
44917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The result is the residue of the dividend after the operation of
449359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        calculating integer division as described for divide-integer, rounded
44940d4c06e06e5ee1f3bb1fa8068114bd700d74864aNeal Norwitz        to precision digits if necessary.  The sign of the result, if
449559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        non-zero, is the same as that of the original dividend.
44967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        This operation will fail under the same conditions as integer division
44987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        (that is, if integer division on the same two operands would fail, the
44997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        remainder cannot be calculated).
45007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45019ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
45027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.1")
45039ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
45047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
45059ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
45067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1")
45079ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
45087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.2")
45099ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
45107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.1")
45119ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
45127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.0")
45137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
45147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__mod__(b, context=self)
45157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def remainder_near(self, a, b):
45177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns to be "a - b * n", where n is the integer nearest the exact
45187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        value of "x / b" (if two integers are equally near then the even one
451959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        is chosen).  If the result is equal to 0 then its sign will be the
45207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        sign of a.
45217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        This operation will fail under the same conditions as integer division
45237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        (that is, if integer division on the same two operands would fail, the
45247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        remainder cannot be calculated).
45257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45269ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
45277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0.9")
45289ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
45297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-2")
45309ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
45317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
45329ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
45337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1")
45349ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
45357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.2")
45369ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
45377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.1")
45389ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
45397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0.3")
45407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
45417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.remainder_near(b, context=self)
45427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4543353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def rotate(self, a, b):
4544353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a rotated copy of a, b times.
4545353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4546353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The coefficient of the result is a rotated copy of the digits in
4547353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        the coefficient of the first operand.  The number of places of
4548353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotation is taken from the absolute value of the second operand,
4549353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        with the rotation being to the left if the second operand is
4550353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        positive or to the right otherwise.
4551353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4552353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4553353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("400000003")
4554353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4555353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("12")
4556353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4557353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("891234567")
4558353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4559353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("123456789")
4560353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4561353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("345678912")
4562353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4563353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.rotate(b, context=self)
4564353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
45657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def same_quantum(self, a, b):
45667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns True if the two operands have the same exponent.
45677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The result is never affected by either the sign or the coefficient of
45697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        either operand.
45707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45719ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
45727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        False
45739ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
45747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        True
45759ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
45767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        False
45779ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
45787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        True
45797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
45807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.same_quantum(b)
45817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4582353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def scaleb (self, a, b):
4583353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the first operand after adding the second value its exp.
4584353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4585353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4586353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0.0750")
4587353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4588353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("7.50")
4589353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4590353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("7.50E+3")
4591353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4592353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.scaleb (b, context=self)
4593353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4594353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def shift(self, a, b):
4595353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a shifted copy of a, b times.
4596353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4597353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The coefficient of the result is a shifted copy of the digits
4598353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        in the coefficient of the first operand.  The number of places
4599353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        to shift is taken from the absolute value of the second operand,
4600353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        with the shift being to the left if the second operand is
4601353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        positive or to the right otherwise.  Digits shifted into the
4602353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        coefficient are zeros.
4603353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4604353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4605353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("400000000")
4606353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4607353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4608353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4609353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1234567")
4610353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4611353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("123456789")
4612353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4613353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("345678900")
4614353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4615353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.shift(b, context=self)
4616353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
46177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def sqrt(self, a):
461859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        """Square root of a non-negative number to context precision.
46197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the result must be inexact, it is rounded using the round-half-even
46217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        algorithm.
46227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46239ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('0'))
46247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0")
46259ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('-0'))
46267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0")
46279ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('0.39'))
46287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.624499800")
46299ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('100'))
46307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("10")
46319ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('1'))
46327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
46339ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('1.0'))
46347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.0")
46359ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('1.00'))
46367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.0")
46379ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('7'))
46387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.64575131")
46399ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('10'))
46407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3.16227766")
46419ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.prec
46426ea484582238a65d44a76e3a831e3ba7c77a1a25Raymond Hettinger        9
46437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
46447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.sqrt(context=self)
46457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def subtract(self, a, b):
4647f33d01d304c349a7f555779c7c99930f1203adb7Georg Brandl        """Return the difference between the two operands.
46487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46499ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
46507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.23")
46519ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
46527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.00")
46539ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
46547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0.77")
46557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
46567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__sub__(b, context=self)
46577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def to_eng_string(self, a):
46597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Converts a number to a string, using scientific notation.
46607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The operation is not affected by the context.
46627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
46637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.to_eng_string(context=self)
46647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def to_sci_string(self, a):
46667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Converts a number to a string, using scientific notation.
46677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The operation is not affected by the context.
46697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
46707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__str__(context=self)
46717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4672353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def to_integral_exact(self, a):
4673353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds to an integer.
4674353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4675353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        When the operand has a negative exponent, the result is the same
4676353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        as using the quantize() operation using the given operand as the
4677353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4678353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        of the operand as the precision setting; Inexact and Rounded flags
4679353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        are allowed in this operation.  The rounding mode is taken from the
4680353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.
4681353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4682353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4683353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2")
4684353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('100'))
4685353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("100")
4686353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4687353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("100")
4688353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4689353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("102")
4690353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4691353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-102")
4692353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4693353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.0E+6")
4694353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4695353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("7.89E+77")
4696353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4697353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-Infinity")
4698353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4699353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.to_integral_exact(context=self)
4700353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4701353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def to_integral_value(self, a):
47027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Rounds to an integer.
47037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        When the operand has a negative exponent, the result is the same
47057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        as using the quantize() operation using the given operand as the
47067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        left-hand-operand, 1E+0 as the right-hand-operand, and the precision
47077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        of the operand as the precision setting, except that no flags will
470859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        be set.  The rounding mode is taken from the context.
47097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4710353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('2.1'))
47117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2")
4712353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('100'))
47137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("100")
4714353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('100.0'))
47157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("100")
4716353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('101.5'))
47177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("102")
4718353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
47197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-102")
4720353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
47217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.0E+6")
4722353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
47237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("7.89E+77")
4724353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
47257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-Infinity")
47267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
4727353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.to_integral_value(context=self)
4728353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4729353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # the method name changed, but we provide also the old one, for compatibility
4730353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    to_integral = to_integral_value
47317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass _WorkRep(object):
47337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __slots__ = ('sign','int','exp')
473417931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger    # sign: 0 or 1
4735636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    # int:  int or long
47367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    # exp:  None, int, or string
47377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __init__(self, value=None):
47397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if value is None:
47407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.sign = None
4741636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self.int = 0
47427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.exp = None
474317931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        elif isinstance(value, Decimal):
474417931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            self.sign = value._sign
4745636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            cum = 0
474617931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            for digit  in value._int:
4747636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                cum = cum * 10 + digit
4748636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self.int = cum
47497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.exp = value._exp
475017931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        else:
475117931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            # assert isinstance(value, tuple)
47527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.sign = value[0]
47537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.int = value[1]
47547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.exp = value[2]
47557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __repr__(self):
47577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
47587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __str__ = __repr__
47607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerdef _normalize(op1, op2, shouldround = 0, prec = 0):
47647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Normalizes op1, op2 to have the same exp and length of coefficient.
47657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Done during addition.
47677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
4768353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if op1.exp < op2.exp:
47697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        tmp = op2
47707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        other = op1
47717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    else:
47727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        tmp = op1
47737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        other = op2
47747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4775353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4776353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Then adding 10**exp to tmp has the same effect (after rounding)
4777353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # as adding any positive quantity smaller than 10**exp; similarly
4778353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # for subtraction.  So if other is smaller than 10**exp we replace
4779353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # it with 10**exp.  This avoids tmp.exp - other.exp getting too large.
4780353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if shouldround:
4781636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        tmp_len = len(str(tmp.int))
4782636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other_len = len(str(other.int))
4783353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exp = tmp.exp + min(-1, tmp_len - prec - 2)
4784353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other_len + other.exp - 1 < exp:
4785636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            other.int = 1
4786353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            other.exp = exp
4787636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
4788353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    tmp.int *= 10 ** (tmp.exp - other.exp)
4789353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    tmp.exp = other.exp
47907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    return op1, op2
47917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerdef _adjust_coefficients(op1, op2):
4793636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    """Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int.
47947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp.
47967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Used on _WorkRep instances during division.
47987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
47997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    adjust = 0
480059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # If op1 is smaller, make it larger
4801636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    while op2.int > op1.int:
4802636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        op1.int *= 10
48037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        op1.exp -= 1
4804636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        adjust += 1
48057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
480659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # If op2 is too small, make it larger
4807636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    while op1.int >= (10 * op2.int):
4808636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        op2.int *= 10
48097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        op2.exp -= 1
48107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        adjust -= 1
4811636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
48127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    return op1, op2, adjust
48137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4814353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4815353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4816353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4817353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# This function from Tim Peters was taken from here:
4818353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4819353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# The correction being in the function definition is for speed, and
4820353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# the whole function is not resolved with math.log because of avoiding
4821353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# the use of floats.
4822353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _nbits(n, correction = {
4823353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '0': 4, '1': 3, '2': 2, '3': 2,
4824353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '4': 1, '5': 1, '6': 1, '7': 1,
4825353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '8': 0, '9': 0, 'a': 0, 'b': 0,
4826353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4827353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Number of bits in binary representation of the positive integer n,
4828353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    or 0 if n == 0.
4829353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
4830353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if n < 0:
4831353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        raise ValueError("The argument to _nbits should be nonnegative.")
4832353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    hex_n = "%x" % n
4833353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return 4*len(hex_n) - correction[hex_n[0]]
4834353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4835353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _sqrt_nearest(n, a):
4836353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Closest integer to the square root of the positive integer n.  a is
4837353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    an initial approximation to the square root.  Any positive integer
4838353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    will do for a, but the closer a is to the square root of n the
4839353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    faster convergence will be.
4840353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4841353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
4842353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if n <= 0 or a <= 0:
4843353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4844353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4845353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    b=0
4846353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    while a != b:
4847353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        b, a = a, a--n//a>>1
4848353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return a
4849353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4850353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _rshift_nearest(x, shift):
4851353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given an integer x and a nonnegative integer shift, return closest
4852353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    integer to x / 2**shift; use round-to-even in case of a tie.
4853353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4854353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
4855353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    b, q = 1L << shift, x >> shift
4856353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return q + (2*(x & (b-1)) + (q&1) > b)
4857353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4858353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _div_nearest(a, b):
4859353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Closest integer to a/b, a and b positive integers; rounds to even
4860353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    in the case of a tie.
4861353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4862353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
4863353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    q, r = divmod(a, b)
4864353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return q + (2*r + (q&1) > b)
4865353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4866353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _ilog(x, M, L = 8):
4867353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Integer approximation to M*log(x/M), with absolute error boundable
4868353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    in terms only of x/M.
4869353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4870353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    Given positive integers x and M, return an integer approximation to
4871353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    M * log(x/M).  For L = 8 and 0.1 <= x/M <= 10 the difference
4872353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    between the approximation and the exact result is at most 22.  For
4873353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15.  In
4874353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    both cases these are upper bounds on the error; it will usually be
4875353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    much smaller."""
4876353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4877353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # The basic algorithm is the following: let log1p be the function
4878353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # log1p(x) = log(1+x).  Then log(x/M) = log1p((x-M)/M).  We use
4879353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # the reduction
4880353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4881353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #    log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4882353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4883353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # repeatedly until the argument to log1p is small (< 2**-L in
4884353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # absolute value).  For small y we can use the Taylor series
4885353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # expansion
4886353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4887353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #    log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4888353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4889353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # truncating at T such that y**T is small enough.  The whole
4890353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # computation is carried out in a form of fixed-point arithmetic,
4891353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # with a real number z being represented by an integer
4892353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # approximation to z*M.  To avoid loss of precision, the y below
4893353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # is actually an integer approximation to 2**R*y*M, where R is the
4894353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # number of reductions performed so far.
4895353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4896353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    y = x-M
4897353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # argument reduction; R = number of reductions performed
4898353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    R = 0
4899353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    while (R <= L and long(abs(y)) << L-R >= M or
4900353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista           R > L and abs(y) >> R-L >= M):
4901353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        y = _div_nearest(long(M*y) << 1,
4902353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                         M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4903353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        R += 1
4904353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4905353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Taylor series with T terms
4906353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    T = -int(-10*len(str(M))//(3*L))
4907353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    yshift = _rshift_nearest(y, R)
4908353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    w = _div_nearest(M, T)
4909353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    for k in xrange(T-1, 0, -1):
4910353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4911353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4912353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return _div_nearest(w*y, M)
4913353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4914353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _dlog10(c, e, p):
4915353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given integers c, e and p with c > 0, p >= 0, compute an integer
4916353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    approximation to 10**p * log10(c*10**e), with an absolute error of
4917353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    at most 1.  Assumes that c*10**e is not exactly 1."""
4918353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4919353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # increase precision by 2; compensate for this by dividing
4920353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # final result by 100
4921353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    p += 2
4922353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4923353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # write c*10**e as d*10**f with either:
4924353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #   f >= 0 and 1 <= d <= 10, or
4925353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #   f <= 0 and 0.1 <= d <= 1.
4926353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Thus for c*10**e close to 1, f = 0
4927353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    l = len(str(c))
4928353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    f = e+l - (e+l >= 1)
4929353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4930353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if p > 0:
4931353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        M = 10**p
4932353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        k = e+p-f
4933353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if k >= 0:
4934353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c *= 10**k
4935353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
4936353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = _div_nearest(c, 10**-k)
4937353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4938353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = _ilog(c, M) # error < 5 + 22 = 27
4939353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_10 = _ilog(10*M, M) # error < 15
4940353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = _div_nearest(log_d*M, log_10)
4941353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_tenpower = f*M # exact
4942353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
4943353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = 0  # error < 2.31
4944353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4945353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4946353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return _div_nearest(log_tenpower+log_d, 100)
4947353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4948353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _dlog(c, e, p):
4949353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given integers c, e and p with c > 0, compute an integer
4950353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    approximation to 10**p * log(c*10**e), with an absolute error of
4951353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    at most 1.  Assumes that c*10**e is not exactly 1."""
4952353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4953353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Increase precision by 2. The precision increase is compensated
4954353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # for at the end with a division by 100.
4955353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    p += 2
4956353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4957353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4958353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # or f <= 0 and 0.1 <= d <= 1.  Then we can compute 10**p * log(c*10**e)
4959353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # as 10**p * log(d) + 10**p*f * log(10).
4960353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    l = len(str(c))
4961353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    f = e+l - (e+l >= 1)
4962353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4963353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # compute approximation to 10**p*log(d), with error < 27
4964353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if p > 0:
4965353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        k = e+p-f
4966353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if k >= 0:
4967353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c *= 10**k
4968353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
4969353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = _div_nearest(c, 10**-k)  # error of <= 0.5 in c
4970353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4971353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # _ilog magnifies existing error in c by a factor of at most 10
4972353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4973353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
4974353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # p <= 0: just approximate the whole thing by 0; error < 2.31
4975353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = 0
4976353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4977353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # compute approximation to 10**p*f*log(10), with error < 17
4978353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if f:
4979353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        sign_f = [-1, 1][f > 0]
4980353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if p >= 0:
4981353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            M = 10**p * abs(f)
4982353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
4983353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            M = _div_nearest(abs(f), 10**-p) # M = 10**p*|f|, error <= 0.5
4984353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4985353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if M:
4986353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            f_log_ten = sign_f*_ilog(10*M, M)   # M*log(10), error <= 1.2 + 15 < 17
4987353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
4988353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            f_log_ten = 0
4989353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
4990353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        f_log_ten = 0
4991353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4992353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # error in sum < 17+27 = 44; error after division < 0.44 + 0.5 < 1
4993353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return _div_nearest(f_log_ten + log_d, 100)
4994353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4995353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _iexp(x, M, L=8):
4996353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given integers x and M, M > 0, such that x/M is small in absolute
4997353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    value, compute an integer approximation to M*exp(x/M).  For 0 <=
4998353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4999353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    is usually much smaller)."""
5000353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5001353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Algorithm: to compute exp(z) for a real number z, first divide z
5002353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # by a suitable power R of 2 so that |z/2**R| < 2**-L.  Then
5003353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5004353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # series
5005353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
5006353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #     expm1(x) = x + x**2/2! + x**3/3! + ...
5007353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
5008353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Now use the identity
5009353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
5010353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #     expm1(2x) = expm1(x)*(expm1(x)+2)
5011353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
5012353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # R times to compute the sequence expm1(z/2**R),
5013353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5014353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5015353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Find R such that x/2**R/M <= 2**-L
5016353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    R = _nbits((long(x)<<L)//M)
5017353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5018353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Taylor series.  (2**L)**T > M
5019353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    T = -int(-10*len(str(M))//(3*L))
5020353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    y = _div_nearest(x, T)
5021353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    Mshift = long(M)<<R
5022353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    for i in xrange(T-1, 0, -1):
5023353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        y = _div_nearest(x*(Mshift + y), Mshift * i)
5024353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5025353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Expansion
5026353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    for k in xrange(R-1, -1, -1):
5027353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Mshift = long(M)<<(k+2)
5028353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        y = _div_nearest(y*(y+Mshift), Mshift)
5029353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5030353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return M+y
5031353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5032353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _dexp(c, e, p):
5033353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Compute an approximation to exp(c*10**e), with p decimal places of
5034353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    precision.
5035353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5036353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    Returns d, f such that:
5037353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5038353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista      10**(p-1) <= d <= 10**p, and
5039353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista      (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5040353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5041353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    In other words, d*10**f is an approximation to exp(c*10**e) with p
5042353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    digits of precision, and with an error in d of at most 1.  This is
5043353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    almost, but not quite, the same as the error being < 1ulp: when d
5044353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    = 10**(p-1) the error could be up to 10 ulp."""
5045353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5046353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5047353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    p += 2
5048353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5049353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # compute log10 with extra precision = adjusted exponent of c*10**e
5050353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    extra = max(0, e + len(str(c)) - 1)
5051353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    q = p + extra
5052353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    log10 = _dlog(10, 0, q)  # error <= 1
5053353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5054353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # compute quotient c*10**e/(log10/10**q) = c*10**(e+q)/log10,
5055353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # rounding down
5056353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    shift = e+q
5057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if shift >= 0:
5058353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        cshift = c*10**shift
5059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
5060353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        cshift = c//10**-shift
5061353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    quot, rem = divmod(cshift, log10)
5062353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5063353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # reduce remainder back to original precision
5064353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    rem = _div_nearest(rem, 10**extra)
5065353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5066353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # error in result of _iexp < 120;  error after division < 0.62
5067353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5068353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5069353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _dpower(xc, xe, yc, ye, p):
5070353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5071353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    y = yc*10**ye, compute x**y.  Returns a pair of integers (c, e) such that:
5072353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista      10**(p-1) <= c <= 10**p, and
5074353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista      (c-1)*10**e < x**y < (c+1)*10**e
5075353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5076353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    in other words, c*10**e is an approximation to x**y with p digits
5077353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    of precision, and with an error in c of at most 1.  (This is
5078353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    almost, but not quite, the same as the error being < 1ulp: when c
5079353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    == 10**(p-1) we can only guarantee error < 10ulp.)
5080353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5081353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    We assume that: x is positive and not equal to 1, and y is nonzero.
5082353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
5083353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5084353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Find b such that 10**(b-1) <= |y| <= 10**b
5085353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    b = len(str(abs(yc))) + ye
5086353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5087353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5088353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    lxc = _dlog(xc, xe, p+b+1)
5089353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5090353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5091353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    shift = ye-b
5092353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if shift >= 0:
5093353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        pc = lxc*yc*10**shift
5094353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
5095353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        pc = _div_nearest(lxc*yc, 10**-shift)
5096353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5097353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if pc == 0:
5098353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # we prefer a result that isn't exactly 1; this makes it
5099353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # easier to compute a correctly rounded result in __pow__
5100353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5101353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            coeff, exp = 10**(p-1)+1, 1-p
5102353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
5103353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            coeff, exp = 10**p-1, -p
5104353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
5105353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        coeff, exp = _dexp(pc, -(p+1), p+1)
5106353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        coeff = _div_nearest(coeff, 10)
5107353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exp += 1
5108353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5109353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return coeff, exp
5110353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5111353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _log10_lb(c, correction = {
5112353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5113353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '6': 23, '7': 16, '8': 10, '9': 5}):
5114353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Compute a lower bound for 100*log10(c) for a positive integer c."""
5115353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if c <= 0:
5116353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        raise ValueError("The argument to _log10_lb should be nonnegative.")
5117353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    str_c = str(c)
5118353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return 100*len(str_c) - correction[str_c[0]]
5119353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
512059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Helper Functions ####################################################
51217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
5122353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _convert_other(other, raiseit=False):
5123636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    """Convert other to Decimal.
5124636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
5125636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    Verifies that it's ok to use in an implicit construction.
5126636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    """
5127636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    if isinstance(other, Decimal):
5128636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        return other
5129636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    if isinstance(other, (int, long)):
5130636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        return Decimal(other)
5131353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if raiseit:
5132353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        raise TypeError("Unable to convert %s to Decimal" % other)
5133267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger    return NotImplemented
5134636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
51357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger_infinity_map = {
51367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    'inf' : 1,
51377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    'infinity' : 1,
51387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    '+inf' : 1,
51397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    '+infinity' : 1,
51407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    '-inf' : -1,
51417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    '-infinity' : -1
51427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger}
51437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51440ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettingerdef _isinfinity(num):
51457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Determines whether a string or float is infinity.
51467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51470ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettinger    +1 for negative infinity; 0 for finite ; +1 for positive infinity
51487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
51497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    num = str(num).lower()
51507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    return _infinity_map.get(num, 0)
51517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51520ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettingerdef _isnan(num):
51537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Determines whether a string or float is NaN
51547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    (1, sign, diagnostic info as string) => NaN
51567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    (2, sign, diagnostic info as string) => sNaN
51577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    0 => not a NaN
51587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
51597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    num = str(num).lower()
51607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    if not num:
51617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return 0
51627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
516359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # Get the sign, get rid of trailing [+-]
51647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    sign = 0
51657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    if num[0] == '+':
51667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        num = num[1:]
516759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    elif num[0] == '-':  # elif avoids '+-nan'
51687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        num = num[1:]
51697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        sign = 1
51707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    if num.startswith('nan'):
517259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        if len(num) > 3 and not num[3:].isdigit():  # diagnostic info
51737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return 0
51747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return (1, sign, num[3:].lstrip('0'))
51757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    if num.startswith('snan'):
51767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if len(num) > 4 and not num[4:].isdigit():
51777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return 0
51787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return (2, sign, num[4:].lstrip('0'))
51797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    return 0
51807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
518259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Setup Specific Contexts ############################################
51837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# The default context prototype used by Context()
5185fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger# Is mutable, so that new contexts can have different default values
51867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerDefaultContext = Context(
51886ea484582238a65d44a76e3a831e3ba7c77a1a25Raymond Hettinger        prec=28, rounding=ROUND_HALF_EVEN,
5189bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        traps=[DivisionByZero, Overflow, InvalidOperation],
5190bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        flags=[],
51917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        _rounding_decision=ALWAYS_ROUND,
519299148e7eaad7741fbfb0822009b7c9b216ecc227Raymond Hettinger        Emax=999999999,
519399148e7eaad7741fbfb0822009b7c9b216ecc227Raymond Hettinger        Emin=-999999999,
5194e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger        capitals=1
51957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger)
51967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# Pre-made alternate contexts offered by the specification
51987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# Don't change these; the user should be able to select these
51997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# contexts and be able to reproduce results from other implementations
52007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# of the spec.
52017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52029ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond HettingerBasicContext = Context(
52037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        prec=9, rounding=ROUND_HALF_UP,
5204bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5205bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        flags=[],
52067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger)
52077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52089ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond HettingerExtendedContext = Context(
52096ea484582238a65d44a76e3a831e3ba7c77a1a25Raymond Hettinger        prec=9, rounding=ROUND_HALF_EVEN,
5210bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        traps=[],
5211bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        flags=[],
52127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger)
52137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
521559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Useful Constants (internal use only) ################################
52167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
521759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista# Reusable defaults
52187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerInf = Decimal('Inf')
52197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingernegInf = Decimal('-Inf')
5220353750c405c9099d0be69c6af1d17037b38c4ddfFacundo BatistaNaN = Decimal('NaN')
5221353750c405c9099d0be69c6af1d17037b38c4ddfFacundo BatistaDec_0 = Decimal(0)
5222353750c405c9099d0be69c6af1d17037b38c4ddfFacundo BatistaDec_p1 = Decimal(1)
5223353750c405c9099d0be69c6af1d17037b38c4ddfFacundo BatistaDec_n1 = Decimal(-1)
5224353750c405c9099d0be69c6af1d17037b38c4ddfFacundo BatistaDec_p2 = Decimal(2)
5225353750c405c9099d0be69c6af1d17037b38c4ddfFacundo BatistaDec_n2 = Decimal(-2)
52267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
522759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista# Infsign[sign] is infinity w/ that sign
52287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerInfsign = (Inf, negInf)
52297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
523159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### crud for parsing strings #############################################
52327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerimport re
52337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# There's an optional sign at the start, and an optional exponent
52357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# at the end.  The exponent has an optional sign and at least one
52367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# digit.  In between, must have either at least one digit followed
52377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# by an optional fraction, or a decimal point followed by at least
52387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# one digit.  Yuck.
52397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger_parser = re.compile(r"""
52417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger#    \s*
52427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    (?P<sign>[-+])?
52437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    (
52447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        (?P<int>\d+) (\. (?P<frac>\d*))?
52457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    |
52467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        \. (?P<onlyfrac>\d+)
52477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    )
52487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    ([eE](?P<exp>[-+]? \d+))?
52497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger#    \s*
52507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    $
525159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista""", re.VERBOSE).match  # Uncomment the \s* to allow leading or trailing spaces.
52527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerdel re
52547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerdef _string2exact(s):
525659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    """Return sign, n, p s.t.
52570d4c06e06e5ee1f3bb1fa8068114bd700d74864aNeal Norwitz
525859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    Float string value == -1**sign * n * 10**p exactly
525959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    """
52607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    m = _parser(s)
52617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    if m is None:
52627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        raise ValueError("invalid literal for Decimal: %r" % s)
52637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    if m.group('sign') == "-":
52657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        sign = 1
52667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    else:
52677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        sign = 0
52687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    exp = m.group('exp')
52707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    if exp is None:
52717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exp = 0
52727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    else:
52737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exp = int(exp)
52747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    intpart = m.group('int')
52767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    if intpart is None:
52777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        intpart = ""
52787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        fracpart = m.group('onlyfrac')
52797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    else:
52807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        fracpart = m.group('frac')
52817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if fracpart is None:
52827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            fracpart = ""
52837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    exp -= len(fracpart)
52857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    mantissa = intpart + fracpart
52877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    tmp = map(int, mantissa)
52887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    backup = tmp
52897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    while tmp and tmp[0] == 0:
52907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        del tmp[0]
52917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    # It's a zero
52937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    if not tmp:
52947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if backup:
52957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return (sign, tuple(backup), exp)
52967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return (sign, (0,), exp)
52977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    mantissa = tuple(tmp)
52987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    return (sign, mantissa, exp)
53007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
53017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
53027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerif __name__ == '__main__':
53037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    import doctest, sys
53047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    doctest.testmod(sys.modules[__name__])
5305