decimal.py revision 2ec7415db5ad63c4e4b27ee793214071454f6fe5
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
21772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(args[1]._sign, args[1]._int, 'n', True)
218353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return ans._fix_nan(context)
219353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            elif args[0] == 2:
22072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(args[1], args[2], 'n', True)
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
247cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista    def handle(self, context, sign, *args):
2487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return Infsign[sign]
2497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass DivisionImpossible(InvalidOperation):
2517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Cannot perform the division adequately.
2527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals invalid-operation if the integer result of a
2547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    divide-integer or remainder operation had too many digits (would be
25559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    longer than precision).  The result is [0,qNaN].
2567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
257cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
2587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, *args):
259cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return NaN
2607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass DivisionUndefined(InvalidOperation, ZeroDivisionError):
2627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Undefined result of division.
2637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals invalid-operation if division by zero was
2657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    attempted (during a divide-integer, divide, or remainder operation), and
26659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    the dividend is also zero.  The result is [0,qNaN].
2677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
268cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
269cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista    def handle(self, context, *args):
2707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return NaN
2717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Inexact(DecimalException):
2737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Had to round, losing information.
2747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals inexact whenever the result of an operation is
2767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    not exact (that is, it needed to be rounded and any discarded digits
27759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    were non-zero), or if an overflow or underflow condition occurs.  The
2787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    result in all cases is unchanged.
2797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The inexact signal may be tested (or trapped) to determine if a given
2817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    operation (or sequence of operations) was inexact.
2827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
2835aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger    pass
2847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass InvalidContext(InvalidOperation):
2867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Invalid context.  Unknown rounding, for example.
2877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals invalid-operation if an invalid context was
28959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    detected during an operation.  This can occur if contexts are not checked
2907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    on creation and either the precision exceeds the capability of the
2917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    underlying concrete representation or an unknown or unsupported rounding
29259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    was specified.  These aspects of the context need only be checked when
29359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    the values are required to be used.  The result is [0,qNaN].
2947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
295cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
2967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, *args):
2977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return NaN
2987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Rounded(DecimalException):
3007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Number got rounded (not  necessarily changed during rounding).
3017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals rounded whenever the result of an operation is
3037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    rounded (that is, some zero or non-zero digits were discarded from the
30459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    coefficient), or if an overflow or underflow condition occurs.  The
3057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    result in all cases is unchanged.
3067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The rounded signal may be tested (or trapped) to determine if a given
3087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    operation (or sequence of operations) caused a loss of precision.
3097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
3105aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger    pass
3117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Subnormal(DecimalException):
3137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Exponent < Emin before rounding.
3147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals subnormal whenever the result of a conversion or
3167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    operation is subnormal (that is, its adjusted exponent is less than
31759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    Emin, before any rounding).  The result in all cases is unchanged.
3187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The subnormal signal may be tested (or trapped) to determine if a given
3207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    or operation (or sequence of operations) yielded a subnormal result.
3217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
3227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    pass
3237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Overflow(Inexact, Rounded):
3257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Numerical overflow.
3267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals overflow if the adjusted exponent of a result
3287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    (from a conversion or from an operation that is not an attempt to divide
3297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    by zero), after rounding, would be greater than the largest value that
3307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    can be handled by the implementation (the value Emax).
3317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The result depends on the rounding mode:
3337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    For round-half-up and round-half-even (and for round-half-down and
3357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    round-up, if implemented), the result of the operation is [sign,inf],
33659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    where sign is the sign of the intermediate result.  For round-down, the
3377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    result is the largest finite number that can be represented in the
33859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    current precision, with the sign of the intermediate result.  For
3397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    round-ceiling, the result is the same as for round-down if the sign of
34059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    the intermediate result is 1, or is [0,inf] otherwise.  For round-floor,
3417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    the result is the same as for round-down if the sign of the intermediate
34259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    result is 0, or is [1,inf] otherwise.  In all cases, Inexact and Rounded
3437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    will also be raised.
344cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis   """
345cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
3467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, sign, *args):
3477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
348353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                ROUND_HALF_DOWN, ROUND_UP):
3497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return Infsign[sign]
3507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if sign == 0:
3517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if context.rounding == ROUND_CEILING:
3527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return Infsign[sign]
35372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(sign, '9'*context.prec,
35472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                            context.Emax-context.prec+1)
3557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if sign == 1:
3567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if context.rounding == ROUND_FLOOR:
3577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return Infsign[sign]
35872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(sign, '9'*context.prec,
35972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                             context.Emax-context.prec+1)
3607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Underflow(Inexact, Rounded, Subnormal):
3637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Numerical underflow with result rounded to 0.
3647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals underflow if a result is inexact and the
3667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    adjusted exponent of the result would be smaller (more negative) than
3677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    the smallest value that can be handled by the implementation (the value
36859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    Emin).  That is, the result is both inexact and subnormal.
3697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The result after an underflow will be a subnormal number rounded, if
37159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    necessary, so that its exponent is not less than Etiny.  This may result
3727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    in 0 with the sign of the intermediate result and an exponent of Etiny.
3737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    In all cases, Inexact, Rounded, and Subnormal will also be raised.
3757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
3767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3775aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger# List of public traps and flags
378fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
379cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis           Underflow, InvalidOperation, Subnormal]
3807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3815aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger# Map conditions (per the spec) to signals
3825aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger_condition_map = {ConversionSyntax:InvalidOperation,
3835aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger                  DivisionImpossible:InvalidOperation,
3845aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger                  DivisionUndefined:InvalidOperation,
3855aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger                  InvalidContext:InvalidOperation}
3867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
38759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Context Functions ##################################################
3887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
389ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger# The getcontext() and setcontext() function manage access to a thread-local
390ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger# current context.  Py2.4 offers direct support for thread locals.  If that
391ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger# is not available, use threading.currentThread() which is slower but will
3927e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger# work for older Pythons.  If threads are not part of the build, create a
393cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis# mock threading object with threading.local() returning the module namespace.
3947e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger
3957e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettingertry:
3967e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    import threading
3977e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettingerexcept ImportError:
3987e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    # Python was compiled without threads; create a mock object instead
3997e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    import sys
40059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    class MockThreading(object):
4017e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger        def local(self, sys=sys):
4027e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger            return sys.modules[__name__]
4037e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    threading = MockThreading()
4047e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    del sys, MockThreading
405ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
406ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettingertry:
407ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    threading.local
408ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
409ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettingerexcept AttributeError:
410ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
41159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # To fix reloading, force it to create a new context
41259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # Old contexts have different exceptions in their dicts, making problems.
413ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    if hasattr(threading.currentThread(), '__decimal_context__'):
414ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        del threading.currentThread().__decimal_context__
415ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
416ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    def setcontext(context):
417ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """Set this thread's context to context."""
418ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        if context in (DefaultContext, BasicContext, ExtendedContext):
4199fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger            context = context.copy()
42061992efc4bb413ae7a19752215eca5af09be6b6dRaymond Hettinger            context.clear_flags()
4217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        threading.currentThread().__decimal_context__ = context
422ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
423ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    def getcontext():
424ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """Returns this thread's context.
425ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
426ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        If this thread does not yet have a context, returns
427ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        a new context and sets this thread's context.
428ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        New contexts are copies of DefaultContext.
429ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """
430ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        try:
431ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            return threading.currentThread().__decimal_context__
432ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        except AttributeError:
433ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            context = Context()
434ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            threading.currentThread().__decimal_context__ = context
435ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            return context
436ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
437ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettingerelse:
438ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
439ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    local = threading.local()
4409fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger    if hasattr(local, '__decimal_context__'):
4419fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        del local.__decimal_context__
442ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
443ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    def getcontext(_local=local):
444ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """Returns this thread's context.
445ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
446ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        If this thread does not yet have a context, returns
447ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        a new context and sets this thread's context.
448ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        New contexts are copies of DefaultContext.
449ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """
450ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        try:
451ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            return _local.__decimal_context__
452ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        except AttributeError:
453ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            context = Context()
454ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            _local.__decimal_context__ = context
455ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            return context
456ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
457ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    def setcontext(context, _local=local):
458ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """Set this thread's context to context."""
459ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        if context in (DefaultContext, BasicContext, ExtendedContext):
4609fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger            context = context.copy()
46161992efc4bb413ae7a19752215eca5af09be6b6dRaymond Hettinger            context.clear_flags()
462ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        _local.__decimal_context__ = context
463ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
464cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis    del threading, local        # Don't contaminate the namespace
4657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4668b6999b4c5fab174090be263ba90f193bdede141Nick Coghlandef localcontext(ctx=None):
4678b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """Return a context manager for a copy of the supplied context
4688b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan
4698b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    Uses a copy of the current context if no context is specified
4708b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    The returned context manager creates a local decimal context
4718b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    in a with statement:
4728b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan        def sin(x):
4738b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan             with localcontext() as ctx:
4748b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 ctx.prec += 2
4758b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # Rest of sin calculation algorithm
4768b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # uses a precision 2 greater than normal
47759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista             return +s  # Convert result to normal precision
4788b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan
4798b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan         def sin(x):
4808b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan             with localcontext(ExtendedContext):
4818b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # Rest of sin calculation algorithm
4828b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # uses the Extended Context from the
4838b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # General Decimal Arithmetic Specification
48459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista             return +s  # Convert result to normal context
4858b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan
4868b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """
487681d86743c21773bb00508dbacb05ed9012388d8Neal Norwitz    # The string below can't be included in the docstring until Python 2.6
4888b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    # as the doctest module doesn't understand __future__ statements
4898b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """
4908b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> from __future__ import with_statement
4918b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> print getcontext().prec
4928b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    28
4938b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> with localcontext():
4948b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...     ctx = getcontext()
495495df4716fce4156c1eb110f9342297164eecbb6Raymond Hettinger    ...     ctx.prec += 2
4968b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...     print ctx.prec
4978b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...
4988b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    30
4998b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> with localcontext(ExtendedContext):
5008b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...     print getcontext().prec
5018b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...
5028b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    9
5038b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> print getcontext().prec
5048b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    28
5058b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """
506ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlan    if ctx is None: ctx = getcontext()
507ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlan    return _ContextManager(ctx)
5088b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan
5097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Decimal class #######################################################
5117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
5127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Decimal(object):
5137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Floating point class for decimal arithmetic."""
5147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
515636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    __slots__ = ('_exp','_int','_sign', '_is_special')
516636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    # Generally, the value of the Decimal instance is given by
517636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    #  (-1)**_sign * _int * 10**_exp
518636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    # Special values are signified by _is_special == True
5197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
520dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger    # We're immutable, so use __new__ not __init__
521636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    def __new__(cls, value="0", context=None):
5227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Create a decimal point instance.
5237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
5247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        >>> Decimal('3.14')              # string input
5257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3.14")
52659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        >>> Decimal((0, (3, 1, 4), -2))  # tuple (sign, digit_tuple, exponent)
5277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3.14")
5287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        >>> Decimal(314)                 # int or long
5297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("314")
5307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        >>> Decimal(Decimal(314))        # another decimal instance
5317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("314")
5327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
5337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
53472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # Note that the coefficient, self._int, is actually stored as
53572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # a string rather than as a tuple of digits.  This speeds up
53672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # the "digits to integer" and "integer to digits" conversions
53772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # that are used in almost every arithmetic operation on
53872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # Decimals.  This is an internal detail: the as_tuple function
53972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # and the Decimal constructor still deal with tuples of
54072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # digits.
54172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista
542636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        self = object.__new__(cls)
543636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
5440d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        # From a string
5450d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        # REs insist on real strings, so we can too.
5460d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        if isinstance(value, basestring):
5470d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            m = _parser(value)
5480d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            if m is None:
5490d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                if context is None:
5500d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    context = getcontext()
5510d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                return context._raise_error(ConversionSyntax,
5520d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                                "Invalid literal for Decimal: %r" % value)
553636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
5540d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            if m.group('sign') == "-":
5550d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                self._sign = 1
5560d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            else:
5570d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                self._sign = 0
5580d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            intpart = m.group('int')
5590d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            if intpart is not None:
5600d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                # finite number
5610d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                fracpart = m.group('frac')
5620d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                exp = int(m.group('exp') or '0')
5630d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                if fracpart is not None:
5640d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    self._int = (intpart+fracpart).lstrip('0') or '0'
5650d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    self._exp = exp - len(fracpart)
5660d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                else:
5670d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    self._int = intpart.lstrip('0') or '0'
5680d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    self._exp = exp
5690d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                self._is_special = False
5700d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            else:
5710d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                diag = m.group('diag')
5720d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                if diag is not None:
5730d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    # NaN
5740d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    self._int = diag.lstrip('0')
5750d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    if m.group('signal'):
5760d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                        self._exp = 'N'
5770d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    else:
5780d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                        self._exp = 'n'
5790d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                else:
5800d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    # infinity
5810d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    self._int = '0'
5820d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    self._exp = 'F'
5830d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                self._is_special = True
584636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return self
585636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
586636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        # From an integer
5877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if isinstance(value, (int,long)):
588636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if value >= 0:
589636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                self._sign = 0
590636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            else:
591636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                self._sign = 1
592636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self._exp = 0
59372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self._int = str(abs(value))
5940d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._is_special = False
5950d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            return self
5960d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista
5970d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        # From another decimal
5980d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        if isinstance(value, Decimal):
5990d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._exp  = value._exp
6000d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._sign = value._sign
6010d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._int  = value._int
6020d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._is_special  = value._is_special
6030d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            return self
6040d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista
6050d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        # From an internal working value
6060d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        if isinstance(value, _WorkRep):
6070d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._sign = value.sign
6080d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._int = str(value.int)
6090d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._exp = int(value.exp)
6100d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._is_special = False
611636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return self
612636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
613636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        # tuple/list conversion (possibly from as_tuple())
614636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if isinstance(value, (list,tuple)):
615636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if len(value) != 3:
6169b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                raise ValueError('Invalid tuple size in creation of Decimal '
6179b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                 'from list or tuple.  The list or tuple '
6189b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                 'should have exactly three elements.')
6199b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista            # process sign.  The isinstance test rejects floats
6209b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista            if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
6219b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                raise ValueError("Invalid sign.  The first value in the tuple "
6229b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                 "should be an integer; either 0 for a "
6239b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                 "positive number or 1 for a negative number.")
624636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self._sign = value[0]
6259b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista            if value[2] == 'F':
6269b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                # infinity: value[1] is ignored
62772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                self._int = '0'
628636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                self._exp = value[2]
629636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                self._is_special = True
630636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            else:
6319b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                # process and validate the digits in value[1]
6329b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                digits = []
6339b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                for digit in value[1]:
6349b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    if isinstance(digit, (int, long)) and 0 <= digit <= 9:
6359b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                        # skip leading zeros
6369b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                        if digits or digit != 0:
6379b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                            digits.append(digit)
6389b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    else:
6399b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                        raise ValueError("The second value in the tuple must "
6409b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                         "be composed of integers in the range "
6419b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                         "0 through 9.")
6429b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                if value[2] in ('n', 'N'):
6439b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    # NaN: digits form the diagnostic
64472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                    self._int = ''.join(map(str, digits))
6459b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    self._exp = value[2]
6469b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    self._is_special = True
6479b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                elif isinstance(value[2], (int, long)):
6489b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    # finite number: digits give the coefficient
64972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                    self._int = ''.join(map(str, digits or [0]))
6509b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    self._exp = value[2]
6519b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    self._is_special = False
6529b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                else:
6539b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    raise ValueError("The third value in the tuple must "
6549b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                     "be an integer, or one of the "
6559b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                     "strings 'F', 'n', 'N'.")
656636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return self
657636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
658636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if isinstance(value, float):
659636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            raise TypeError("Cannot convert float to Decimal.  " +
660636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                            "First convert the float to a string")
6617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
662636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        raise TypeError("Cannot convert %r to Decimal" % value)
6637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _isnan(self):
6657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns whether the number is not actually one.
6667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        0 if a number
668353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        1 if NaN  (it could be a normal quiet NaN or a phantom one)
6697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        2 if sNaN
6707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
671636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
672636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            exp = self._exp
673636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if exp == 'n':
674636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return 1
675636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            elif exp == 'N':
676636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return 2
6777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return 0
6787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _isinfinity(self):
6807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns whether the number is infinite
6817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        0 if finite or not a number
6837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        1 if +INF
6847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        -1 if -INF
6857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
6867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._exp == 'F':
6877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if self._sign:
6887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return -1
6897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return 1
6907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return 0
6917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
692353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _check_nans(self, other=None, context=None):
6937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns whether the number is not actually one.
6947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self, other are sNaN, signal
6967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self, other are NaN return nan
6977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return 0
6987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Done before operations.
7007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
7017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
702636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        self_is_nan = self._isnan()
703636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if other is None:
704636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            other_is_nan = False
705636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        else:
706636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            other_is_nan = other._isnan()
707636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
708636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self_is_nan or other_is_nan:
709636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if context is None:
710636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                context = getcontext()
711636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
712636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self_is_nan == 2:
713636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return context._raise_error(InvalidOperation, 'sNaN',
714636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                                        1, self)
715636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if other_is_nan == 2:
716636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return context._raise_error(InvalidOperation, 'sNaN',
717636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                                        1, other)
718636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self_is_nan:
719353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self._fix_nan(context)
720636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
721353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return other._fix_nan(context)
7227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return 0
7237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __nonzero__(self):
7251a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is nonzero; otherwise return False.
7267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7271a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        NaNs and infinities are considered nonzero.
7287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
72972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return self._is_special or self._int != '0'
7307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
731353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def __cmp__(self, other):
732636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
733267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
734353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # Never return NotImplemented
735353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return 1
7367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
737636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
738353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # check for nans, without raising on a signaling nan
739353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self._isnan() or other._isnan():
74059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                return 1  # Comparison involving NaN's always reports self > other
741636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
742636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            # INF = INF
743636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return cmp(self._isinfinity(), other._isinfinity())
7447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
745353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # check for zeros;  note that cmp(0, -0) should return 0
746353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
747353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if not other:
748353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return 0
749353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
750353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return -((-1)**other._sign)
751353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other:
752353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return (-1)**self._sign
7537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
75459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # If different signs, neg one is less
7557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if other._sign < self._sign:
7567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return -1
7577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign < other._sign:
7587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return 1
7597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
760636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        self_adjusted = self.adjusted()
761636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other_adjusted = other.adjusted()
762353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_adjusted == other_adjusted:
76372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self_padded = self._int + '0'*(self._exp - other._exp)
76472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            other_padded = other._int + '0'*(other._exp - self._exp)
765353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return cmp(self_padded, other_padded) * (-1)**self._sign
766353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif self_adjusted > other_adjusted:
7677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return (-1)**self._sign
768353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else: # self_adjusted < other_adjusted
7697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return -((-1)**self._sign)
7707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7710aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger    def __eq__(self, other):
7720aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger        if not isinstance(other, (Decimal, int, long)):
773267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return NotImplemented
7740aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger        return self.__cmp__(other) == 0
7750aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger
7760aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger    def __ne__(self, other):
7770aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger        if not isinstance(other, (Decimal, int, long)):
778267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return NotImplemented
7790aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger        return self.__cmp__(other) != 0
7800aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger
7817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def compare(self, other, context=None):
7827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Compares one to another.
7837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        -1 => a < b
7857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        0  => a = b
7867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        1  => a > b
7877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        NaN => one is NaN
7887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Like __cmp__, but returns Decimal instances.
7897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
790353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
7917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
79259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # Compare(NaN, NaN) = NaN
793636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if (self._is_special or other and other._is_special):
794636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
795636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
796636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
7977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
798353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal(self.__cmp__(other))
7997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __hash__(self):
8017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """x.__hash__() <==> hash(x)"""
8027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Decimal integers must hash the same as the ints
8037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Non-integer decimals are normalized and hashed as strings
8041fb9f528bd69efa135bacda917ec7bb166068d5dGeorg Brandl        # Normalization assures that hash(100E-1) == hash(10)
805bea3f6f5c788eb4f0f7639913ff89654152864c0Raymond Hettinger        if self._is_special:
806bea3f6f5c788eb4f0f7639913ff89654152864c0Raymond Hettinger            if self._isnan():
807bea3f6f5c788eb4f0f7639913ff89654152864c0Raymond Hettinger                raise TypeError('Cannot hash a NaN value.')
808bea3f6f5c788eb4f0f7639913ff89654152864c0Raymond Hettinger            return hash(str(self))
8098c202440699cef19602acc24822366d0d7c32083Facundo Batista        if not self:
8108c202440699cef19602acc24822366d0d7c32083Facundo Batista            return 0
8118c202440699cef19602acc24822366d0d7c32083Facundo Batista        if self._isinteger():
8128c202440699cef19602acc24822366d0d7c32083Facundo Batista            op = _WorkRep(self.to_integral_value())
8138c202440699cef19602acc24822366d0d7c32083Facundo Batista            # to make computation feasible for Decimals with large
8148c202440699cef19602acc24822366d0d7c32083Facundo Batista            # exponent, we use the fact that hash(n) == hash(m) for
8158c202440699cef19602acc24822366d0d7c32083Facundo Batista            # any two nonzero integers n and m such that (i) n and m
8168c202440699cef19602acc24822366d0d7c32083Facundo Batista            # have the same sign, and (ii) n is congruent to m modulo
8178c202440699cef19602acc24822366d0d7c32083Facundo Batista            # 2**64-1.  So we can replace hash((-1)**s*c*10**e) with
8188c202440699cef19602acc24822366d0d7c32083Facundo Batista            # hash((-1)**s*c*pow(10, e, 2**64-1).
8198c202440699cef19602acc24822366d0d7c32083Facundo Batista            return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
8207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return hash(str(self.normalize()))
8217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def as_tuple(self):
8237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Represents the number as a triple tuple.
8247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        To show the internals exactly as they are.
8267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
82772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return (self._sign, tuple(map(int, self._int)), self._exp)
8287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __repr__(self):
8307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Represents the number as an instance of Decimal."""
8317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Invariant:  eval(repr(d)) == d
8327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return 'Decimal("%s")' % str(self)
8337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
834353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def __str__(self, eng=False, context=None):
8357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return string representation of the number in scientific notation.
8367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Captures all of the information in the underlying representation.
8387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
8397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
84062edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        sign = ['', '-'][self._sign]
841e5a0a9609faea9afdc6f81f1f6dfa07b1437e3aeRaymond Hettinger        if self._is_special:
84262edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            if self._exp == 'F':
84362edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista                return sign + 'Infinity'
84462edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            elif self._exp == 'n':
84562edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista                return sign + 'NaN' + self._int
84662edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            else: # self._exp == 'N'
84762edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista                return sign + 'sNaN' + self._int
84862edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista
84962edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        # number of digits of self._int to left of decimal point
85062edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        leftdigits = self._exp + len(self._int)
85162edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista
85262edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        # dotplace is number of digits of self._int to the left of the
85362edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        # decimal point in the mantissa of the output string (that is,
85462edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        # after adjusting the exponent)
85562edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        if self._exp <= 0 and leftdigits > -6:
85662edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            # no exponent required
85762edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            dotplace = leftdigits
85862edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        elif not eng:
85962edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            # usual scientific notation: 1 digit on left of the point
8607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            dotplace = 1
86162edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        elif self._int == '0':
86262edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            # engineering notation, zero
86362edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            dotplace = (leftdigits + 1) % 3 - 1
8647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
86562edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            # engineering notation, nonzero
86662edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            dotplace = (leftdigits - 1) % 3 + 1
86762edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista
86862edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        if dotplace <= 0:
86962edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            intpart = '0'
87062edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            fracpart = '.' + '0'*(-dotplace) + self._int
87162edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        elif dotplace >= len(self._int):
87262edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            intpart = self._int+'0'*(dotplace-len(self._int))
87362edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            fracpart = ''
87462edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        else:
87562edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            intpart = self._int[:dotplace]
87662edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            fracpart = '.' + self._int[dotplace:]
87762edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        if leftdigits == dotplace:
87862edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            exp = ''
87962edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        else:
88062edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            if context is None:
88162edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista                context = getcontext()
88262edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
88362edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista
88462edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        return sign + intpart + fracpart + exp
8857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def to_eng_string(self, context=None):
8877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Convert to engineering-type string.
8887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Engineering notation has an exponent which is a multiple of 3, so there
8907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        are up to 3 digits left of the decimal place.
8917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Same rules for when in exponential and when as a value as in __str__.
8937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
894353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self.__str__(eng=True, context=context)
8957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __neg__(self, context=None):
8977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns a copy with the sign switched.
8987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Rounds, if it has reason.
9007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
901636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
902636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
903636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
904636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
9057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
9077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            # -Decimal('0') is Decimal('0'), not Decimal('-0')
908353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.copy_sign(Dec_0)
9097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
910353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.copy_negate()
911636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
912636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
913636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
9147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context._rounding_decision == ALWAYS_ROUND:
915353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
916353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
9177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __pos__(self, context=None):
9197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns a copy, unless it is a sNaN.
9207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Rounds the number (if more then precision digits)
9227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
923636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
924636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
925636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
926636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
9277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
9297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            # + (-0) = 0
930353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.copy_sign(Dec_0)
931353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
932353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal(self)
9337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
934636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
935636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
9367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context._rounding_decision == ALWAYS_ROUND:
937353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
9387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
9397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __abs__(self, round=1, context=None):
9417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the absolute value of self.
9427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the second argument is 0, do not round.
9447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
945636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
946636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
947636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
948636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
9497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not round:
951636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if context is None:
952636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                context = getcontext()
9539fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger            context = context._shallow_copy()
9547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context._set_rounding_decision(NEVER_ROUND)
9557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign:
9577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = self.__neg__(context=context)
9587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
9597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = self.__pos__(context=context)
9607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
9627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __add__(self, other, context=None):
9647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns self + other.
9657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        -INF + INF (or the reverse) cause InvalidOperation errors.
9677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
968636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
969267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
970267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
971636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
9727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
9737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
9747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
975636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
976636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
977636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
978636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
9797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
980636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity():
98159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                # If both INF, same sign => same as both, opposite => error.
982636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if self._sign != other._sign and other._isinfinity():
983636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    return context._raise_error(InvalidOperation, '-INF + INF')
984636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Decimal(self)
985636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if other._isinfinity():
98659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                return Decimal(other)  # Can't both be infinity here
9877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        shouldround = context._rounding_decision == ALWAYS_ROUND
9897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exp = min(self._exp, other._exp)
9917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        negativezero = 0
9927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context.rounding == ROUND_FLOOR and self._sign != other._sign:
99359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If the answer is 0, the sign should be negative, in this case.
9947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            negativezero = 1
9957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self and not other:
9977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            sign = min(self._sign, other._sign)
9987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if negativezero:
9997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                sign = 1
100072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(sign, '0', exp)
1001353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if shouldround:
1002353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                ans = ans._fix(context)
1003353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
10047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
100599b5548298ffc2ae5f03bd9ef873ce45a9844f0eFacundo Batista            exp = max(exp, other._exp - context.prec-1)
1006353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = other._rescale(exp, context.rounding)
10077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if shouldround:
1008dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger                ans = ans._fix(context)
10097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
10107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not other:
101199b5548298ffc2ae5f03bd9ef873ce45a9844f0eFacundo Batista            exp = max(exp, self._exp - context.prec-1)
1012353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._rescale(exp, context.rounding)
10137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if shouldround:
1014dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger                ans = ans._fix(context)
10157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
10167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        op1 = _WorkRep(self)
10187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        op2 = _WorkRep(other)
10197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        op1, op2 = _normalize(op1, op2, shouldround, context.prec)
10207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        result = _WorkRep()
10227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if op1.sign != op2.sign:
10237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            # Equal and opposite
102417931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            if op1.int == op2.int:
102572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(negativezero, '0', exp)
1026353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if shouldround:
1027353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    ans = ans._fix(context)
1028353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return ans
102917931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            if op1.int < op2.int:
10307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                op1, op2 = op2, op1
103159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                # OK, now abs(op1) > abs(op2)
103217931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            if op1.sign == 1:
103317931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger                result.sign = 1
10347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                op1.sign, op2.sign = op2.sign, op1.sign
10357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            else:
103617931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger                result.sign = 0
103759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                # So we know the sign, and op1 > 0.
103817931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        elif op1.sign == 1:
10397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            result.sign = 1
104017931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            op1.sign, op2.sign = (0, 0)
104117931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        else:
104217931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            result.sign = 0
104359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # Now, op1 > abs(op2) > 0
10447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
104517931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        if op2.sign == 0:
1046636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            result.int = op1.int + op2.int
10477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
1048636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            result.int = op1.int - op2.int
10497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        result.exp = op1.exp
10517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        ans = Decimal(result)
10527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if shouldround:
1053dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger            ans = ans._fix(context)
10547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
10557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __radd__ = __add__
10577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __sub__(self, other, context=None):
1059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return self - other"""
1060636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1061267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1062267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
10637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1064636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
1065636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context=context)
1066636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
1067636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
10687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1069353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self - other is computed as self + other.copy_negate()
1070353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self.__add__(other.copy_negate(), context=context)
10717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rsub__(self, other, context=None):
1073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return other - self"""
1074636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1075267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1076267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
10777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1078353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return other.__sub__(self, context=context)
10797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __mul__(self, other, context=None):
10817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return self * other.
10827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        (+-) INF * 0 (or its reverse) raise InvalidOperation.
10847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1085636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1086267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1087267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
1088636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
10897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
10907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
10917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1092d87ac8f24da5dce860b559b69e6af59edd2c3eecRaymond Hettinger        resultsign = self._sign ^ other._sign
10937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1094636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
1095636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
1096636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
1097636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
1098636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1099636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity():
1100636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if not other:
1101636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    return context._raise_error(InvalidOperation, '(+-)INF * 0')
1102636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Infsign[resultsign]
1103636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1104636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if other._isinfinity():
1105636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if not self:
1106636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    return context._raise_error(InvalidOperation, '0 * (+-)INF')
1107636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Infsign[resultsign]
11087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        resultexp = self._exp + other._exp
11107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        shouldround = context._rounding_decision == ALWAYS_ROUND
11117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Special case for multiplying by zero
11137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self or not other:
111472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(resultsign, '0', resultexp)
11157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if shouldround:
111659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                # Fixing in case the exponent is out of bounds
1117dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger                ans = ans._fix(context)
11187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
11197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Special case for multiplying by power of 10
112172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        if self._int == '1':
112272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(resultsign, other._int, resultexp)
11237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if shouldround:
1124dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger                ans = ans._fix(context)
11257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
112672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        if other._int == '1':
112772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(resultsign, self._int, resultexp)
11287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if shouldround:
1129dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger                ans = ans._fix(context)
11307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
11317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1132636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        op1 = _WorkRep(self)
1133636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        op2 = _WorkRep(other)
1134636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
113572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
11367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if shouldround:
1137dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger            ans = ans._fix(context)
11387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
11407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __rmul__ = __mul__
11417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __div__(self, other, context=None):
11437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return self / other."""
1144636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1145267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1146cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return NotImplemented
1147636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
11487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
11497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
11507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1151636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        sign = self._sign ^ other._sign
1152636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1153636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
1154636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
1155636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
11567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return ans
11577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1158636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity() and other._isinfinity():
11597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
11607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if self._isinfinity():
1162636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Infsign[sign]
1163636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1164636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if other._isinfinity():
1165636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                context._raise_error(Clamped, 'Division by infinity')
116672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(sign, '0', context.Etiny())
1167636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1168636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        # Special cases for zeroes
1169636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if not other:
1170cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if not self:
1171cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(DivisionUndefined, '0 / 0')
1172636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return context._raise_error(DivisionByZero, 'x / 0', sign)
11737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1174cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if not self:
1175cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            exp = self._exp - other._exp
1176cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            coeff = 0
1177cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        else:
1178cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            # OK, so neither = 0, INF or NaN
1179cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            shift = len(other._int) - len(self._int) + context.prec + 1
1180cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            exp = self._exp - other._exp - shift
1181cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            op1 = _WorkRep(self)
1182cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            op2 = _WorkRep(other)
1183cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if shift >= 0:
1184cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1185cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1186cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1187cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if remainder:
1188cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                # result is not exact; adjust to ensure correct rounding
1189cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                if coeff % 5 == 0:
1190cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                    coeff += 1
1191cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1192cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                # result is exact; get as close to ideal exponent as possible
1193cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                ideal_exp = self._exp - other._exp
1194cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                while exp < ideal_exp and coeff % 10 == 0:
1195cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                    coeff //= 10
1196cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                    exp += 1
11977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
119872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        ans = _dec_from_triple(sign, str(coeff), exp)
1199cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return ans._fix(context)
12007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1201cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista    __truediv__ = __div__
12027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1203cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista    def _divide(self, other, context):
1204cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        """Return (self // other, self % other), to context.prec precision.
12057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1206cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        Assumes that neither self nor other is a NaN, that self is not
1207cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        infinite and that other is nonzero.
1208cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        """
1209cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        sign = self._sign ^ other._sign
1210cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if other._isinfinity():
1211cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            ideal_exp = self._exp
1212cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        else:
1213cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            ideal_exp = min(self._exp, other._exp)
12147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1215cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        expdiff = self.adjusted() - other.adjusted()
1216cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if not self or other._isinfinity() or expdiff <= -2:
121772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return (_dec_from_triple(sign, '0', 0),
1218cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                    self._rescale(ideal_exp, context.rounding))
1219cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if expdiff <= context.prec:
1220cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            op1 = _WorkRep(self)
1221cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            op2 = _WorkRep(other)
1222cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if op1.exp >= op2.exp:
1223cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                op1.int *= 10**(op1.exp - op2.exp)
1224cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1225cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                op2.int *= 10**(op2.exp - op1.exp)
1226cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            q, r = divmod(op1.int, op2.int)
1227cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if q < 10**context.prec:
122872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return (_dec_from_triple(sign, str(q), 0),
122972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                        _dec_from_triple(self._sign, str(r), ideal_exp))
12307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1231cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        # Here the quotient is too large to be representable
1232cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        ans = context._raise_error(DivisionImpossible,
1233cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                                   'quotient too large in //, % or divmod')
1234cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return ans, ans
12357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rdiv__(self, other, context=None):
12377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Swaps self/other and returns __div__."""
1238636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1239267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1240267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
12417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return other.__div__(self, context=context)
12427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __rtruediv__ = __rdiv__
12437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __divmod__(self, other, context=None):
12457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1246cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        Return (self // other, self % other)
12477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1248cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        other = _convert_other(other)
1249cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if other is NotImplemented:
1250cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return other
1251cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1252cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if context is None:
1253cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            context = getcontext()
1254cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1255cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        ans = self._check_nans(other, context)
1256cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if ans:
1257cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return (ans, ans)
1258cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1259cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        sign = self._sign ^ other._sign
1260cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if self._isinfinity():
1261cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if other._isinfinity():
1262cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1263cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return ans, ans
1264cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1265cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return (Infsign[sign],
1266cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                        context._raise_error(InvalidOperation, 'INF % x'))
1267cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1268cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if not other:
1269cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if not self:
1270cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1271cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return ans, ans
1272cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1273cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return (context._raise_error(DivisionByZero, 'x // 0', sign),
1274cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                        context._raise_error(InvalidOperation, 'x % 0'))
1275cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1276cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        quotient, remainder = self._divide(other, context)
1277cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if context._rounding_decision == ALWAYS_ROUND:
1278cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            remainder = remainder._fix(context)
1279cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return quotient, remainder
12807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rdivmod__(self, other, context=None):
12827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Swaps self/other and returns __divmod__."""
1283636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1284267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1285267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
12867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return other.__divmod__(self, context=context)
12877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __mod__(self, other, context=None):
12897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
12907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self % other
12917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1292636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1293267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1294267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
12957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1296cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if context is None:
1297cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            context = getcontext()
12987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1299cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        ans = self._check_nans(other, context)
1300cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if ans:
1301cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return ans
13027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1303cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if self._isinfinity():
1304cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return context._raise_error(InvalidOperation, 'INF % x')
1305cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        elif not other:
1306cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if self:
1307cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(InvalidOperation, 'x % 0')
1308cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1309cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(DivisionUndefined, '0 % 0')
1310cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1311cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        remainder = self._divide(other, context)[1]
1312cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if context._rounding_decision == ALWAYS_ROUND:
1313cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            remainder = remainder._fix(context)
1314cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return remainder
13157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rmod__(self, other, context=None):
13177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Swaps self/other and returns __mod__."""
1318636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1319267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1320267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
13217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return other.__mod__(self, context=context)
13227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def remainder_near(self, other, context=None):
13247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
13257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Remainder nearest to 0-  abs(remainder-near) <= other/2
13267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1327636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
1328636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
13297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1330353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
13317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1332353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
1333353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
1334353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
13357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1336353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self == +/-infinity -> InvalidOperation
1337353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
1338353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1339353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'remainder_near(infinity, x)')
13407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1341353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # other == 0 -> either InvalidOperation or DivisionUndefined
1342353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other:
1343353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self:
1344353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation,
1345353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                            'remainder_near(x, 0)')
1346353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1347353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(DivisionUndefined,
1348353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                            'remainder_near(0, 0)')
13497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1350353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # other = +/-infinity -> remainder = self
1351353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._isinfinity():
1352353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal(self)
1353353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
13547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1355353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self = 0 -> remainder = self, with ideal exponent
1356353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ideal_exponent = min(self._exp, other._exp)
1357353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
135872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(self._sign, '0', ideal_exponent)
1359353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
13607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1361353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # catch most cases of large or small quotient
1362353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        expdiff = self.adjusted() - other.adjusted()
1363353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if expdiff >= context.prec + 1:
1364353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # expdiff >= prec+1 => abs(self/other) > 10**prec
1365cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return context._raise_error(DivisionImpossible)
1366353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if expdiff <= -2:
1367353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # expdiff <= -2 => abs(self/other) < 0.1
1368353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._rescale(ideal_exponent, context.rounding)
1369353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
13707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1371353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # adjust both arguments to have the same exponent, then divide
1372353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op1 = _WorkRep(self)
1373353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op2 = _WorkRep(other)
1374353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if op1.exp >= op2.exp:
1375353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            op1.int *= 10**(op1.exp - op2.exp)
13767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
1377353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            op2.int *= 10**(op2.exp - op1.exp)
1378353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        q, r = divmod(op1.int, op2.int)
1379353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # remainder is r*10**ideal_exponent; other is +/-op2.int *
1380353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 10**ideal_exponent.   Apply correction to ensure that
1381353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # abs(remainder) <= abs(other)/2
1382353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if 2*r + (q&1) > op2.int:
1383353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            r -= op2.int
1384353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            q += 1
1385353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1386353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if q >= 10**context.prec:
1387cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return context._raise_error(DivisionImpossible)
1388353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1389353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # result has same sign as self unless r is negative
1390353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        sign = self._sign
1391353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if r < 0:
1392353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sign = 1-sign
1393353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            r = -r
13947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
139572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        ans = _dec_from_triple(sign, str(r), ideal_exponent)
1396353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans._fix(context)
13977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __floordiv__(self, other, context=None):
13997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """self // other"""
1400cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        other = _convert_other(other)
1401cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if other is NotImplemented:
1402cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return other
1403cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1404cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if context is None:
1405cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            context = getcontext()
1406cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1407cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        ans = self._check_nans(other, context)
1408cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if ans:
1409cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return ans
1410cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1411cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if self._isinfinity():
1412cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if other._isinfinity():
1413cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(InvalidOperation, 'INF // INF')
1414cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1415cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return Infsign[self._sign ^ other._sign]
1416cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1417cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if not other:
1418cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if self:
1419cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(DivisionByZero, 'x // 0',
1420cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                                            self._sign ^ other._sign)
1421cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1422cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(DivisionUndefined, '0 // 0')
1423cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1424cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return self._divide(other, context)[0]
14257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rfloordiv__(self, other, context=None):
14277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Swaps self/other and returns __floordiv__."""
1428636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1429267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1430267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
14317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return other.__floordiv__(self, context=context)
14327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __float__(self):
14347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Float representation."""
14357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return float(str(self))
14367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __int__(self):
143846b0802ccd9a9c47b27a285526fbb2a8bee5b8cbBrett Cannon        """Converts self to an int, truncating if necessary."""
1439636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
1440636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isnan():
1441636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                context = getcontext()
1442636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return context._raise_error(InvalidContext)
1443636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            elif self._isinfinity():
144459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                raise OverflowError("Cannot convert infinity to long")
1445353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        s = (-1)**self._sign
14467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._exp >= 0:
144772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return s*int(self._int)*10**self._exp
1448605ed0248375bbf87bbd1d80afc7c6918fd3ce2bRaymond Hettinger        else:
144972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return s*int(self._int[:self._exp] or '0')
14507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __long__(self):
14527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Converts to a long.
14537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Equivalent to long(int(self))
14557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
14567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return long(self.__int__())
14577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1458353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _fix_nan(self, context):
1459353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Decapitate the payload of a NaN to fit the context"""
1460353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        payload = self._int
1461353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1462353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # maximum length of payload is precision if _clamp=0,
1463353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # precision-1 if _clamp=1.
1464353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        max_payload_len = context.prec - context._clamp
1465353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if len(payload) > max_payload_len:
146672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            payload = payload[len(payload)-max_payload_len:].lstrip('0')
146772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(self._sign, payload, self._exp, True)
14686c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        return Decimal(self)
1469353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1470dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger    def _fix(self, context):
14717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Round if it is necessary to keep self within prec precision.
14727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Rounds and fixes the exponent.  Does not raise on a sNaN.
14747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Arguments:
14767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self - Decimal instance
14777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        context - context used.
14787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1479636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
14807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
14817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
14827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1483353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
1484353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self._isnan():
1485353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # decapitate payload if necessary
1486353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self._fix_nan(context)
1487353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1488353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # self is +/-Infinity; return unaltered
14896c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                return Decimal(self)
14907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1491353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if self is zero then exponent should be between Etiny and
1492353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1493353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Etiny = context.Etiny()
1494353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Etop = context.Etop()
14957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
1496353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            exp_max = [context.Emax, Etop][context._clamp]
1497353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            new_exp = min(max(self._exp, Etiny), exp_max)
1498353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if new_exp != self._exp:
1499353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Clamped)
150072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(self._sign, '0', new_exp)
15017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            else:
15026c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                return Decimal(self)
15037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1504353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp_min is the smallest allowable exponent of the result,
1505353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # equal to max(self.adjusted()-context.prec+1, Etiny)
1506353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exp_min = len(self._int) + self._exp - context.prec
1507353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if exp_min > Etop:
1508353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # overflow: exp_min > Etop iff self.adjusted() > Emax
1509353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
1510353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Rounded)
1511353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(Overflow, 'above Emax', self._sign)
1512353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_is_subnormal = exp_min < Etiny
1513353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_is_subnormal:
1514353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Subnormal)
1515353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            exp_min = Etiny
15167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1517353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # round if self has too many digits
1518353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp < exp_min:
15197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context._raise_error(Rounded)
15202ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            digits = len(self._int) + self._exp - exp_min
15212ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            if digits < 0:
15222ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista                self = _dec_from_triple(self._sign, '1', exp_min-1)
15232ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista                digits = 0
15242ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            this_function = getattr(self, self._pick_rounding_function[context.rounding])
15252ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            changed = this_function(digits)
15262ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            coeff = self._int[:digits] or '0'
15272ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            if changed == 1:
15282ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista                coeff = str(int(coeff)+1)
15292ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            ans = _dec_from_triple(self._sign, coeff, exp_min)
15302ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista
15312ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            if changed:
1532353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Inexact)
1533353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_is_subnormal:
1534353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    context._raise_error(Underflow)
1535353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if not ans:
1536353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        # raise Clamped on underflow to 0
1537353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        context._raise_error(Clamped)
1538353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                elif len(ans._int) == context.prec+1:
1539353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    # we get here only if rescaling rounds the
1540353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    # cofficient up to exactly 10**context.prec
1541353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if ans._exp < Etop:
154272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                        ans = _dec_from_triple(ans._sign,
154372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                                   ans._int[:-1], ans._exp+1)
1544353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    else:
1545353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        # Inexact and Rounded have already been raised
1546353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        ans = context._raise_error(Overflow, 'above Emax',
1547353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                                   self._sign)
15487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
15497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1550353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # fold down if _clamp == 1 and self has too few digits
1551353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context._clamp == 1 and self._exp > Etop:
1552353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Clamped)
155372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self_padded = self._int + '0'*(self._exp - Etop)
155472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(self._sign, self_padded, Etop)
15557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1556353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # here self was representable to begin with; return unchanged
15576c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        return Decimal(self)
15587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
15597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    _pick_rounding_function = {}
15607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1561353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # for each of the rounding functions below:
1562353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #   self is a finite, nonzero Decimal
1563353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #   prec is an integer satisfying 0 <= prec < len(self._int)
15642ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    #
15652ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    # each function returns either -1, 0, or 1, as follows:
15662ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    #   1 indicates that self should be rounded up (away from zero)
15672ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    #   0 indicates that self should be truncated, and that all the
15682ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    #     digits to be truncated are zeros (so the value is unchanged)
15692ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    #  -1 indicates that there are nonzero digits to be truncated
15707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1571353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_down(self, prec):
1572353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Also known as round-towards-0, truncate."""
15732ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        if _all_zeros(self._int, prec):
15742ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return 0
15752ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        else:
15762ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -1
15777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1578353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_up(self, prec):
1579353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds away from 0."""
15802ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        return -self._round_down(prec)
15817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1582353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_half_up(self, prec):
1583353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds 5 up (away from 0)"""
158472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        if self._int[prec] in '56789':
15852ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return 1
15862ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        elif _all_zeros(self._int, prec):
15872ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return 0
1588353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
15892ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -1
15907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1591353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_half_down(self, prec):
15927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Round 5 down"""
15932ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        if _exact_half(self._int, prec):
15942ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -1
15952ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        else:
15962ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return self._round_half_up(prec)
15977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1598353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_half_even(self, prec):
1599353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Round 5 to even, rest to nearest."""
16002ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        if _exact_half(self._int, prec) and \
16012ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista                (prec == 0 or self._int[prec-1] in '02468'):
16022ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -1
1603353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
16042ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return self._round_half_up(prec)
16057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1606353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_ceiling(self, prec):
16077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Rounds up (not away from 0 if negative.)"""
16087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign:
1609353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_down(prec)
16107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
16112ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -self._round_down(prec)
16127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1613353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_floor(self, prec):
16147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Rounds down (not towards 0 if negative)"""
16157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self._sign:
1616353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_down(prec)
16177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
16182ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -self._round_down(prec)
16197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1620353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_05up(self, prec):
1621353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Round down unless digit prec-1 is 0 or 5."""
16222ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        if prec and self._int[prec-1] not in '05':
1623353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_down(prec)
16242ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        else:
16252ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -self._round_down(prec)
1626353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1627353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def fma(self, other, third, context=None):
1628353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Fused multiply-add.
16297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1630353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Returns self*other+third with no rounding of the intermediate
1631353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        product self*other.
1632353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1633353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self and other are multiplied together, with no rounding of
1634353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        the result.  The third operand is then added to the result,
1635353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        and a single final rounding is performed.
16367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1637353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1638353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
1639353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        third = _convert_other(third, raiseit=True)
1640636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
16417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
16427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
16437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1644353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # do self*other in fresh context with no traps and no rounding
1645353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        mul_context = Context(traps=[], flags=[],
1646353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                              _rounding_decision=NEVER_ROUND)
1647353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        product = self.__mul__(other, mul_context)
16487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1649353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if mul_context.flags[InvalidOperation]:
1650353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # reraise in current context
1651353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1652353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'invalid multiplication in fma',
1653353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, product)
16547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1655353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = product.__add__(third, context)
1656353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
16577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1658353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _power_modulo(self, other, modulo, context=None):
1659353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Three argument version of __pow__"""
16607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1661353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if can't convert other and modulo to Decimal, raise
1662353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # TypeError; there's no point returning NotImplemented (no
1663353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # equivalent of __rpow__ for three argument pow)
1664353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
1665353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        modulo = _convert_other(modulo, raiseit=True)
16667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1667353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
1668353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
16697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1670353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # deal with NaNs: if there are any sNaNs then first one wins,
1671353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (i.e. behaviour for NaNs is identical to that of fma)
1672353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_is_nan = self._isnan()
1673353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other_is_nan = other._isnan()
1674353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        modulo_is_nan = modulo._isnan()
1675353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_is_nan or other_is_nan or modulo_is_nan:
1676353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self_is_nan == 2:
1677353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation, 'sNaN',
1678353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, self)
1679353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other_is_nan == 2:
1680353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation, 'sNaN',
1681353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, other)
1682353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if modulo_is_nan == 2:
1683353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation, 'sNaN',
1684353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, modulo)
1685353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self_is_nan:
16866c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                return self._fix_nan(context)
1687353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other_is_nan:
16886c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                return other._fix_nan(context)
16896c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return modulo._fix_nan(context)
1690353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1691353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # check inputs: we apply same restrictions as Python's pow()
1692353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (self._isinteger() and
1693353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                other._isinteger() and
1694353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                modulo._isinteger()):
1695353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1696353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'pow() 3rd argument not allowed '
1697353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'unless all arguments are integers')
1698353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other < 0:
1699353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1700353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'pow() 2nd argument cannot be '
1701353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'negative when 3rd argument specified')
1702353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not modulo:
1703353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1704353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'pow() 3rd argument cannot be 0')
1705353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1706353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # additional restriction for decimal: the modulus must be less
1707353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # than 10**prec in absolute value
1708353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if modulo.adjusted() >= context.prec:
1709353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1710353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'insufficient precision: pow() 3rd '
1711353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'argument must not have more than '
1712353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'precision digits')
1713353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1714353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # define 0**0 == NaN, for consistency with two-argument pow
1715353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (even though it hurts!)
1716353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other and not self:
1717353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1718353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'at least one of pow() 1st argument '
1719353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'and 2nd argument must be nonzero ;'
1720353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        '0**0 is not defined')
1721353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1722353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute sign of result
1723353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._iseven():
1724353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sign = 0
1725353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
1726353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sign = self._sign
1727353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1728353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # convert modulo to a Python integer, and self and other to
1729353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Decimal integers (i.e. force their exponents to be >= 0)
1730353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        modulo = abs(int(modulo))
1731353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        base = _WorkRep(self.to_integral_value())
1732353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exponent = _WorkRep(other.to_integral_value())
1733353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1734353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute result using integer pow()
1735353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1736353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        for i in xrange(exponent.exp):
1737353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            base = pow(base, 10, modulo)
1738353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        base = pow(base, exponent.int, modulo)
1739353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
174072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(sign, str(base), 0)
1741353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1742353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _power_exact(self, other, p):
1743353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Attempt to compute self**other exactly.
1744353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1745353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Given Decimals self and other and an integer p, attempt to
1746353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        compute an exact result for the power self**other, with p
1747353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        digits of precision.  Return None if self**other is not
1748353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exactly representable in p digits.
1749353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1750353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Assumes that elimination of special cases has already been
1751353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        performed: self and other must both be nonspecial; self must
1752353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        be positive and not numerically equal to 1; other must be
1753353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        nonzero.  For efficiency, other._exp should not be too large,
1754353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        so that 10**abs(other._exp) is a feasible calculation."""
1755353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1756353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # In the comments below, we write x for the value of self and
1757353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # y for the value of other.  Write x = xc*10**xe and y =
1758353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # yc*10**ye.
1759353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1760353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # The main purpose of this method is to identify the *failure*
1761353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # of x**y to be exactly representable with as little effort as
1762353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # possible.  So we look for cheap and easy tests that
1763353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # eliminate the possibility of x**y being exact.  Only if all
1764353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # these tests are passed do we go on to actually compute x**y.
1765353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1766353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Here's the main idea.  First normalize both x and y.  We
1767353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # express y as a rational m/n, with m and n relatively prime
1768353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # and n>0.  Then for x**y to be exactly representable (at
1769353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # *any* precision), xc must be the nth power of a positive
1770353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # integer and xe must be divisible by n.  If m is negative
1771353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # then additionally xc must be a power of either 2 or 5, hence
1772353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # a power of 2**n or 5**n.
1773353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1774353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # There's a limit to how small |y| can be: if y=m/n as above
1775353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # then:
1776353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1777353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #  (1) if xc != 1 then for the result to be representable we
1778353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      need xc**(1/n) >= 2, and hence also xc**|y| >= 2.  So
1779353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1780353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      2**(1/|y|), hence xc**|y| < 2 and the result is not
1781353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      representable.
1782353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1783353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #  (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1.  Hence if
1784353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      |y| < 1/|xe| then the result is not representable.
1785353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1786353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Note that since x is not equal to 1, at least one of (1) and
1787353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (2) must apply.  Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1788353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1789353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1790353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # There's also a limit to how large y can be, at least if it's
1791353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # positive: the normalized result will have coefficient xc**y,
1792353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # so if it's representable then xc**y < 10**p, and y <
1793353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # p/log10(xc).  Hence if y*log10(xc) >= p then the result is
1794353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # not exactly representable.
1795353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1796353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1797353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # so |y| < 1/xe and the result is not representable.
1798353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1799353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # < 1/nbits(xc).
1800353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1801353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        x = _WorkRep(self)
1802353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        xc, xe = x.int, x.exp
1803353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while xc % 10 == 0:
1804353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xc //= 10
1805353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xe += 1
1806353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1807353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        y = _WorkRep(other)
1808353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        yc, ye = y.int, y.exp
1809353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while yc % 10 == 0:
1810353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            yc //= 10
1811353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ye += 1
1812353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1813353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # case where xc == 1: result is 10**(xe*y), with xe*y
1814353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # required to be an integer
1815353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if xc == 1:
1816353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ye >= 0:
1817353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exponent = xe*yc*10**ye
1818353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1819353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exponent, remainder = divmod(xe*yc, 10**-ye)
1820353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if remainder:
1821353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1822353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if y.sign == 1:
1823353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exponent = -exponent
1824353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # if other is a nonnegative integer, use ideal exponent
1825353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._isinteger() and other._sign == 0:
1826353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                ideal_exponent = self._exp*int(other)
1827353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                zeros = min(exponent-ideal_exponent, p-1)
1828353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1829353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                zeros = 0
183072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
1831353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1832353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # case where y is negative: xc must be either a power
1833353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # of 2 or a power of 5.
1834353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if y.sign == 1:
1835353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            last_digit = xc % 10
1836353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if last_digit in (2,4,6,8):
1837353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # quick test for power of 2
1838353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if xc & -xc != xc:
1839353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1840353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # now xc is a power of 2; e is its exponent
1841353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                e = _nbits(xc)-1
1842353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # find e*y and xe*y; both must be integers
1843353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if ye >= 0:
1844353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    y_as_int = yc*10**ye
1845353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e = e*y_as_int
1846353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xe = xe*y_as_int
1847353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                else:
1848353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    ten_pow = 10**-ye
1849353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e, remainder = divmod(e*yc, ten_pow)
1850353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if remainder:
1851353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return None
1852353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xe, remainder = divmod(xe*yc, ten_pow)
1853353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if remainder:
1854353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return None
1855353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1856353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if e*65 >= p*93: # 93/65 > log(10)/log(5)
1857353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1858353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                xc = 5**e
1859353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1860353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            elif last_digit == 5:
1861353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # e >= log_5(xc) if xc is a power of 5; we have
1862353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # equality all the way up to xc=5**2658
1863353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                e = _nbits(xc)*28//65
1864353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                xc, remainder = divmod(5**e, xc)
1865353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if remainder:
1866353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1867353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                while xc % 5 == 0:
1868353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xc //= 5
1869353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e -= 1
1870353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if ye >= 0:
1871353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    y_as_integer = yc*10**ye
1872353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e = e*y_as_integer
1873353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xe = xe*y_as_integer
1874353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                else:
1875353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    ten_pow = 10**-ye
1876353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e, remainder = divmod(e*yc, ten_pow)
1877353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if remainder:
1878353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return None
1879353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xe, remainder = divmod(xe*yc, ten_pow)
1880353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if remainder:
1881353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return None
1882353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if e*3 >= p*10: # 10/3 > log(10)/log(2)
1883353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1884353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                xc = 2**e
1885353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1886353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
18877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1888353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if xc >= 10**p:
1889353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1890353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xe = -e-xe
189172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(0, str(xc), xe)
18927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1893353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # now y is positive; find m and n such that y = m/n
1894353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ye >= 0:
1895353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            m, n = yc*10**ye, 1
1896353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
1897353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1898353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1899353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xc_bits = _nbits(xc)
1900353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1901353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1902353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            m, n = yc, 10**(-ye)
1903353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while m % 2 == n % 2 == 0:
1904353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                m //= 2
1905353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n //= 2
1906353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while m % 5 == n % 5 == 0:
1907353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                m //= 5
1908353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n //= 5
1909353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1910353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute nth root of xc*10**xe
1911353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if n > 1:
1912353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # if 1 < xc < 2**n then xc isn't an nth power
1913353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if xc != 1 and xc_bits <= n:
1914353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1915353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1916353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xe, rem = divmod(xe, n)
1917353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if rem != 0:
1918353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1919353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1920353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # compute nth root of xc using Newton's method
1921353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            a = 1L << -(-_nbits(xc)//n) # initial estimate
1922353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while True:
1923353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                q, r = divmod(xc, a**(n-1))
1924353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if a <= q:
1925353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
1926353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                else:
1927353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    a = (a*(n-1) + q)//n
1928353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if not (a == q and r == 0):
1929353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1930353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xc = a
1931353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1932353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # now xc*10**xe is the nth root of the original xc*10**xe
1933353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute mth power of xc*10**xe
1934353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1935353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1936353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 10**p and the result is not representable.
1937353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if xc > 1 and m > p*100//_log10_lb(xc):
1938353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return None
1939353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        xc = xc**m
1940353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        xe *= m
1941353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if xc > 10**p:
1942353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return None
1943353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1944353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # by this point the result *is* exactly representable
1945353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # adjust the exponent to get as close as possible to the ideal
1946353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exponent, if necessary
1947353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        str_xc = str(xc)
1948353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._isinteger() and other._sign == 0:
1949353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ideal_exponent = self._exp*int(other)
1950353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            zeros = min(xe-ideal_exponent, p-len(str_xc))
1951353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
1952353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            zeros = 0
195372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
1954cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
1955353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def __pow__(self, other, modulo=None, context=None):
1956353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return self ** other [ % modulo].
19577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1958353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        With two arguments, compute self**other.
19597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1960353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        With three arguments, compute (self**other) % modulo.  For the
1961353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        three argument form, the following restrictions on the
1962353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        arguments hold:
19637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1964353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - all three arguments must be integral
1965353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - other must be nonnegative
1966353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - either self or other (or both) must be nonzero
1967353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - modulo must be nonzero and must have at most p digits,
1968353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista           where p is the context precision.
19697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1970353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        If any of these restrictions is violated the InvalidOperation
1971353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        flag is raised.
1972353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1973353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result of pow(self, other, modulo) is identical to the
1974353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        result that would be obtained by computing (self**other) %
1975353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        modulo with unbounded precision, but is computed more
1976353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        efficiently.  It is always exact.
1977353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
1978353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1979353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if modulo is not None:
1980353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._power_modulo(other, modulo, context)
19817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1982636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1983267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1984267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
19857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1986353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
1987353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
19887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1989353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # either argument is a NaN => result is NaN
1990353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
1991353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
1992353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
19937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1994353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
1995353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other:
1996353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if not self:
1997353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation, '0 ** 0')
1998353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1999353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_p1
20007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2001353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # result has sign 1 iff self._sign is 1 and other is an odd integer
2002353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        result_sign = 0
2003353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign == 1:
2004353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._isinteger():
2005353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if not other._iseven():
2006353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    result_sign = 1
2007353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2008353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # -ve**noninteger = NaN
2009353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # (-0)**noninteger = 0**noninteger
2010353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self:
2011353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return context._raise_error(InvalidOperation,
2012353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        'x ** y with x negative and y not an integer')
2013353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # negate self, without doing any unwanted rounding
201472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self = self.copy_negate()
2015353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2016353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2017353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2018353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._sign == 0:
201972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(result_sign, '0', 0)
2020353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2021353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Infsign[result_sign]
2022353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2023353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
2024353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
2025353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._sign == 0:
2026353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Infsign[result_sign]
2027353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
202872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(result_sign, '0', 0)
2029353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2030353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 1**other = 1, but the choice of exponent and the flags
2031353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # depend on the exponent of self, and on whether other is a
2032353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # positive integer, a negative integer, or neither
2033353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self == Dec_p1:
2034353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._isinteger():
2035353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # exp = max(self._exp*max(int(other), 0),
2036353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # 1-context.prec) but evaluating int(other) directly
2037353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # is dangerous until we know other is small (other
2038353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # could be 1e999999999)
2039353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other._sign == 1:
2040353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    multiplier = 0
2041353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                elif other > context.prec:
2042353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    multiplier = context.prec
2043353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                else:
2044353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    multiplier = int(other)
2045353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2046353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exp = self._exp * multiplier
2047353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if exp < 1-context.prec:
2048353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    exp = 1-context.prec
2049353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    context._raise_error(Rounded)
2050353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2051353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Inexact)
2052353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Rounded)
2053353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exp = 1-context.prec
2054353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
205572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
2056353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute adjusted exponent of self
2058353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_adj = self.adjusted()
2059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2060353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self ** infinity is infinity if self > 1, 0 if self < 1
2061353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self ** -infinity is infinity if self < 1, 0 if self > 1
2062353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._isinfinity():
2063353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if (other._sign == 0) == (self_adj < 0):
206472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(result_sign, '0', 0)
2065353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2066353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Infsign[result_sign]
2067353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2068353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # from here on, the result always goes through the call
2069353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # to _fix at the end of this function.
2070353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = None
2071353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2072353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # crude test to catch cases of extreme overflow/underflow.  If
2073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2074353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2075353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self**other >= 10**(Emax+1), so overflow occurs.  The test
2076353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # for underflow is similar.
2077353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        bound = self._log10_exp_bound() + other.adjusted()
2078353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if (self_adj >= 0) == (other._sign == 0):
2079353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # self > 1 and other +ve, or self < 1 and other -ve
2080353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # possibility of overflow
2081353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if bound >= len(str(context.Emax)):
208272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(result_sign, '1', context.Emax+1)
2083353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2084353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # self > 1 and other -ve, or self < 1 and other +ve
2085353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # possibility of underflow to 0
2086353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            Etiny = context.Etiny()
2087353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if bound >= len(str(-Etiny)):
208872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(result_sign, '1', Etiny-1)
2089353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2090353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # try for an exact result with precision +1
2091353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans is None:
2092353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._power_exact(other, context.prec + 1)
2093353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans is not None and result_sign == 1:
209472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(1, ans._int, ans._exp)
2095353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2096353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # usual case: inexact result, x**y computed directly as exp(y*log(x))
2097353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans is None:
2098353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            p = context.prec
2099353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            x = _WorkRep(self)
2100353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xc, xe = x.int, x.exp
2101353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            y = _WorkRep(other)
2102353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            yc, ye = y.int, y.exp
2103353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if y.sign == 1:
2104353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                yc = -yc
2105353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2106353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # compute correctly rounded result:  start with precision +3,
2107353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # then increase precision until result is unambiguously roundable
2108353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            extra = 3
2109353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while True:
2110353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2111353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if coeff % (5*10**(len(str(coeff))-p-1)):
2112353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
2113353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                extra += 3
2114353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
211572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(result_sign, str(coeff), exp)
2116353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2117353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the specification says that for non-integer other we need to
2118353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # raise Inexact, even when the result is actually exact.  In
2119353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the same way, we need to raise Underflow here if the result
2120353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # is subnormal.  (The call to _fix will take care of raising
2121353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Rounded and Subnormal, as usual.)
2122353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other._isinteger():
2123353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
2124353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # pad with zeros up to length context.prec+1 if necessary
2125353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if len(ans._int) <= context.prec:
2126353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                expdiff = context.prec+1 - len(ans._int)
212772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
212872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                       ans._exp-expdiff)
2129353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans.adjusted() < context.Emin:
2130353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Underflow)
2131353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2132353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # unlike exp, ln and log10, the power function respects the
2133353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # rounding mode; no need to use ROUND_HALF_EVEN here
2134353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2135353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
2136353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2137353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def __rpow__(self, other, context=None):
2138353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Swaps self/other and returns __pow__."""
2139353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other)
2140353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other is NotImplemented:
2141353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return other
2142353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return other.__pow__(self, context=context)
2143353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2144353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def normalize(self, context=None):
2145353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
2146353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2147353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2148353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2149353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2150353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
2151353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._check_nans(context=context)
2152353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans:
2153353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return ans
2154353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2155353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        dup = self._fix(context)
2156353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if dup._isinfinity():
2157353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return dup
2158353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2159353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not dup:
216072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(dup._sign, '0', 0)
2161353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exp_max = [context.Emax, context.Etop()][context._clamp]
2162353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        end = len(dup._int)
21637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exp = dup._exp
216472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        while dup._int[end-1] == '0' and exp < exp_max:
21657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            exp += 1
21667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            end -= 1
216772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(dup._sign, dup._int[:end], exp)
21687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2169bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista    def quantize(self, exp, rounding=None, context=None, watchexp=True):
21707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Quantize self so its exponent is the same as that of exp.
21717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
21727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Similar to self._rescale(exp._exp) but with error checking.
21737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2174bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista        exp = _convert_other(exp, raiseit=True)
2175bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista
2176353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2177353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2178353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if rounding is None:
2179353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rounding = context.rounding
2180353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2181636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or exp._is_special:
2182636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(exp, context)
2183636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
2184636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
21857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2186636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if exp._isinfinity() or self._isinfinity():
2187636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if exp._isinfinity() and self._isinfinity():
21886c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return Decimal(self)  # if both are inf, it is OK
2189636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return context._raise_error(InvalidOperation,
2190636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                                        'quantize with one INF')
2191353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2192bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista        # if we're not watching exponents, do a simple rescale
2193bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista        if not watchexp:
2194bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista            ans = self._rescale(exp._exp, rounding)
2195bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista            # raise Inexact and Rounded where appropriate
2196bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista            if ans._exp > self._exp:
2197bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista                context._raise_error(Rounded)
2198bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista                if ans != self:
2199bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista                    context._raise_error(Inexact)
2200bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista            return ans
2201bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista
2202353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp._exp should be between Etiny and Emax
2203353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (context.Etiny() <= exp._exp <= context.Emax):
2204353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2205353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                   'target exponent out of bounds in quantize')
2206353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2207353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
220872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(self._sign, '0', exp._exp)
2209353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
2210353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2211353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_adjusted = self.adjusted()
2212353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_adjusted > context.Emax:
2213353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2214353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'exponent of quantize result too large for current context')
2215353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_adjusted - exp._exp + 1 > context.prec:
2216353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2217353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'quantize result has too many digits for current context')
2218353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2219353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._rescale(exp._exp, rounding)
2220353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans.adjusted() > context.Emax:
2221353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2222353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'exponent of quantize result too large for current context')
2223353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if len(ans._int) > context.prec:
2224353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2225353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'quantize result has too many digits for current context')
2226353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2227353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # raise appropriate flags
2228353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans._exp > self._exp:
2229353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Rounded)
2230353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans != self:
2231353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Inexact)
2232353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans and ans.adjusted() < context.Emin:
2233353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Subnormal)
2234353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2235353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # call to fix takes care of any necessary folddown
2236353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2237353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
22387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
22397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def same_quantum(self, other):
22401a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self and other have the same exponent; otherwise
22411a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return False.
22427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
22431a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        If either operand is a special value, the following rules are used:
22441a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista           * return True if both operands are infinities
22451a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista           * return True if both operands are NaNs
22461a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista           * otherwise, return False.
22477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
22481a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        other = _convert_other(other, raiseit=True)
2249636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
22501a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista            return (self.is_nan() and other.is_nan() or
22511a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista                    self.is_infinite() and other.is_infinite())
22527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return self._exp == other._exp
22537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2254353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _rescale(self, exp, rounding):
2255353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rescale self so that the exponent is exp, either by padding with zeros
2256353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        or by truncating digits, using the given rounding mode.
2257353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2258353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Specials are returned without change.  This operation is
2259353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        quiet: it raises no flags, and uses no information from the
2260353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.
22617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
22627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exp = exp to scale to (an integer)
2263353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = rounding mode
22647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2265636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
22666c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
22677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
226872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(self._sign, '0', exp)
22697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2270353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp >= exp:
2271353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # pad answer with zeros if necessary
227272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(self._sign,
227372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                        self._int + '0'*(self._exp - exp), exp)
22747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2275353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # too many digits; round and lose data.  If self.adjusted() <
2276353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp-1, replace self by 10**(exp-1) before rounding
2277353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        digits = len(self._int) + self._exp - exp
22787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if digits < 0:
227972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self = _dec_from_triple(self._sign, '1', exp-1)
2280353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            digits = 0
2281353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        this_function = getattr(self, self._pick_rounding_function[rounding])
22822ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        changed = this_function(digits)
22832ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        coeff = self._int[:digits] or '0'
22842ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        if changed == 1:
22852ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            coeff = str(int(coeff)+1)
22862ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        return _dec_from_triple(self._sign, coeff, exp)
22877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2288353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def to_integral_exact(self, rounding=None, context=None):
2289353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds to a nearby integer.
22907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2291353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        If no rounding mode is specified, take the rounding mode from
2292353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        the context.  This method raises the Rounded and Inexact flags
2293353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        when appropriate.
22947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2295353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        See also: to_integral_value, which does exactly the same as
2296353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        this method except that it doesn't raise Inexact or Rounded.
2297353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2298636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
2299636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
2300636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
2301636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
23026c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
23037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._exp >= 0:
23046c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
2305353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
230672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(self._sign, '0', 0)
2307636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
2308636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
2309353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if rounding is None:
2310353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rounding = context.rounding
2311353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._raise_error(Rounded)
2312353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._rescale(0, rounding)
2313353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans != self:
2314353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
23157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
23167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2317353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def to_integral_value(self, rounding=None, context=None):
2318353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds to the nearest integer, without raising inexact, rounded."""
2319353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2320353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2321353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if rounding is None:
2322353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rounding = context.rounding
2323353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
2324353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._check_nans(context=context)
2325353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans:
2326353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return ans
23276c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
2328353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp >= 0:
23296c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
2330353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2331353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._rescale(0, rounding)
23327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2333353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # the method name changed, but we provide also the old one, for compatibility
2334353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    to_integral = to_integral_value
2335353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2336353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def sqrt(self, context=None):
2337353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return the square root of self."""
2338636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
2339636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
2340636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
2341636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
23427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2343636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity() and self._sign == 0:
2344636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Decimal(self)
23457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
23467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
2347353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # exponent = self._exp // 2.  sqrt(-0) = -0
234872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(self._sign, '0', self._exp // 2)
2349353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
23507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2351636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
2352636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
2353636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
23547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign == 1:
23557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
23567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2357353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # At this point self represents a positive number.  Let p be
2358353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the desired precision and express self in the form c*100**e
2359353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # with c a positive real number and e an integer, c and e
2360353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # being chosen so that 100**(p-1) <= c < 100**p.  Then the
2361353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2362353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # <= sqrt(c) < 10**p, so the closest representable Decimal at
2363353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # precision p is n*10**e where n = round_half_even(sqrt(c)),
2364353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the closest integer to sqrt(c) with the even integer chosen
2365353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # in the case of a tie.
2366353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
2367353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # To ensure correct rounding in all cases, we use the
2368353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # following trick: we compute the square root to an extra
2369353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # place (precision p+1 instead of precision p), rounding down.
2370353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Then, if the result is inexact and its last digit is 0 or 5,
2371353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # we increase the last digit to 1 or 6 respectively; if it's
2372353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exact we leave the last digit alone.  Now the final round to
2373353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # p places (or fewer in the case of underflow) will round
2374353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # correctly and raise the appropriate flags.
2375353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2376353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # use an extra digit of precision
2377353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        prec = context.prec+1
2378353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2379353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # write argument in the form c*100**e where e = self._exp//2
2380353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # is the 'ideal' exponent, to be used if the square root is
2381353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exactly representable.  l is the number of 'digits' of c in
2382353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # base 100, so that 100**(l-1) <= c < 100**l.
2383353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op = _WorkRep(self)
2384353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        e = op.exp >> 1
2385353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if op.exp & 1:
2386353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = op.int * 10
2387353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            l = (len(self._int) >> 1) + 1
23887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
2389353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = op.int
2390353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            l = len(self._int)+1 >> 1
2391353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2392353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # rescale so that c has exactly prec base 100 'digits'
2393353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        shift = prec-l
2394353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if shift >= 0:
2395353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c *= 100**shift
2396353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            exact = True
23977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
2398353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c, remainder = divmod(c, 100**-shift)
2399353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            exact = not remainder
2400353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        e -= shift
2401353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2402353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # find n = floor(sqrt(c)) using Newton's method
2403353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        n = 10**prec
2404353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while True:
2405353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            q = c//n
2406353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if n <= q:
24077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                break
2408353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2409353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n = n + q >> 1
2410353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exact = exact and n*n == c
2411353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2412353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if exact:
2413353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # result is exact; rescale to use ideal exponent e
2414353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if shift >= 0:
2415353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # assert n % 10**shift == 0
2416353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n //= 10**shift
2417353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2418353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n *= 10**-shift
2419353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            e += shift
24207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
2421353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # result is not exact; fix last digit as described above
2422353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if n % 5 == 0:
2423353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n += 1
24247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
242572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        ans = _dec_from_triple(0, str(n), e)
24267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2427353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # round, and fit to current context
2428353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context._shallow_copy()
2429353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = context._set_rounding(ROUND_HALF_EVEN)
2430dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger        ans = ans._fix(context)
2431353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.rounding = rounding
24327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2433353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
24347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
24357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def max(self, other, context=None):
24367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the larger value.
24377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2438353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Like max(self, other) except if one is not a number, returns
24397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        NaN (and signals if one is sNaN).  Also rounds.
24407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2441353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
2442636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
24436c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        if context is None:
24446c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            context = getcontext()
24456c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista
2446636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
244759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If one operand is a quiet NaN and the other is number, then the
2448636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            # number is always returned
2449636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            sn = self._isnan()
2450636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            on = other._isnan()
2451636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if sn or on:
2452636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if on == 1 and sn != 2:
24536c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return self._fix_nan(context)
2454636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if sn == 1 and on != 2:
24556c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return other._fix_nan(context)
2456636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return self._check_nans(other, context)
24577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2458d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        c = self.__cmp__(other)
2459d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        if c == 0:
246059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If both operands are finite and equal in numerical value
2461d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger            # then an ordering is applied:
2462d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger            #
246359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If the signs differ then max returns the operand with the
2464d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger            # positive sign and min returns the operand with the negative sign
2465d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger            #
246659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If the signs are the same then the exponent is used to select
2467353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # the result.  This is exactly the ordering used in compare_total.
2468353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = self.compare_total(other)
2469353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2470353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == -1:
24717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = other
2472353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2473353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self
2474636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
247576e60d687dde9d987f39e16f8fe7814daf1f1e26Raymond Hettinger        if context._rounding_decision == ALWAYS_ROUND:
247676e60d687dde9d987f39e16f8fe7814daf1f1e26Raymond Hettinger            return ans._fix(context)
247776e60d687dde9d987f39e16f8fe7814daf1f1e26Raymond Hettinger        return ans
24787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
24797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def min(self, other, context=None):
24807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the smaller value.
24817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
248259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        Like min(self, other) except if one is not a number, returns
24837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        NaN (and signals if one is sNaN).  Also rounds.
24847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2485353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
2486636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
24876c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        if context is None:
24886c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            context = getcontext()
24896c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista
2490636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
249159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If one operand is a quiet NaN and the other is number, then the
2492636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            # number is always returned
2493636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            sn = self._isnan()
2494636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            on = other._isnan()
2495636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if sn or on:
2496636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if on == 1 and sn != 2:
24976c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return self._fix_nan(context)
2498636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if sn == 1 and on != 2:
24996c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return other._fix_nan(context)
2500636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return self._check_nans(other, context)
25017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2502d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        c = self.__cmp__(other)
2503d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        if c == 0:
2504353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = self.compare_total(other)
2505353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2506353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == -1:
2507353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self
2508353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
25097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = other
2510636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
251176e60d687dde9d987f39e16f8fe7814daf1f1e26Raymond Hettinger        if context._rounding_decision == ALWAYS_ROUND:
251276e60d687dde9d987f39e16f8fe7814daf1f1e26Raymond Hettinger            return ans._fix(context)
251376e60d687dde9d987f39e16f8fe7814daf1f1e26Raymond Hettinger        return ans
25147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
25157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _isinteger(self):
25167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns whether self is an integer"""
2517353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
2518353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return False
25197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._exp >= 0:
25207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return True
25217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rest = self._int[self._exp:]
252272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return rest == '0'*len(rest)
25237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
25247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _iseven(self):
2525353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns True if self is even.  Assumes self is an integer."""
2526353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self or self._exp > 0:
2527353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return True
252872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return self._int[-1+self._exp] in '02468'
25297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
25307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def adjusted(self):
25317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return the adjusted exponent of self"""
25327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        try:
25337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return self._exp + len(self._int) - 1
253459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # If NaN or Infinity, self._exp is string
25357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        except TypeError:
25367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return 0
25377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2538353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def canonical(self, context=None):
2539353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the same Decimal object.
2540353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2541353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        As we do not have different encodings for the same number, the
2542353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        received object already is in its canonical form.
2543353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2544353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self
2545353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2546353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_signal(self, other, context=None):
2547353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares self to the other operand numerically.
2548353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2549353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        It's pretty much like compare(), but all NaNs signal, with signaling
2550353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        NaNs taking precedence over quiet NaNs.
2551353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2552353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2553353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2554353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2555353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_is_nan = self._isnan()
2556353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other_is_nan = other._isnan()
2557353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_is_nan == 2:
2558353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation, 'sNaN',
2559353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, self)
2560353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other_is_nan == 2:
2561353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation, 'sNaN',
2562353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, other)
2563353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_is_nan:
2564353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2565353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, self)
2566353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other_is_nan:
2567353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2568353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, other)
2569353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self.compare(other, context=context)
2570353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2571353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_total(self, other):
2572353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares self to other using the abstract representations.
2573353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2574353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        This is not like the standard compare, which use their numerical
2575353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        value. Note that a total ordering is defined for all possible abstract
2576353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        representations.
2577353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2578353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if one is negative and the other is positive, it's easy
2579353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign and not other._sign:
2580353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_n1
2581353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self._sign and other._sign:
2582353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_p1
2583353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        sign = self._sign
2584353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2585353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # let's handle both NaN types
2586353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_nan = self._isnan()
2587353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other_nan = other._isnan()
2588353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_nan or other_nan:
2589353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self_nan == other_nan:
2590353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self._int < other._int:
2591353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if sign:
2592353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return Dec_p1
2593353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    else:
2594353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return Dec_n1
2595353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self._int > other._int:
2596353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if sign:
2597353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return Dec_n1
2598353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    else:
2599353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return Dec_p1
2600353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_0
2601353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2602353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sign:
2603353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_nan == 1:
2604353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_n1
2605353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other_nan == 1:
2606353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_p1
2607353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_nan == 2:
2608353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_n1
2609353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other_nan == 2:
2610353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_p1
2611353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2612353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_nan == 1:
2613353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_p1
2614353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other_nan == 1:
2615353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_n1
2616353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_nan == 2:
2617353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_p1
2618353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other_nan == 2:
2619353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_n1
2620353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2621353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self < other:
2622353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_n1
2623353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self > other:
2624353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_p1
2625353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2626353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp < other._exp:
2627353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sign:
2628353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_p1
2629353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2630353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_n1
2631353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp > other._exp:
2632353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sign:
2633353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_n1
2634353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2635353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_p1
2636353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Dec_0
2637353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2638353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2639353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_total_mag(self, other):
2640353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares self to other using abstract repr., ignoring sign.
2641353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2642353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Like compare_total, but with operand's sign ignored and assumed to be 0.
2643353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2644353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        s = self.copy_abs()
2645353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        o = other.copy_abs()
2646353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return s.compare_total(o)
2647353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2648353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_abs(self):
2649353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy with the sign set to 0. """
265072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(0, self._int, self._exp, self._is_special)
2651353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2652353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_negate(self):
2653353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy with the sign inverted."""
2654353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign:
265572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(0, self._int, self._exp, self._is_special)
2656353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
265772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(1, self._int, self._exp, self._is_special)
2658353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2659353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_sign(self, other):
2660353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns self with the sign of other."""
266172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(other._sign, self._int,
266272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                self._exp, self._is_special)
2663353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2664353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def exp(self, context=None):
2665353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns e ** self."""
2666353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2667353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2668353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2669353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2670353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp(NaN) = NaN
2671353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
2672353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
2673353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
2674353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2675353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp(-Infinity) = 0
2676353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == -1:
2677353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_0
2678353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2679353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp(0) = 1
2680353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2681353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_p1
2682353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2683353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp(Infinity) = Infinity
2684353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
2685353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Decimal(self)
2686353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2687353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the result is now guaranteed to be inexact (the true
2688353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # mathematical result is transcendental). There's no need to
2689353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # raise Rounded and Inexact here---they'll always be raised as
2690353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # a result of the call to _fix.
2691353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        p = context.prec
2692353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        adj = self.adjusted()
2693353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2694353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # we only need to do any computation for quite a small range
2695353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # of adjusted exponents---for example, -29 <= adj <= 10 for
2696353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the default context.  For smaller exponent the result is
2697353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # indistinguishable from 1 at the given precision, while for
2698353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # larger exponent the result either overflows or underflows.
2699353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2700353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # overflow
270172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(0, '1', context.Emax+1)
2702353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2703353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # underflow to 0
270472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(0, '1', context.Etiny()-1)
2705353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif self._sign == 0 and adj < -p:
2706353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # p+1 digits; final round will raise correct flags
270772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
2708353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif self._sign == 1 and adj < -p-1:
2709353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # p+1 digits; final round will raise correct flags
271072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(0, '9'*(p+1), -p-1)
2711353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # general case
2712353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2713353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            op = _WorkRep(self)
2714353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c, e = op.int, op.exp
2715353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if op.sign == 1:
2716353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                c = -c
2717353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2718353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # compute correctly rounded result: increase precision by
2719353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # 3 digits at a time until we get an unambiguously
2720353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # roundable result
2721353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            extra = 3
2722353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while True:
2723353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                coeff, exp = _dexp(c, e, p+extra)
2724353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if coeff % (5*10**(len(str(coeff))-p-1)):
2725353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
2726353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                extra += 3
2727353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
272872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(0, str(coeff), exp)
2729353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2730353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # at this stage, ans should round correctly with *any*
2731353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # rounding mode, not just with ROUND_HALF_EVEN
2732353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context._shallow_copy()
2733353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = context._set_rounding(ROUND_HALF_EVEN)
2734353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2735353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.rounding = rounding
2736353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2737353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
2738353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2739353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_canonical(self):
27401a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is canonical; otherwise return False.
27411a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista
27421a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        Currently, the encoding of a Decimal instance is always
27431a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        canonical, so this method returns True for any Decimal.
27441a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """
27451a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return True
2746353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2747353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_finite(self):
27481a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is finite; otherwise return False.
2749353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
27501a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        A Decimal instance is considered finite if it is neither
27511a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        infinite nor a NaN.
2752353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
27531a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return not self._is_special
2754353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2755353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_infinite(self):
27561a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is infinite; otherwise return False."""
27571a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self._exp == 'F'
2758353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2759353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_nan(self):
27601a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is a qNaN or sNaN; otherwise return False."""
27611a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self._exp in ('n', 'N')
2762353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2763353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_normal(self, context=None):
27641a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is a normal number; otherwise return False."""
27651a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        if self._is_special or not self:
27661a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista            return False
2767353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2768353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
27691a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return context.Emin <= self.adjusted() <= context.Emax
2770353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2771353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_qnan(self):
27721a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is a quiet NaN; otherwise return False."""
27731a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self._exp == 'n'
2774353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2775353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_signed(self):
27761a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is negative; otherwise return False."""
27771a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self._sign == 1
2778353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2779353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_snan(self):
27801a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is a signaling NaN; otherwise return False."""
27811a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self._exp == 'N'
2782353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2783353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_subnormal(self, context=None):
27841a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is subnormal; otherwise return False."""
27851a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        if self._is_special or not self:
27861a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista            return False
2787353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2788353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
27891a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self.adjusted() < context.Emin
2790353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2791353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_zero(self):
27921a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is a zero; otherwise return False."""
279372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return not self._is_special and self._int == '0'
2794353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2795353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _ln_exp_bound(self):
2796353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compute a lower bound for the adjusted exponent of self.ln().
2797353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        In other words, compute r such that self.ln() >= 10**r.  Assumes
2798353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        that self is finite and positive and that self != 1.
2799353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2800353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2801353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2802353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        adj = self._exp + len(self._int) - 1
2803353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj >= 1:
2804353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2805353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(str(adj*23//10)) - 1
2806353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj <= -2:
2807353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # argument <= 0.1
2808353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(str((-1-adj)*23//10)) - 1
2809353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op = _WorkRep(self)
2810353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c, e = op.int, op.exp
2811353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj == 0:
2812353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # 1 < self < 10
2813353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            num = str(c-10**-e)
2814353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            den = str(c)
2815353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(num) - len(den) - (num < den)
2816353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # adj == -1, 0.1 <= self < 1
2817353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return e + len(str(10**-e - c)) - 1
2818353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2819353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2820353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def ln(self, context=None):
2821353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the natural (base e) logarithm of self."""
2822353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2823353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2824353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2825353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2826353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(NaN) = NaN
2827353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
2828353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
2829353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
2830353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2831353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(0.0) == -Infinity
2832353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2833353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return negInf
2834353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2835353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(Infinity) = Infinity
2836353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
2837353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Inf
2838353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2839353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(1.0) == 0.0
2840353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self == Dec_p1:
2841353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_0
2842353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2843353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(negative) raises InvalidOperation
2844353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign == 1:
2845353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2846353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'ln of a negative value')
2847353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2848353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # result is irrational, so necessarily inexact
2849353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op = _WorkRep(self)
2850353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c, e = op.int, op.exp
2851353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        p = context.prec
2852353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2853353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # correctly rounded result: repeatedly increase precision by 3
2854353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # until we get an unambiguously roundable result
2855353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        places = p - self._ln_exp_bound() + 2 # at least p+3 places
2856353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while True:
2857353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            coeff = _dlog(c, e, places)
2858353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # assert len(str(abs(coeff)))-p >= 1
2859353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2860353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                break
2861353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            places += 3
286272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
2863353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2864353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context._shallow_copy()
2865353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = context._set_rounding(ROUND_HALF_EVEN)
2866353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2867353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.rounding = rounding
2868353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
2869353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2870353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _log10_exp_bound(self):
2871353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compute a lower bound for the adjusted exponent of self.log10().
2872353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        In other words, find r such that self.log10() >= 10**r.
2873353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Assumes that self is finite and positive and that self != 1.
2874353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2875353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2876353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # For x >= 10 or x < 0.1 we only need a bound on the integer
2877353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # part of log10(self), and this comes directly from the
2878353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exponent of x.  For 0.1 <= x <= 10 we use the inequalities
2879353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2880353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (1-1/x)/2.31 > 0.  If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2881353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2882353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        adj = self._exp + len(self._int) - 1
2883353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj >= 1:
2884353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # self >= 10
2885353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(str(adj))-1
2886353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj <= -2:
2887353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # self < 0.1
2888353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(str(-1-adj))-1
2889353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op = _WorkRep(self)
2890353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c, e = op.int, op.exp
2891353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj == 0:
2892353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # 1 < self < 10
2893353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            num = str(c-10**-e)
2894353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            den = str(231*c)
2895353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(num) - len(den) - (num < den) + 2
2896353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # adj == -1, 0.1 <= self < 1
2897353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        num = str(10**-e-c)
2898353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return len(num) + e - (num < "231") - 1
2899353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2900353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def log10(self, context=None):
2901353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the base 10 logarithm of self."""
2902353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2903353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2904353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2905353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2906353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(NaN) = NaN
2907353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
2908353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
2909353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
2910353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2911353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(0.0) == -Infinity
2912353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2913353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return negInf
2914353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2915353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(Infinity) = Infinity
2916353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
2917353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Inf
2918353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2919353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(negative or -Infinity) raises InvalidOperation
2920353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign == 1:
2921353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2922353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'log10 of a negative value')
2923353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2924353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(10**n) = n
292572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
2926353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # answer may need rounding
2927353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal(self._exp + len(self._int) - 1)
2928353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2929353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # result is irrational, so necessarily inexact
2930353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            op = _WorkRep(self)
2931353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c, e = op.int, op.exp
2932353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            p = context.prec
2933353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2934353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # correctly rounded result: repeatedly increase precision
2935353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # until result is unambiguously roundable
2936353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            places = p-self._log10_exp_bound()+2
2937353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while True:
2938353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                coeff = _dlog10(c, e, places)
2939353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # assert len(str(abs(coeff)))-p >= 1
2940353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2941353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
2942353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                places += 3
294372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
2944353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2945353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context._shallow_copy()
2946353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = context._set_rounding(ROUND_HALF_EVEN)
2947353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2948353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.rounding = rounding
2949353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
2950353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2951353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logb(self, context=None):
2952353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """ Returns the exponent of the magnitude of self's MSD.
2953353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2954353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result is the integer which is the exponent of the magnitude
2955353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        of the most significant digit of self (as though it were truncated
2956353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        to a single digit while maintaining the value of that digit and
2957353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        without limiting the resulting exponent).
2958353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2959353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # logb(NaN) = NaN
2960353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
2961353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
2962353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
2963353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2964353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2965353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2966353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2967353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # logb(+/-Inf) = +Inf
2968353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
2969353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Inf
2970353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2971353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # logb(0) = -Inf, DivisionByZero
2972353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2973cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return context._raise_error(DivisionByZero, 'logb(0)', 1)
2974353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2975353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # otherwise, simply return the adjusted exponent of self, as a
2976353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Decimal.  Note that no attempt is made to fit the result
2977353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # into the current context.
2978353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal(self.adjusted())
2979353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2980353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _islogical(self):
2981353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return True if self is a logical operand.
2982353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2983353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        For being logical, it must be a finite numbers with a sign of 0,
2984353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        an exponent of 0, and a coefficient whose digits must all be
2985353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        either 0 or 1.
2986353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2987353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign != 0 or self._exp != 0:
2988353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return False
2989353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        for dig in self._int:
299072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            if dig not in '01':
2991353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return False
2992353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return True
2993353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2994353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _fill_logical(self, context, opa, opb):
2995353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        dif = context.prec - len(opa)
2996353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if dif > 0:
299772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            opa = '0'*dif + opa
2998353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif dif < 0:
2999353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            opa = opa[-context.prec:]
3000353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        dif = context.prec - len(opb)
3001353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if dif > 0:
300272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            opb = '0'*dif + opb
3003353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif dif < 0:
3004353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            opb = opb[-context.prec:]
3005353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return opa, opb
3006353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3007353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_and(self, other, context=None):
3008353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies an 'and' operation between self and other's digits."""
3009353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3010353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3011353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self._islogical() or not other._islogical():
3012353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3013353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3014353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # fill to context.prec
3015353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        (opa, opb) = self._fill_logical(context, self._int, other._int)
3016353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3017353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # make the operation, and clean starting zeroes
301872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
301972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3020353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3021353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_invert(self, context=None):
3022353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Invert all its digits."""
3023353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3024353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
302572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
302672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                context)
3027353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3028353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_or(self, other, context=None):
3029353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies an 'or' operation between self and other's digits."""
3030353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3031353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3032353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self._islogical() or not other._islogical():
3033353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3034353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3035353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # fill to context.prec
3036353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        (opa, opb) = self._fill_logical(context, self._int, other._int)
3037353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3038353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # make the operation, and clean starting zeroes
303972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
304072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3041353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3042353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_xor(self, other, context=None):
3043353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies an 'xor' 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
305372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
305472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3055353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3056353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def max_mag(self, other, context=None):
3057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values numerically with their sign ignored."""
3058353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
3059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
30606c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        if context is None:
30616c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            context = getcontext()
30626c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista
3063353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special or other._is_special:
3064353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # If one operand is a quiet NaN and the other is number, then the
3065353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # number is always returned
3066353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sn = self._isnan()
3067353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            on = other._isnan()
3068353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sn or on:
3069353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if on == 1 and sn != 2:
30706c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return self._fix_nan(context)
3071353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if sn == 1 and on != 2:
30726c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return other._fix_nan(context)
3073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self._check_nans(other, context)
3074353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3075353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c = self.copy_abs().__cmp__(other.copy_abs())
3076353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == 0:
3077353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = self.compare_total(other)
3078353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3079353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == -1:
3080353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = other
3081353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
3082353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self
3083353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3084353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context._rounding_decision == ALWAYS_ROUND:
3085353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
3086353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
3087353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3088353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def min_mag(self, other, context=None):
3089353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values numerically with their sign ignored."""
3090353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
3091353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
30926c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        if context is None:
30936c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            context = getcontext()
30946c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista
3095353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special or other._is_special:
3096353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # If one operand is a quiet NaN and the other is number, then the
3097353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # number is always returned
3098353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sn = self._isnan()
3099353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            on = other._isnan()
3100353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sn or on:
3101353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if on == 1 and sn != 2:
31026c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return self._fix_nan(context)
3103353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if sn == 1 and on != 2:
31046c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return other._fix_nan(context)
3105353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self._check_nans(other, context)
3106353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3107353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c = self.copy_abs().__cmp__(other.copy_abs())
3108353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == 0:
3109353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = self.compare_total(other)
3110353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3111353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == -1:
3112353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self
3113353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
3114353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = other
3115353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3116353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context._rounding_decision == ALWAYS_ROUND:
3117353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
3118353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
3119353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3120353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_minus(self, context=None):
3121353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the largest representable number smaller than itself."""
3122353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3123353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3124353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3125353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
3126353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3127353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3128353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3129353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == -1:
3130353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return negInf
3131353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
313272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(0, '9'*context.prec, context.Etop())
3133353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3134353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context.copy()
3135353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._set_rounding(ROUND_FLOOR)
3136353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._ignore_all_flags()
3137353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        new_self = self._fix(context)
3138353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if new_self != self:
3139353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return new_self
314072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
314172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                            context)
3142353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3143353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_plus(self, context=None):
3144353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the smallest representable number larger than itself."""
3145353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3146353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3147353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3148353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
3149353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3150353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3151353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3152353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
3153353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Inf
3154353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == -1:
315572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(1, '9'*context.prec, context.Etop())
3156353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3157353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context.copy()
3158353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._set_rounding(ROUND_CEILING)
3159353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._ignore_all_flags()
3160353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        new_self = self._fix(context)
3161353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if new_self != self:
3162353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return new_self
316372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
316472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                            context)
3165353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3166353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_toward(self, other, context=None):
3167353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the number closest to self, in the direction towards other.
3168353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3169353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result is the closest representable number to self
3170353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        (excluding self) that is in the direction towards other,
3171353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        unless both have the same value.  If the two operands are
3172353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        numerically equal, then the result is a copy of self with the
3173353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        sign set to be the same as the sign of other.
3174353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3175353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
3176353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3177353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3178353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3179353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3180353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
3181353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3182353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3183353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3184353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        comparison = self.__cmp__(other)
3185353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if comparison == 0:
318672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return self.copy_sign(other)
3187353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3188353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if comparison == -1:
3189353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.next_plus(context)
3190353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else: # comparison == 1
3191353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.next_minus(context)
3192353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3193353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # decide which flags to raise using value of ans
3194353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans._isinfinity():
3195353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Overflow,
3196353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                 'Infinite result from next_toward',
3197353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                 ans._sign)
3198353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Rounded)
3199353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
3200353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif ans.adjusted() < context.Emin:
3201353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Underflow)
3202353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Subnormal)
3203353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Rounded)
3204353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
3205353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # if precision == 1 then we don't raise Clamped for a
3206353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # result 0E-Etiny.
3207353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if not ans:
3208353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Clamped)
3209353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3210353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
3211353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3212353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def number_class(self, context=None):
3213353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns an indication of the class of self.
3214353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3215353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The class is one of the following strings:
3216353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -sNaN
3217353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -NaN
3218353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Infinity
3219353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Normal
3220353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Subnormal
3221353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Zero
3222353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Zero
3223353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Subnormal
3224353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Normal
3225353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Infinity
3226353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3227353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self.is_snan():
3228353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "sNaN"
3229353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self.is_qnan():
3230353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "NaN"
3231353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        inf = self._isinfinity()
3232353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if inf == 1:
3233353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "+Infinity"
3234353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if inf == -1:
3235353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "-Infinity"
3236353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self.is_zero():
3237353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self._sign:
3238353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return "-Zero"
3239353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
3240353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return "+Zero"
3241353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3242353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3243353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self.is_subnormal(context=context):
3244353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self._sign:
3245353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return "-Subnormal"
3246353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
3247353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return "+Subnormal"
3248353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # just a normal, regular, boring number, :)
3249353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign:
3250353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "-Normal"
3251353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
3252353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "+Normal"
3253353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3254353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def radix(self):
3255353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Just returns 10, as this is Decimal, :)"""
3256353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal(10)
3257353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3258353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def rotate(self, other, context=None):
3259353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a rotated copy of self, value-of-other times."""
3260353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3261353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3262353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3263353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
3264353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3265353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3266353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3267353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._exp != 0:
3268353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3269353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (-context.prec <= int(other) <= context.prec):
3270353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3271353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3272353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
32736c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
3274353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3275353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # get values, pad if necessary
3276353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        torot = int(other)
3277353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotdig = self._int
3278353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        topad = context.prec - len(rotdig)
3279353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if topad:
328072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            rotdig = '0'*topad + rotdig
3281353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3282353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # let's rotate!
3283353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotated = rotdig[torot:] + rotdig[:torot]
328472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(self._sign,
328572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                rotated.lstrip('0') or '0', self._exp)
3286353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3287353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def scaleb (self, other, context=None):
3288353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns self operand after adding the second value to its exp."""
3289353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3290353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3291353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3292353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
3293353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3294353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3295353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3296353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._exp != 0:
3297353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3298353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        liminf = -2 * (context.Emax + context.prec)
3299353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        limsup =  2 * (context.Emax + context.prec)
3300353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (liminf <= int(other) <= limsup):
3301353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3302353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3303353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
33046c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
3305353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
330672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
3307353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        d = d._fix(context)
3308353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return d
3309353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3310353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def shift(self, other, context=None):
3311353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a shifted copy of self, value-of-other times."""
3312353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3313353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3314353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3315353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
3316353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3317353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3318353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3319353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._exp != 0:
3320353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3321353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (-context.prec <= int(other) <= context.prec):
3322353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3323353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3324353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
33256c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
3326353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3327353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # get values, pad if necessary
3328353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        torot = int(other)
3329353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not torot:
33306c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
3331353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotdig = self._int
3332353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        topad = context.prec - len(rotdig)
3333353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if topad:
333472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            rotdig = '0'*topad + rotdig
3335353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3336353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # let's shift!
3337353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if torot < 0:
3338353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rotated = rotdig[:torot]
3339353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
334072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            rotated = rotdig + '0'*torot
3341353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rotated = rotated[-context.prec:]
3342353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
334372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(self._sign,
334472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                    rotated.lstrip('0') or '0', self._exp)
3345353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
334659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # Support for pickling, copy, and deepcopy
33477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __reduce__(self):
33487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return (self.__class__, (str(self),))
33497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
33507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __copy__(self):
33517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if type(self) == Decimal:
3352cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis            return self     # I'm immutable; therefore I am my own clone
33537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return self.__class__(str(self))
33547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
33557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __deepcopy__(self, memo):
33567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if type(self) == Decimal:
3357cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis            return self     # My components are also immutable
33587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return self.__class__(str(self))
33597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
336072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batistadef _dec_from_triple(sign, coefficient, exponent, special=False):
336172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    """Create a decimal instance directly, without any validation,
336272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    normalization (e.g. removal of leading zeros) or argument
336372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    conversion.
336472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista
336572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    This function is for *internal use only*.
336672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    """
336772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista
336872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    self = object.__new__(Decimal)
336972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    self._sign = sign
337072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    self._int = coefficient
337172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    self._exp = exponent
337272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    self._is_special = special
337372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista
337472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    return self
337572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista
337659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Context class #######################################################
3377cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
33787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3379cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis# get rounding method function:
338059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batistarounding_functions = [name for name in Decimal.__dict__.keys()
338159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                                    if name.startswith('_round_')]
33827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerfor name in rounding_functions:
338359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
33847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    globalname = name[1:].upper()
33857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    val = globals()[globalname]
33867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Decimal._pick_rounding_function[val] = name
33877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
33889ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettingerdel name, val, globalname, rounding_functions
33897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3390ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlanclass _ContextManager(object):
33918b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """Context manager class to support localcontext().
33921a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum
3393ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlan      Sets a copy of the supplied context in __enter__() and restores
33948b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan      the previous decimal context in __exit__()
33958b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """
33961a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum    def __init__(self, new_context):
3397ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlan        self.new_context = new_context.copy()
33981a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum    def __enter__(self):
33991a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum        self.saved_context = getcontext()
34001a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum        setcontext(self.new_context)
34011a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum        return self.new_context
34021a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum    def __exit__(self, t, v, tb):
34031a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum        setcontext(self.saved_context)
34041a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum
34057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Context(object):
34067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Contains the context for a Decimal instance.
34077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
34087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Contains:
34097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    prec - precision (for use in rounding, division, square roots..)
341059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    rounding - rounding type (how you round)
34117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
3412bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger    traps - If traps[exception] = 1, then the exception is
34137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    raised when it is caused.  Otherwise, a value is
34147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    substituted in.
34157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    flags  - When an exception is caused, flags[exception] is incremented.
34167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger             (Whether or not the trap_enabler is set)
34177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger             Should be reset by user of Decimal instance.
34180ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettinger    Emin -   Minimum exponent
34190ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettinger    Emax -   Maximum exponent
34207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    capitals -      If 1, 1*10^1 is printed as 1E+1.
34217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    If 0, printed as 1e1
3422e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger    _clamp - If 1, change exponents if too high (Default 0)
34237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
34249ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger
34257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __init__(self, prec=None, rounding=None,
3426abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger                 traps=None, flags=None,
34277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                 _rounding_decision=None,
34280ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettinger                 Emin=None, Emax=None,
3429e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger                 capitals=None, _clamp=0,
3430abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger                 _ignored_flags=None):
3431abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger        if flags is None:
3432abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger            flags = []
3433abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger        if _ignored_flags is None:
3434abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger            _ignored_flags = []
3435bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        if not isinstance(flags, dict):
3436fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger            flags = dict([(s,s in flags) for s in _signals])
3437b91af521fddac47b14c57cd9ba736775334e6379Raymond Hettinger            del s
3438bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        if traps is not None and not isinstance(traps, dict):
3439fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger            traps = dict([(s,s in traps) for s in _signals])
3440b91af521fddac47b14c57cd9ba736775334e6379Raymond Hettinger            del s
34417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        for name, val in locals().items():
34427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if val is None:
3443eb2608415ee4eb8aaea746f6a313937e264d0cdaRaymond Hettinger                setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
34447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            else:
34457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                setattr(self, name, val)
34467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        del self.self
34477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3448b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger    def __repr__(self):
3449bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        """Show the current context."""
3450b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger        s = []
345159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
345259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
345359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                 % vars(self))
345459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        names = [f.__name__ for f, v in self.flags.items() if v]
345559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        s.append('flags=[' + ', '.join(names) + ']')
345659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        names = [t.__name__ for t, v in self.traps.items() if v]
345759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        s.append('traps=[' + ', '.join(names) + ']')
3458b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger        return ', '.join(s) + ')'
3459b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger
3460d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger    def clear_flags(self):
3461d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger        """Reset all flags to zero"""
3462d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger        for flag in self.flags:
3463b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger            self.flags[flag] = 0
3464d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger
34659fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger    def _shallow_copy(self):
34669fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        """Returns a shallow copy from self."""
3467bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        nc = Context(self.prec, self.rounding, self.traps, self.flags,
34687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                         self._rounding_decision, self.Emin, self.Emax,
34697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                         self.capitals, self._clamp, self._ignored_flags)
34707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return nc
34719fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger
34729fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger    def copy(self):
34739fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        """Returns a deep copy from self."""
347459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        nc = Context(self.prec, self.rounding, self.traps.copy(),
347559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                self.flags.copy(), self._rounding_decision, self.Emin,
347659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                self.Emax, self.capitals, self._clamp, self._ignored_flags)
34779fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        return nc
34789ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger    __copy__ = copy
34797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
34805aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger    def _raise_error(self, condition, explanation = None, *args):
34817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Handles an error
34827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
34837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the flag is in _ignored_flags, returns the default response.
34847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Otherwise, it increments the flag, then, if the corresponding
34857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        trap_enabler is set, it reaises the exception.  Otherwise, it returns
34867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        the default value after incrementing the flag.
34877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
34885aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger        error = _condition_map.get(condition, condition)
34897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if error in self._ignored_flags:
349059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # Don't touch the flag
34917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return error().handle(self, *args)
34927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
34937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self.flags[error] += 1
3494bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        if not self.traps[error]:
349559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # The errors define how to handle themselves.
34965aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger            return condition().handle(self, *args)
34977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
34987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Errors should only be risked on copies of the context
349959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # self._ignored_flags = []
35007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        raise error, explanation
35017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _ignore_all_flags(self):
35037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Ignore all flags, if they are raised"""
3504fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger        return self._ignore_flags(*_signals)
35057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _ignore_flags(self, *flags):
35077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Ignore the flags, if they are raised"""
35087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Do not mutate-- This way, copies of a context leave the original
35097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # alone.
35107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self._ignored_flags = (self._ignored_flags + list(flags))
35117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return list(flags)
35127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _regard_flags(self, *flags):
35147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Stop ignoring the flags, if they are raised"""
35157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if flags and isinstance(flags[0], (tuple,list)):
35167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            flags = flags[0]
35177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        for flag in flags:
35187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self._ignored_flags.remove(flag)
35197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35205aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger    def __hash__(self):
35215aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger        """A Context cannot be hashed."""
35225aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger        # We inherit object.__hash__, so we must deny this explicitly
352359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        raise TypeError("Cannot hash a Context.")
35245aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger
35257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def Etiny(self):
35267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns Etiny (= Emin - prec + 1)"""
35277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return int(self.Emin - self.prec + 1)
35287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def Etop(self):
3530e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger        """Returns maximum exponent (= Emax - prec + 1)"""
35317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return int(self.Emax - self.prec + 1)
35327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _set_rounding_decision(self, type):
35347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Sets the rounding decision.
35357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Sets the rounding decision, and returns the current (previous)
35377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding decision.  Often used like:
35387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35399fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        context = context._shallow_copy()
35407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # That so you don't change the calling context
35417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # if an error occurs in the middle (say DivisionImpossible is raised).
35427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding = context._set_rounding_decision(NEVER_ROUND)
35447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        instance = instance / Decimal(2)
35457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        context._set_rounding_decision(rounding)
35467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        This will make it not round for that operation.
35487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
3549cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
35507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding = self._rounding_decision
35517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self._rounding_decision = type
35527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return rounding
35537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _set_rounding(self, type):
35557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Sets the rounding type.
35567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Sets the rounding type, and returns the current (previous)
35587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding type.  Often used like:
35597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        context = context.copy()
35617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # so you don't change the calling context
35627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # if an error occurs in the middle.
35637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding = context._set_rounding(ROUND_UP)
35647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        val = self.__sub__(other, context=context)
35657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        context._set_rounding(rounding)
35667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        This will make it round up for that operation.
35687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
35697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding = self.rounding
35707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self.rounding= type
35717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return rounding
35727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3573fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger    def create_decimal(self, num='0'):
35747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Creates a new Decimal instance but using self as context."""
35757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        d = Decimal(num, context=self)
3576353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if d._isnan() and len(d._int) > self.prec - self._clamp:
3577353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._raise_error(ConversionSyntax,
3578353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                     "diagnostic info too long in NaN")
3579dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger        return d._fix(self)
35807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
358159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # Methods
35827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def abs(self, a):
35837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the absolute value of the operand.
35847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the operand is negative, the result is the same as using the minus
358659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operation on the operand.  Otherwise, the result is the same as using
35877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        the plus operation on the operand.
35887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35899ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.abs(Decimal('2.1'))
35907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.1")
35919ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.abs(Decimal('-100'))
35927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("100")
35939ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.abs(Decimal('101.5'))
35947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("101.5")
35959ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.abs(Decimal('-101.5'))
35967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("101.5")
35977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
35987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__abs__(context=self)
35997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def add(self, a, b):
36017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return the sum of the two operands.
36027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36039ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
36047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("19.00")
36059ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
36067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.02E+4")
36077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
36087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__add__(b, context=self)
36097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _apply(self, a):
3611dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger        return str(a._fix(self))
36127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3613353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def canonical(self, a):
3614353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the same Decimal object.
3615353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3616353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        As we do not have different encodings for the same number, the
3617353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        received object already is in its canonical form.
3618353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3619353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.canonical(Decimal('2.50'))
3620353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.50")
3621353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3622353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.canonical(context=self)
3623353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
36247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def compare(self, a, b):
36257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Compares values numerically.
36267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the signs of the operands differ, a value representing each operand
36287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        ('-1' if the operand is less than zero, '0' if the operand is zero or
36297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        negative zero, or '1' if the operand is greater than zero) is used in
36307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        place of that operand for the comparison instead of the actual
36317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        operand.
36327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The comparison is then effected by subtracting the second operand from
36347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        the first and then returning a value according to the result of the
36357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        subtraction: '-1' if the result is less than zero, '0' if the result is
36367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        zero or negative zero, or '1' if the result is greater than zero.
36377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36389ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
36397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1")
36409ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
36417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0")
36429ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
36437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0")
36449ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
36457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
36469ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
36477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
36489ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
36497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1")
36507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
36517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.compare(b, context=self)
36527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3653353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_signal(self, a, b):
3654353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values of the two operands numerically.
3655353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3656353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        It's pretty much like compare(), but all NaNs signal, with signaling
3657353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        NaNs taking precedence over quiet NaNs.
3658353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3659353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext
3660353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3661353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1")
3662353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3663353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3664353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.flags[InvalidOperation] = 0
3665353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> print c.flags[InvalidOperation]
3666353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        0
3667353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3668353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("NaN")
3669353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> print c.flags[InvalidOperation]
3670353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        1
3671353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.flags[InvalidOperation] = 0
3672353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> print c.flags[InvalidOperation]
3673353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        0
3674353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3675353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("NaN")
3676353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> print c.flags[InvalidOperation]
3677353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        1
3678353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3679353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.compare_signal(b, context=self)
3680353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3681353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_total(self, a, b):
3682353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares two operands using their abstract representation.
3683353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3684353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        This is not like the standard compare, which use their numerical
3685353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        value. Note that a total ordering is defined for all possible abstract
3686353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        representations.
3687353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3688353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3689353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1")
3690353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('-127'),  Decimal('12'))
3691353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1")
3692353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3693353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1")
3694353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3695353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3696353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('12.300'))
3697353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3698353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('NaN'))
3699353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1")
3700353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3701353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.compare_total(b)
3702353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3703353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_total_mag(self, a, b):
3704353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares two operands using their abstract representation ignoring sign.
3705353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3706353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Like compare_total, but with operand's sign ignored and assumed to be 0.
3707353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3708353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.compare_total_mag(b)
3709353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3710353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_abs(self, a):
3711353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy of the operand with the sign set to 0.
3712353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3713353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_abs(Decimal('2.1'))
3714353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.1")
3715353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_abs(Decimal('-100'))
3716353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("100")
3717353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3718353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.copy_abs()
3719353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3720353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_decimal(self, a):
3721353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy of the decimal objet.
3722353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3723353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3724353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.1")
3725353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3726353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.00")
3727353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
37286c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        return Decimal(a)
3729353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3730353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_negate(self, a):
3731353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy of the operand with the sign inverted.
3732353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3733353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_negate(Decimal('101.5'))
3734353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-101.5")
3735353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3736353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("101.5")
3737353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3738353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.copy_negate()
3739353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3740353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_sign(self, a, b):
3741353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Copies the second operand's sign to the first one.
3742353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3743353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        In detail, it returns a copy of the first operand with the sign
3744353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        equal to the sign of the second operand.
3745353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3746353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3747353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.50")
3748353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3749353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.50")
3750353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3751353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.50")
3752353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3753353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.50")
3754353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3755353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.copy_sign(b)
3756353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
37577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def divide(self, a, b):
37587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Decimal division in a specified context.
37597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37609ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
37617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.333333333")
37629ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
37637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.666666667")
37649ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
37657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.5")
37669ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
37677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.1")
37689ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
37697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
37709ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
37717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("4.00")
37729ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
37737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.20")
37749ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
37757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("10")
37769ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
37777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1000")
37789ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
37797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.20E+6")
37807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
37817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__div__(b, context=self)
37827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def divide_int(self, a, b):
37847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Divides two numbers and returns the integer part of the result.
37857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37869ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
37877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0")
37889ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
37897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3")
37909ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
37917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3")
37927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
37937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__floordiv__(b, context=self)
37947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def divmod(self, a, b):
37967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__divmod__(b, context=self)
37977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3798353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def exp(self, a):
3799353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns e ** a.
3800353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3801353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
3802353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
3803353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
3804353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('-Infinity'))
3805353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3806353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('-1'))
3807353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0.367879441")
3808353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('0'))
3809353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3810353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('1'))
3811353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.71828183")
3812353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('0.693147181'))
3813353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.00000000")
3814353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('+Infinity'))
3815353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("Infinity")
3816353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3817353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.exp(context=self)
3818353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3819353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def fma(self, a, b, c):
3820353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a multiplied by b, plus c.
3821353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3822353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The first two operands are multiplied together, using multiply,
3823353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        the third operand is then added to the result of that
3824353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        multiplication, using add, all with only one final rounding.
3825353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3826353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3827353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("22")
3828353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3829353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-8")
3830353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3831353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.38435736E+12")
3832353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3833353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.fma(b, c, context=self)
3834353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3835353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_canonical(self, a):
38361a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is canonical; otherwise return False.
38371a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista
38381a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        Currently, the encoding of a Decimal instance is always
38391a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        canonical, so this method returns True for any Decimal.
3840353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3841353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_canonical(Decimal('2.50'))
38421a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3843353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
38441a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return a.is_canonical()
3845353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3846353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_finite(self, a):
38471a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is finite; otherwise return False.
3848353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
38491a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        A Decimal instance is considered finite if it is neither
38501a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        infinite nor a NaN.
3851353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3852353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('2.50'))
38531a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3854353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('-0.3'))
38551a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3856353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('0'))
38571a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3858353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('Inf'))
38591a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3860353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('NaN'))
38611a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3862353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3863353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_finite()
3864353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3865353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_infinite(self, a):
38661a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is infinite; otherwise return False.
3867353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3868353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_infinite(Decimal('2.50'))
38691a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3870353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_infinite(Decimal('-Inf'))
38711a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3872353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_infinite(Decimal('NaN'))
38731a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3874353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3875353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_infinite()
3876353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3877353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_nan(self, a):
38781a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is a qNaN or sNaN;
38791a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        otherwise return False.
3880353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3881353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_nan(Decimal('2.50'))
38821a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3883353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_nan(Decimal('NaN'))
38841a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3885353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_nan(Decimal('-sNaN'))
38861a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3887353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3888353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_nan()
3889353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3890353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_normal(self, a):
38911a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is a normal number;
38921a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        otherwise return False.
3893353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3894353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
3895353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
3896353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
3897353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('2.50'))
38981a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3899353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('0.1E-999'))
39001a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3901353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('0.00'))
39021a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3903353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('-Inf'))
39041a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3905353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('NaN'))
39061a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3907353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3908353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_normal(context=self)
3909353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3910353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_qnan(self, a):
39111a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is a quiet NaN; otherwise return False.
3912353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3913353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_qnan(Decimal('2.50'))
39141a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3915353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_qnan(Decimal('NaN'))
39161a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3917353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_qnan(Decimal('sNaN'))
39181a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3919353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3920353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_qnan()
3921353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3922353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_signed(self, a):
39231a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is negative; otherwise return False.
3924353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3925353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_signed(Decimal('2.50'))
39261a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3927353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_signed(Decimal('-12'))
39281a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3929353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_signed(Decimal('-0'))
39301a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3931353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3932353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_signed()
3933353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3934353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_snan(self, a):
39351a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is a signaling NaN;
39361a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        otherwise return False.
3937353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3938353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_snan(Decimal('2.50'))
39391a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3940353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_snan(Decimal('NaN'))
39411a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3942353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_snan(Decimal('sNaN'))
39431a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3944353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3945353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_snan()
3946353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3947353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_subnormal(self, a):
39481a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is subnormal; otherwise return False.
3949353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3950353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
3951353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
3952353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
3953353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('2.50'))
39541a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3955353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('0.1E-999'))
39561a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3957353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('0.00'))
39581a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3959353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('-Inf'))
39601a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3961353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('NaN'))
39621a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3963353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3964353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_subnormal(context=self)
3965353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3966353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_zero(self, a):
39671a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is a zero; otherwise return False.
3968353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3969353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_zero(Decimal('0'))
39701a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3971353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_zero(Decimal('2.50'))
39721a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3973353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_zero(Decimal('-0E+2'))
39741a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3975353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3976353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_zero()
3977353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3978353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def ln(self, a):
3979353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the natural (base e) logarithm of the operand.
3980353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3981353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
3982353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
3983353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
3984353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('0'))
3985353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-Infinity")
3986353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('1.000'))
3987353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3988353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('2.71828183'))
3989353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.00000000")
3990353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('10'))
3991353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.30258509")
3992353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('+Infinity'))
3993353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("Infinity")
3994353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3995353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.ln(context=self)
3996353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3997353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def log10(self, a):
3998353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the base 10 logarithm of the operand.
3999353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4000353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4001353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4002353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4003353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('0'))
4004353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-Infinity")
4005353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('0.001'))
4006353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-3")
4007353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('1.000'))
4008353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4009353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('2'))
4010353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0.301029996")
4011353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('10'))
4012353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4013353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('70'))
4014353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.84509804")
4015353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('+Infinity'))
4016353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("Infinity")
4017353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4018353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.log10(context=self)
4019353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4020353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logb(self, a):
4021353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """ Returns the exponent of the magnitude of the operand's MSD.
4022353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4023353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result is the integer which is the exponent of the magnitude
4024353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        of the most significant digit of the operand (as though the
4025353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        operand were truncated to a single digit while maintaining the
4026353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        value of that digit and without limiting the resulting exponent).
4027353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4028353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logb(Decimal('250'))
4029353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2")
4030353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logb(Decimal('2.50'))
4031353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4032353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logb(Decimal('0.03'))
4033353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-2")
4034353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logb(Decimal('0'))
4035353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-Infinity")
4036353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4037353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logb(context=self)
4038353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4039353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_and(self, a, b):
4040353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies the logical operation 'and' between each operand's digits.
4041353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4042353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The operands must be both logical numbers.
4043353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4044353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4045353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4046353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4047353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4048353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4049353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4050353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4051353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4052353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4053353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1000")
4054353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4055353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("10")
4056353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logical_and(b, context=self)
4058353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_invert(self, a):
4060353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Invert all the digits in the operand.
4061353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4062353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The operand must be a logical number.
4063353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4064353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_invert(Decimal('0'))
4065353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("111111111")
4066353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_invert(Decimal('1'))
4067353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("111111110")
4068353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_invert(Decimal('111111111'))
4069353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4070353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_invert(Decimal('101010101'))
4071353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("10101010")
4072353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logical_invert(context=self)
4074353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4075353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_or(self, a, b):
4076353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies the logical operation 'or' between each operand's digits.
4077353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4078353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The operands must be both logical numbers.
4079353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4080353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4081353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4082353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4083353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4084353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4085353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4086353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4087353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4088353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4089353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1110")
4090353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4091353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1110")
4092353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4093353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logical_or(b, context=self)
4094353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4095353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_xor(self, a, b):
4096353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies the logical operation 'xor' between each operand's digits.
4097353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4098353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The operands must be both logical numbers.
4099353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4100353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4101353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4102353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4103353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4104353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4105353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4106353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4107353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4108353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4109353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("110")
4110353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4111353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1101")
4112353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4113353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logical_xor(b, context=self)
4114353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
41157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def max(self, a,b):
41167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """max compares two values numerically and returns the maximum.
41177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If either operand is a NaN then the general rules apply.
41197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Otherwise, the operands are compared as as though by the compare
412059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operation.  If they are numerically equal then the left-hand operand
412159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        is chosen as the result.  Otherwise the maximum (closer to positive
41227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        infinity) of the two operands is chosen as the result.
41237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41249ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
41257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3")
41269ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
41277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3")
41289ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
4129d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        Decimal("1")
4130d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4131d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        Decimal("7")
41327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
41337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.max(b, context=self)
41347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4135353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def max_mag(self, a, b):
4136353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values numerically with their sign ignored."""
4137353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.max_mag(b, context=self)
4138353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
41397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def min(self, a,b):
41407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """min compares two values numerically and returns the minimum.
41417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If either operand is a NaN then the general rules apply.
41437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Otherwise, the operands are compared as as though by the compare
414459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operation.  If they are numerically equal then the left-hand operand
414559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        is chosen as the result.  Otherwise the minimum (closer to negative
41467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        infinity) of the two operands is chosen as the result.
41477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41489ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
41497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2")
41509ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
41517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-10")
41529ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
41537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.0")
4154d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4155d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        Decimal("7")
41567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
41577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.min(b, context=self)
41587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4159353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def min_mag(self, a, b):
4160353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values numerically with their sign ignored."""
4161353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.min_mag(b, context=self)
4162353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
41637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def minus(self, a):
41647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Minus corresponds to unary prefix minus in Python.
41657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The operation is evaluated using the same rules as subtract; the
41677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        operation minus(a) is calculated as subtract('0', a) where the '0'
41687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        has the same exponent as the operand.
41697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41709ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.minus(Decimal('1.3'))
41717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1.3")
41729ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.minus(Decimal('-1.3'))
41737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.3")
41747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
41757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__neg__(context=self)
41767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def multiply(self, a, b):
41787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """multiply multiplies two operands.
41797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4180cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis        If either operand is a special value then the general rules apply.
4181cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis        Otherwise, the operands are multiplied together ('long multiplication'),
4182cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis        resulting in a number which may be as long as the sum of the lengths
4183cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis        of the two operands.
41847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41859ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
41867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3.60")
41879ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
41887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("21")
41899ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
41907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.72")
41919ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
41927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0.0")
41939ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
41947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("4.28135971E+11")
41957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
41967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__mul__(b, context=self)
41977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4198353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_minus(self, a):
4199353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the largest representable number smaller than a.
4200353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4201353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4202353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4203353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4204353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.next_minus(Decimal('1'))
4205353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0.999999999")
4206353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_minus(Decimal('1E-1007'))
4207353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0E-1007")
4208353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4209353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.00000004")
4210353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_minus(Decimal('Infinity'))
4211353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("9.99999999E+999")
4212353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4213353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.next_minus(context=self)
4214353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4215353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_plus(self, a):
4216353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the smallest representable number larger than a.
4217353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4218353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4219353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4220353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4221353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.next_plus(Decimal('1'))
4222353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.00000001")
4223353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_plus(Decimal('-1E-1007'))
4224353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-0E-1007")
4225353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4226353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.00000002")
4227353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_plus(Decimal('-Infinity'))
4228353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-9.99999999E+999")
4229353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4230353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.next_plus(context=self)
4231353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4232353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_toward(self, a, b):
4233353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the number closest to a, in direction towards b.
4234353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4235353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result is the closest representable number from the first
4236353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        operand (but not the first operand) that is in the direction
4237353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        towards the second operand, unless the operands have the same
4238353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        value.
4239353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4240353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4241353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4242353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4243353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('1'), Decimal('2'))
4244353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.00000001")
4245353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4246353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-0E-1007")
4247353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4248353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.00000002")
4249353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('1'), Decimal('0'))
4250353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0.999999999")
4251353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4252353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0E-1007")
4253353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4254353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.00000004")
4255353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4256353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-0.00")
4257353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4258353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.next_toward(b, context=self)
4259353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
42607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def normalize(self, a):
4261e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger        """normalize reduces an operand to its simplest form.
42627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
42637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Essentially a plus operation with all trailing zeros removed from the
42647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        result.
42657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
42669ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('2.1'))
42677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.1")
42689ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('-2.0'))
42697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-2")
42709ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('1.200'))
42717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.2")
42729ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('-120'))
42737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1.2E+2")
42749ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('120.00'))
42757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.2E+2")
42769ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('0.00'))
42777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0")
42787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
42797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.normalize(context=self)
42807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4281353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def number_class(self, a):
4282353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns an indication of the class of the operand.
4283353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4284353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The class is one of the following strings:
4285353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -sNaN
4286353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -NaN
4287353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Infinity
4288353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Normal
4289353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Subnormal
4290353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Zero
4291353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Zero
4292353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Subnormal
4293353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Normal
4294353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Infinity
4295353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4296353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = Context(ExtendedContext)
4297353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4298353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4299353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('Infinity'))
4300353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Infinity'
4301353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('1E-10'))
4302353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Normal'
4303353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('2.50'))
4304353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Normal'
4305353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('0.1E-999'))
4306353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Subnormal'
4307353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('0'))
4308353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Zero'
4309353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-0'))
4310353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Zero'
4311353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-0.1E-999'))
4312353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Subnormal'
4313353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-1E-10'))
4314353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Normal'
4315353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-2.50'))
4316353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Normal'
4317353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-Infinity'))
4318353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Infinity'
4319353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('NaN'))
4320353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        'NaN'
4321353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-NaN'))
4322353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        'NaN'
4323353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('sNaN'))
4324353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        'sNaN'
4325353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4326353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.number_class(context=self)
4327353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
43287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def plus(self, a):
43297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Plus corresponds to unary prefix plus in Python.
43307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
43317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The operation is evaluated using the same rules as add; the
43327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        operation plus(a) is calculated as add('0', a) where the '0'
43337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        has the same exponent as the operand.
43347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
43359ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.plus(Decimal('1.3'))
43367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.3")
43379ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.plus(Decimal('-1.3'))
43387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1.3")
43397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
43407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__pos__(context=self)
43417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
43427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def power(self, a, b, modulo=None):
43437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Raises a to the power of b, to modulo if given.
43447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4345353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        With two arguments, compute a**b.  If a is negative then b
4346353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        must be integral.  The result will be inexact unless b is
4347353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        integral and the result is finite and can be expressed exactly
4348353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        in 'precision' digits.
4349353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4350353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        With three arguments, compute (a**b) % modulo.  For the
4351353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        three argument form, the following restrictions on the
4352353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        arguments hold:
4353353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4354353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - all three arguments must be integral
4355353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - b must be nonnegative
4356353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - at least one of a or b must be nonzero
4357353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - modulo must be nonzero and have at most 'precision' digits
4358353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4359353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result of pow(a, b, modulo) is identical to the result
4360353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        that would be obtained by computing (a**b) % modulo with
4361353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        unbounded precision, but is computed more efficiently.  It is
4362353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        always exact.
4363353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4364353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4365353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4366353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4367353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('2'), Decimal('3'))
43687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("8")
4369353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-2'), Decimal('3'))
4370353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-8")
4371353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('2'), Decimal('-3'))
43727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.125")
4373353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('1.7'), Decimal('8'))
43747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("69.7575744")
4375353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('10'), Decimal('0.301029996'))
4376353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.00000000")
4377353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('Infinity'), Decimal('-1'))
43787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0")
4379353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('Infinity'), Decimal('0'))
43807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
4381353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('Infinity'), Decimal('1'))
43827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("Infinity")
4383353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-Infinity'), Decimal('-1'))
43847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0")
4385353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-Infinity'), Decimal('0'))
43867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
4387353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-Infinity'), Decimal('1'))
43887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-Infinity")
4389353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-Infinity'), Decimal('2'))
43907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("Infinity")
4391353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('0'), Decimal('0'))
43927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("NaN")
4393353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4394353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4395353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("11")
4396353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4397353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-11")
4398353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4399353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4400353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4401353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("11")
4402353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4403353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("11729830")
4404353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4405353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-0")
4406353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4407353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
44087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
44097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__pow__(b, modulo, context=self)
44107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def quantize(self, a, b):
441259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
44137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The coefficient of the result is derived from that of the left-hand
441559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operand.  It may be rounded using the current rounding setting (if the
44167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exponent is being increased), multiplied by a positive power of ten (if
44177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        the exponent is being decreased), or is unchanged (if the exponent is
44187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        already equal to that of the right-hand operand).
44197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Unlike other operations, if the length of the coefficient after the
44217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        quantize operation would be greater than precision then an Invalid
442259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operation condition is raised.  This guarantees that, unless there is
442359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        an error condition, the exponent of the result of a quantize is always
44247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        equal to that of the right-hand operand.
44257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Also unlike other operations, quantize will never raise Underflow, even
44277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if the result is subnormal and inexact.
44287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44299ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
44307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.170")
44319ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
44327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.17")
44339ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
44347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.2")
44359ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
44367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2")
44379ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
44387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0E+1")
44399ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
44407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-Infinity")
44419ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
44427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("NaN")
44439ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
44447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0")
44459ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
44467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0E+5")
44479ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
44487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("NaN")
44499ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
44507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("NaN")
44519ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
44527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("217.0")
44539ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
44547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("217")
44559ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
44567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.2E+2")
44579ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
44587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2E+2")
44597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
44607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.quantize(b, context=self)
44617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4462353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def radix(self):
4463353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Just returns 10, as this is Decimal, :)
4464353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4465353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.radix()
4466353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("10")
4467353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4468353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal(10)
4469353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
44707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def remainder(self, a, b):
44717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the remainder from integer division.
44727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The result is the residue of the dividend after the operation of
447459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        calculating integer division as described for divide-integer, rounded
44750d4c06e06e5ee1f3bb1fa8068114bd700d74864aNeal Norwitz        to precision digits if necessary.  The sign of the result, if
447659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        non-zero, is the same as that of the original dividend.
44777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        This operation will fail under the same conditions as integer division
44797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        (that is, if integer division on the same two operands would fail, the
44807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        remainder cannot be calculated).
44817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44829ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
44837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.1")
44849ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
44857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
44869ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
44877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1")
44889ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
44897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.2")
44909ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
44917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.1")
44929ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
44937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.0")
44947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
44957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__mod__(b, context=self)
44967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def remainder_near(self, a, b):
44987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns to be "a - b * n", where n is the integer nearest the exact
44997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        value of "x / b" (if two integers are equally near then the even one
450059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        is chosen).  If the result is equal to 0 then its sign will be the
45017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        sign of a.
45027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        This operation will fail under the same conditions as integer division
45047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        (that is, if integer division on the same two operands would fail, the
45057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        remainder cannot be calculated).
45067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45079ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
45087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0.9")
45099ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
45107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-2")
45119ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
45127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
45139ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
45147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1")
45159ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
45167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.2")
45179ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
45187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.1")
45199ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
45207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0.3")
45217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
45227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.remainder_near(b, context=self)
45237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4524353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def rotate(self, a, b):
4525353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a rotated copy of a, b times.
4526353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4527353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The coefficient of the result is a rotated copy of the digits in
4528353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        the coefficient of the first operand.  The number of places of
4529353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotation is taken from the absolute value of the second operand,
4530353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        with the rotation being to the left if the second operand is
4531353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        positive or to the right otherwise.
4532353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4533353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4534353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("400000003")
4535353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4536353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("12")
4537353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4538353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("891234567")
4539353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4540353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("123456789")
4541353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4542353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("345678912")
4543353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4544353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.rotate(b, context=self)
4545353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
45467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def same_quantum(self, a, b):
45477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns True if the two operands have the same exponent.
45487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The result is never affected by either the sign or the coefficient of
45507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        either operand.
45517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45529ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
45537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        False
45549ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
45557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        True
45569ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
45577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        False
45589ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
45597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        True
45607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
45617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.same_quantum(b)
45627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4563353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def scaleb (self, a, b):
4564353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the first operand after adding the second value its exp.
4565353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4566353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4567353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0.0750")
4568353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4569353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("7.50")
4570353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4571353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("7.50E+3")
4572353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4573353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.scaleb (b, context=self)
4574353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4575353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def shift(self, a, b):
4576353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a shifted copy of a, b times.
4577353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4578353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The coefficient of the result is a shifted copy of the digits
4579353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        in the coefficient of the first operand.  The number of places
4580353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        to shift is taken from the absolute value of the second operand,
4581353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        with the shift being to the left if the second operand is
4582353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        positive or to the right otherwise.  Digits shifted into the
4583353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        coefficient are zeros.
4584353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4585353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4586353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("400000000")
4587353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4588353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4589353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4590353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1234567")
4591353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4592353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("123456789")
4593353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4594353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("345678900")
4595353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4596353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.shift(b, context=self)
4597353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
45987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def sqrt(self, a):
459959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        """Square root of a non-negative number to context precision.
46007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the result must be inexact, it is rounded using the round-half-even
46027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        algorithm.
46037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46049ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('0'))
46057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0")
46069ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('-0'))
46077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0")
46089ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('0.39'))
46097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.624499800")
46109ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('100'))
46117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("10")
46129ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('1'))
46137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
46149ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('1.0'))
46157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.0")
46169ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('1.00'))
46177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.0")
46189ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('7'))
46197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.64575131")
46209ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('10'))
46217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3.16227766")
46229ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.prec
46236ea484582238a65d44a76e3a831e3ba7c77a1a25Raymond Hettinger        9
46247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
46257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.sqrt(context=self)
46267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def subtract(self, a, b):
4628f33d01d304c349a7f555779c7c99930f1203adb7Georg Brandl        """Return the difference between the two operands.
46297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46309ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
46317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.23")
46329ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
46337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.00")
46349ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
46357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0.77")
46367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
46377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__sub__(b, context=self)
46387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def to_eng_string(self, a):
46407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Converts a number to a string, using scientific notation.
46417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The operation is not affected by the context.
46437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
46447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.to_eng_string(context=self)
46457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def to_sci_string(self, a):
46477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Converts a number to a string, using scientific notation.
46487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The operation is not affected by the context.
46507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
46517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__str__(context=self)
46527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4653353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def to_integral_exact(self, a):
4654353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds to an integer.
4655353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4656353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        When the operand has a negative exponent, the result is the same
4657353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        as using the quantize() operation using the given operand as the
4658353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4659353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        of the operand as the precision setting; Inexact and Rounded flags
4660353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        are allowed in this operation.  The rounding mode is taken from the
4661353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.
4662353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4663353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4664353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2")
4665353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('100'))
4666353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("100")
4667353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4668353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("100")
4669353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4670353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("102")
4671353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4672353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-102")
4673353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4674353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.0E+6")
4675353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4676353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("7.89E+77")
4677353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4678353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-Infinity")
4679353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4680353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.to_integral_exact(context=self)
4681353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4682353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def to_integral_value(self, a):
46837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Rounds to an integer.
46847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        When the operand has a negative exponent, the result is the same
46867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        as using the quantize() operation using the given operand as the
46877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        left-hand-operand, 1E+0 as the right-hand-operand, and the precision
46887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        of the operand as the precision setting, except that no flags will
468959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        be set.  The rounding mode is taken from the context.
46907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4691353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('2.1'))
46927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2")
4693353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('100'))
46947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("100")
4695353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('100.0'))
46967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("100")
4697353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('101.5'))
46987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("102")
4699353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
47007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-102")
4701353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
47027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.0E+6")
4703353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
47047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("7.89E+77")
4705353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
47067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-Infinity")
47077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
4708353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.to_integral_value(context=self)
4709353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4710353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # the method name changed, but we provide also the old one, for compatibility
4711353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    to_integral = to_integral_value
47127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass _WorkRep(object):
47147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __slots__ = ('sign','int','exp')
471517931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger    # sign: 0 or 1
4716636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    # int:  int or long
47177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    # exp:  None, int, or string
47187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __init__(self, value=None):
47207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if value is None:
47217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.sign = None
4722636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self.int = 0
47237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.exp = None
472417931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        elif isinstance(value, Decimal):
472517931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            self.sign = value._sign
472672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self.int = int(value._int)
47277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.exp = value._exp
472817931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        else:
472917931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            # assert isinstance(value, tuple)
47307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.sign = value[0]
47317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.int = value[1]
47327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.exp = value[2]
47337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __repr__(self):
47357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
47367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __str__ = __repr__
47387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerdef _normalize(op1, op2, shouldround = 0, prec = 0):
47427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Normalizes op1, op2 to have the same exp and length of coefficient.
47437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Done during addition.
47457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
4746353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if op1.exp < op2.exp:
47477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        tmp = op2
47487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        other = op1
47497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    else:
47507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        tmp = op1
47517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        other = op2
47527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4753353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4754353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Then adding 10**exp to tmp has the same effect (after rounding)
4755353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # as adding any positive quantity smaller than 10**exp; similarly
4756353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # for subtraction.  So if other is smaller than 10**exp we replace
4757353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # it with 10**exp.  This avoids tmp.exp - other.exp getting too large.
4758353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if shouldround:
4759636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        tmp_len = len(str(tmp.int))
4760636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other_len = len(str(other.int))
4761353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exp = tmp.exp + min(-1, tmp_len - prec - 2)
4762353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other_len + other.exp - 1 < exp:
4763636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            other.int = 1
4764353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            other.exp = exp
4765636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
4766353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    tmp.int *= 10 ** (tmp.exp - other.exp)
4767353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    tmp.exp = other.exp
47687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    return op1, op2
47697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4770353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4771353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4772353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# This function from Tim Peters was taken from here:
4773353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4774353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# The correction being in the function definition is for speed, and
4775353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# the whole function is not resolved with math.log because of avoiding
4776353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# the use of floats.
4777353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _nbits(n, correction = {
4778353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '0': 4, '1': 3, '2': 2, '3': 2,
4779353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '4': 1, '5': 1, '6': 1, '7': 1,
4780353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '8': 0, '9': 0, 'a': 0, 'b': 0,
4781353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4782353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Number of bits in binary representation of the positive integer n,
4783353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    or 0 if n == 0.
4784353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
4785353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if n < 0:
4786353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        raise ValueError("The argument to _nbits should be nonnegative.")
4787353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    hex_n = "%x" % n
4788353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return 4*len(hex_n) - correction[hex_n[0]]
4789353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4790353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _sqrt_nearest(n, a):
4791353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Closest integer to the square root of the positive integer n.  a is
4792353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    an initial approximation to the square root.  Any positive integer
4793353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    will do for a, but the closer a is to the square root of n the
4794353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    faster convergence will be.
4795353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4796353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
4797353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if n <= 0 or a <= 0:
4798353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4799353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4800353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    b=0
4801353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    while a != b:
4802353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        b, a = a, a--n//a>>1
4803353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return a
4804353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4805353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _rshift_nearest(x, shift):
4806353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given an integer x and a nonnegative integer shift, return closest
4807353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    integer to x / 2**shift; use round-to-even in case of a tie.
4808353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4809353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
4810353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    b, q = 1L << shift, x >> shift
4811353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return q + (2*(x & (b-1)) + (q&1) > b)
4812353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4813353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _div_nearest(a, b):
4814353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Closest integer to a/b, a and b positive integers; rounds to even
4815353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    in the case of a tie.
4816353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4817353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
4818353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    q, r = divmod(a, b)
4819353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return q + (2*r + (q&1) > b)
4820353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4821353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _ilog(x, M, L = 8):
4822353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Integer approximation to M*log(x/M), with absolute error boundable
4823353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    in terms only of x/M.
4824353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4825353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    Given positive integers x and M, return an integer approximation to
4826353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    M * log(x/M).  For L = 8 and 0.1 <= x/M <= 10 the difference
4827353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    between the approximation and the exact result is at most 22.  For
4828353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15.  In
4829353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    both cases these are upper bounds on the error; it will usually be
4830353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    much smaller."""
4831353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4832353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # The basic algorithm is the following: let log1p be the function
4833353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # log1p(x) = log(1+x).  Then log(x/M) = log1p((x-M)/M).  We use
4834353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # the reduction
4835353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4836353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #    log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4837353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4838353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # repeatedly until the argument to log1p is small (< 2**-L in
4839353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # absolute value).  For small y we can use the Taylor series
4840353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # expansion
4841353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4842353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #    log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4843353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4844353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # truncating at T such that y**T is small enough.  The whole
4845353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # computation is carried out in a form of fixed-point arithmetic,
4846353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # with a real number z being represented by an integer
4847353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # approximation to z*M.  To avoid loss of precision, the y below
4848353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # is actually an integer approximation to 2**R*y*M, where R is the
4849353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # number of reductions performed so far.
4850353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4851353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    y = x-M
4852353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # argument reduction; R = number of reductions performed
4853353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    R = 0
4854353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    while (R <= L and long(abs(y)) << L-R >= M or
4855353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista           R > L and abs(y) >> R-L >= M):
4856353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        y = _div_nearest(long(M*y) << 1,
4857353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                         M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4858353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        R += 1
4859353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4860353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Taylor series with T terms
4861353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    T = -int(-10*len(str(M))//(3*L))
4862353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    yshift = _rshift_nearest(y, R)
4863353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    w = _div_nearest(M, T)
4864353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    for k in xrange(T-1, 0, -1):
4865353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4866353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4867353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return _div_nearest(w*y, M)
4868353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4869353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _dlog10(c, e, p):
4870353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given integers c, e and p with c > 0, p >= 0, compute an integer
4871353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    approximation to 10**p * log10(c*10**e), with an absolute error of
4872353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    at most 1.  Assumes that c*10**e is not exactly 1."""
4873353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4874353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # increase precision by 2; compensate for this by dividing
4875353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # final result by 100
4876353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    p += 2
4877353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4878353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # write c*10**e as d*10**f with either:
4879353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #   f >= 0 and 1 <= d <= 10, or
4880353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #   f <= 0 and 0.1 <= d <= 1.
4881353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Thus for c*10**e close to 1, f = 0
4882353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    l = len(str(c))
4883353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    f = e+l - (e+l >= 1)
4884353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4885353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if p > 0:
4886353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        M = 10**p
4887353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        k = e+p-f
4888353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if k >= 0:
4889353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c *= 10**k
4890353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
4891353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = _div_nearest(c, 10**-k)
4892353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4893353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = _ilog(c, M) # error < 5 + 22 = 27
4894be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        log_10 = _log10_digits(p) # error < 1
4895353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = _div_nearest(log_d*M, log_10)
4896353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_tenpower = f*M # exact
4897353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
4898353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = 0  # error < 2.31
4899353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4900353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4901353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return _div_nearest(log_tenpower+log_d, 100)
4902353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4903353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _dlog(c, e, p):
4904353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given integers c, e and p with c > 0, compute an integer
4905353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    approximation to 10**p * log(c*10**e), with an absolute error of
4906353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    at most 1.  Assumes that c*10**e is not exactly 1."""
4907353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4908353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Increase precision by 2. The precision increase is compensated
4909353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # for at the end with a division by 100.
4910353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    p += 2
4911353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4912353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4913353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # or f <= 0 and 0.1 <= d <= 1.  Then we can compute 10**p * log(c*10**e)
4914353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # as 10**p * log(d) + 10**p*f * log(10).
4915353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    l = len(str(c))
4916353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    f = e+l - (e+l >= 1)
4917353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4918353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # compute approximation to 10**p*log(d), with error < 27
4919353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if p > 0:
4920353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        k = e+p-f
4921353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if k >= 0:
4922353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c *= 10**k
4923353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
4924353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = _div_nearest(c, 10**-k)  # error of <= 0.5 in c
4925353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4926353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # _ilog magnifies existing error in c by a factor of at most 10
4927353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4928353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
4929353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # p <= 0: just approximate the whole thing by 0; error < 2.31
4930353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = 0
4931353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4932be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    # compute approximation to f*10**p*log(10), with error < 11.
4933353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if f:
4934be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        extra = len(str(abs(f)))-1
4935be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        if p + extra >= 0:
4936be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4937be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4938be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
4939353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
4940353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            f_log_ten = 0
4941353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
4942353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        f_log_ten = 0
4943353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4944be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
4945353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return _div_nearest(f_log_ten + log_d, 100)
4946353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4947be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batistaclass _Log10Memoize(object):
4948be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    """Class to compute, store, and allow retrieval of, digits of the
4949be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    constant log(10) = 2.302585....  This constant is needed by
4950be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4951be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    def __init__(self):
4952be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        self.digits = "23025850929940456840179914546843642076011014886"
4953be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista
4954be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    def getdigits(self, p):
4955be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        """Given an integer p >= 0, return floor(10**p)*log(10).
4956be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista
4957be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        For example, self.getdigits(3) returns 2302.
4958be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        """
4959be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        # digits are stored as a string, for quick conversion to
4960be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        # integer in the case that we've already computed enough
4961be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        # digits; the stored digits should always be correct
4962be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        # (truncated, not rounded to nearest).
4963be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        if p < 0:
4964be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            raise ValueError("p should be nonnegative")
4965be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista
4966be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        if p >= len(self.digits):
4967be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # compute p+3, p+6, p+9, ... digits; continue until at
4968be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # least one of the extra digits is nonzero
4969be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            extra = 3
4970be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            while True:
4971be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                # compute p+extra digits, correct to within 1ulp
4972be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                M = 10**(p+extra+2)
4973be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                digits = str(_div_nearest(_ilog(10*M, M), 100))
4974be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                if digits[-extra:] != '0'*extra:
4975be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                    break
4976be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                extra += 3
4977be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # keep all reliable digits so far; remove trailing zeros
4978be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # and next nonzero digit
4979be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            self.digits = digits.rstrip('0')[:-1]
4980be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        return int(self.digits[:p+1])
4981be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista
4982be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista_log10_digits = _Log10Memoize().getdigits
4983be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista
4984353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _iexp(x, M, L=8):
4985353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given integers x and M, M > 0, such that x/M is small in absolute
4986353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    value, compute an integer approximation to M*exp(x/M).  For 0 <=
4987353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4988353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    is usually much smaller)."""
4989353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4990353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Algorithm: to compute exp(z) for a real number z, first divide z
4991353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # by a suitable power R of 2 so that |z/2**R| < 2**-L.  Then
4992353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
4993353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # series
4994353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4995353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #     expm1(x) = x + x**2/2! + x**3/3! + ...
4996353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4997353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Now use the identity
4998353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4999353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #     expm1(2x) = expm1(x)*(expm1(x)+2)
5000353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
5001353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # R times to compute the sequence expm1(z/2**R),
5002353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5003353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5004353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Find R such that x/2**R/M <= 2**-L
5005353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    R = _nbits((long(x)<<L)//M)
5006353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5007353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Taylor series.  (2**L)**T > M
5008353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    T = -int(-10*len(str(M))//(3*L))
5009353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    y = _div_nearest(x, T)
5010353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    Mshift = long(M)<<R
5011353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    for i in xrange(T-1, 0, -1):
5012353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        y = _div_nearest(x*(Mshift + y), Mshift * i)
5013353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5014353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Expansion
5015353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    for k in xrange(R-1, -1, -1):
5016353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Mshift = long(M)<<(k+2)
5017353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        y = _div_nearest(y*(y+Mshift), Mshift)
5018353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5019353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return M+y
5020353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5021353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _dexp(c, e, p):
5022353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Compute an approximation to exp(c*10**e), with p decimal places of
5023353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    precision.
5024353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5025be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    Returns integers d, f such that:
5026353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5027353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista      10**(p-1) <= d <= 10**p, and
5028353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista      (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5029353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5030353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    In other words, d*10**f is an approximation to exp(c*10**e) with p
5031353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    digits of precision, and with an error in d of at most 1.  This is
5032353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    almost, but not quite, the same as the error being < 1ulp: when d
5033353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    = 10**(p-1) the error could be up to 10 ulp."""
5034353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5035353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5036353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    p += 2
5037353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5038be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    # compute log(10) with extra precision = adjusted exponent of c*10**e
5039353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    extra = max(0, e + len(str(c)) - 1)
5040353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    q = p + extra
5041353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5042be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
5043353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # rounding down
5044353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    shift = e+q
5045353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if shift >= 0:
5046353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        cshift = c*10**shift
5047353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
5048353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        cshift = c//10**-shift
5049be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    quot, rem = divmod(cshift, _log10_digits(q))
5050353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5051353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # reduce remainder back to original precision
5052353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    rem = _div_nearest(rem, 10**extra)
5053353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5054353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # error in result of _iexp < 120;  error after division < 0.62
5055353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5056353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _dpower(xc, xe, yc, ye, p):
5058353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    y = yc*10**ye, compute x**y.  Returns a pair of integers (c, e) such that:
5060353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5061353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista      10**(p-1) <= c <= 10**p, and
5062353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista      (c-1)*10**e < x**y < (c+1)*10**e
5063353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5064353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    in other words, c*10**e is an approximation to x**y with p digits
5065353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    of precision, and with an error in c of at most 1.  (This is
5066353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    almost, but not quite, the same as the error being < 1ulp: when c
5067353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    == 10**(p-1) we can only guarantee error < 10ulp.)
5068353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5069353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    We assume that: x is positive and not equal to 1, and y is nonzero.
5070353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
5071353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5072353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Find b such that 10**(b-1) <= |y| <= 10**b
5073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    b = len(str(abs(yc))) + ye
5074353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5075353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5076353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    lxc = _dlog(xc, xe, p+b+1)
5077353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5078353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5079353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    shift = ye-b
5080353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if shift >= 0:
5081353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        pc = lxc*yc*10**shift
5082353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
5083353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        pc = _div_nearest(lxc*yc, 10**-shift)
5084353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5085353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if pc == 0:
5086353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # we prefer a result that isn't exactly 1; this makes it
5087353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # easier to compute a correctly rounded result in __pow__
5088353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5089353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            coeff, exp = 10**(p-1)+1, 1-p
5090353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
5091353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            coeff, exp = 10**p-1, -p
5092353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
5093353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        coeff, exp = _dexp(pc, -(p+1), p+1)
5094353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        coeff = _div_nearest(coeff, 10)
5095353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exp += 1
5096353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5097353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return coeff, exp
5098353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5099353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _log10_lb(c, correction = {
5100353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5101353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '6': 23, '7': 16, '8': 10, '9': 5}):
5102353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Compute a lower bound for 100*log10(c) for a positive integer c."""
5103353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if c <= 0:
5104353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        raise ValueError("The argument to _log10_lb should be nonnegative.")
5105353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    str_c = str(c)
5106353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return 100*len(str_c) - correction[str_c[0]]
5107353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
510859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Helper Functions ####################################################
51097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
5110353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _convert_other(other, raiseit=False):
5111636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    """Convert other to Decimal.
5112636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
5113636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    Verifies that it's ok to use in an implicit construction.
5114636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    """
5115636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    if isinstance(other, Decimal):
5116636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        return other
5117636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    if isinstance(other, (int, long)):
5118636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        return Decimal(other)
5119353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if raiseit:
5120353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        raise TypeError("Unable to convert %s to Decimal" % other)
5121267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger    return NotImplemented
5122636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
512359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Setup Specific Contexts ############################################
51247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# The default context prototype used by Context()
5126fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger# Is mutable, so that new contexts can have different default values
51277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerDefaultContext = Context(
51296ea484582238a65d44a76e3a831e3ba7c77a1a25Raymond Hettinger        prec=28, rounding=ROUND_HALF_EVEN,
5130bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        traps=[DivisionByZero, Overflow, InvalidOperation],
5131bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        flags=[],
51327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        _rounding_decision=ALWAYS_ROUND,
513399148e7eaad7741fbfb0822009b7c9b216ecc227Raymond Hettinger        Emax=999999999,
513499148e7eaad7741fbfb0822009b7c9b216ecc227Raymond Hettinger        Emin=-999999999,
5135e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger        capitals=1
51367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger)
51377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# Pre-made alternate contexts offered by the specification
51397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# Don't change these; the user should be able to select these
51407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# contexts and be able to reproduce results from other implementations
51417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# of the spec.
51427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51439ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond HettingerBasicContext = Context(
51447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        prec=9, rounding=ROUND_HALF_UP,
5145bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5146bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        flags=[],
51477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger)
51487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51499ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond HettingerExtendedContext = Context(
51506ea484582238a65d44a76e3a831e3ba7c77a1a25Raymond Hettinger        prec=9, rounding=ROUND_HALF_EVEN,
5151bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        traps=[],
5152bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        flags=[],
51537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger)
51547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
515659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### crud for parsing strings #############################################
51577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerimport re
51587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
515972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# Regular expression used for parsing numeric strings.  Additional
516072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# comments:
516172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista#
516272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
516372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# whitespace.  But note that the specification disallows whitespace in
516472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# a numeric string.
516572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista#
516672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# 2. For finite numbers (not infinities and NaNs) the body of the
516772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# number between the optional sign and the optional exponent must have
516872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# at least one decimal digit, possibly after the decimal point.  The
516972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# lookahead expression '(?=\d|\.\d)' checks this.
517072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista#
517172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# As the flag UNICODE is not enabled here, we're explicitly avoiding any
517272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# other meaning for \d than the numbers [0-9].
51737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
517472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batistaimport re
517572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista_parser = re.compile(r"""     # A numeric string consists of:
51767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger#    \s*
517772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    (?P<sign>[-+])?           # an optional sign, followed by either...
51787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    (
517972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        (?=\d|\.\d)           # ...a number (with at least one digit)
518072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        (?P<int>\d*)          # consisting of a (possibly empty) integer part
518172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        (\.(?P<frac>\d*))?    # followed by an optional fractional part
518272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
51837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    |
518472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        Inf(inity)?           # ...an infinity, or...
518572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    |
518672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        (?P<signal>s)?        # ...an (optionally signaling)
518772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        NaN                   # NaN
518872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        (?P<diag>\d*)         # with (possibly empty) diagnostic information.
51897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    )
51907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger#    \s*
51917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    $
519272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista""", re.VERBOSE | re.IGNORECASE).match
51937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51942ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista_all_zeros = re.compile('0*$').match
51952ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista_exact_half = re.compile('50*$').match
51967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerdel re
51977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51980d4c06e06e5ee1f3bb1fa8068114bd700d74864aNeal Norwitz
519972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista##### Useful Constants (internal use only) ################################
52007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
520172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# Reusable defaults
520272bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaInf = Decimal('Inf')
520372bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistanegInf = Decimal('-Inf')
520472bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaNaN = Decimal('NaN')
520572bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaDec_0 = Decimal(0)
520672bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaDec_p1 = Decimal(1)
520772bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaDec_n1 = Decimal(-1)
520872bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaDec_p2 = Decimal(2)
520972bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaDec_n2 = Decimal(-2)
52107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
521172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# Infsign[sign] is infinity w/ that sign
521272bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaInfsign = (Inf, negInf)
52137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerif __name__ == '__main__':
52177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    import doctest, sys
52187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    doctest.testmod(sys.modules[__name__])
5219