decimal.py revision e64acfad3dd13809943eecf50f11c40c510dedbe
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# Errors
1507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass DecimalException(ArithmeticError):
1525aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger    """Base exception class.
1537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Used exceptions derive from this.
1557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    If an exception derives from another exception besides this (such as
1567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
1577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    called if the others are present.  This isn't actually used for
1587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    anything, though.
1597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
160cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis    handle  -- Called when context._raise_error is called and the
161cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis               trap_enabler is set.  First argument is self, second is the
162cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis               context.  More arguments can be given, those being after
163cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis               the explanation in _raise_error (For example,
164cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis               context._raise_error(NewError, '(-x)!', self._sign) would
165cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis               call NewError().handle(context, self._sign).)
166cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
1677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    To define a new exception, it should be sufficient to have it derive
1687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    from DecimalException.
1697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
1707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, *args):
1717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        pass
1727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Clamped(DecimalException):
1757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Exponent of a 0 changed to fit bounds.
1767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals clamped if the exponent of a result has been
1787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    altered in order to fit the constraints of a specific concrete
17959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    representation.  This may occur when the exponent of a zero result would
18059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    be outside the bounds of a representation, or when a large normal
18159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    number would have an encoded exponent that cannot be represented.  In
1827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    this latter case, the exponent is reduced to fit and the corresponding
1837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    number of zero digits are appended to the coefficient ("fold-down").
1847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
1857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass InvalidOperation(DecimalException):
1887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """An invalid operation was performed.
1897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Various bad things cause this:
1917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Something creates a signaling NaN
1937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    -INF + INF
19459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    0 * (+-)INF
19559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    (+-)INF / (+-)INF
1967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    x % 0
1977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    (+-)INF % x
1987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    x._rescale( non-integer )
1997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    sqrt(-x) , x > 0
2007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    0 ** 0
2017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    x ** (non-integer)
2027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    x ** (+-)INF
2037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    An operand is invalid
204353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
205353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    The result of the operation after these is a quiet positive NaN,
206353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    except when the cause is a signaling NaN, in which case the result is
207353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    also a quiet NaN, but with the original sign, and an optional
208353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    diagnostic information.
2097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
2107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, *args):
2117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if args:
21259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            if args[0] == 1:  # sNaN, must drop 's' but keep diagnostics
21372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(args[1]._sign, args[1]._int, 'n', True)
214353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return ans._fix_nan(context)
215353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            elif args[0] == 2:
21672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(args[1], args[2], 'n', True)
2177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return NaN
2187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
219353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass ConversionSyntax(InvalidOperation):
2217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Trying to convert badly formed string.
2227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals invalid-operation if an string is being
2247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    converted to a number and it does not conform to the numeric string
22559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    syntax.  The result is [0,qNaN].
2267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
227cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis    def handle(self, context, *args):
228353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return NaN
2297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass DivisionByZero(DecimalException, ZeroDivisionError):
2317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Division by 0.
2327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals division-by-zero if division of a finite number
2347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    by zero was attempted (during a divide-integer or divide operation, or a
2357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    power operation with negative right-hand operand), and the dividend was
2367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    not zero.
2377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The result of the operation is [sign,inf], where sign is the exclusive
2397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    or of the signs of the operands for divide, or is 1 for an odd power of
2407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    -0, for power.
2417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
242cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
243cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista    def handle(self, context, sign, *args):
2447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return Infsign[sign]
2457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass DivisionImpossible(InvalidOperation):
2477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Cannot perform the division adequately.
2487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals invalid-operation if the integer result of a
2507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    divide-integer or remainder operation had too many digits (would be
25159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    longer than precision).  The result is [0,qNaN].
2527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
253cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
2547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, *args):
255cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return NaN
2567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass DivisionUndefined(InvalidOperation, ZeroDivisionError):
2587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Undefined result of division.
2597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals invalid-operation if division by zero was
2617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    attempted (during a divide-integer, divide, or remainder operation), and
26259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    the dividend is also zero.  The result is [0,qNaN].
2637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
264cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
265cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista    def handle(self, context, *args):
2667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return NaN
2677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Inexact(DecimalException):
2697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Had to round, losing information.
2707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals inexact whenever the result of an operation is
2727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    not exact (that is, it needed to be rounded and any discarded digits
27359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    were non-zero), or if an overflow or underflow condition occurs.  The
2747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    result in all cases is unchanged.
2757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The inexact signal may be tested (or trapped) to determine if a given
2777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    operation (or sequence of operations) was inexact.
2787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
2795aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger    pass
2807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass InvalidContext(InvalidOperation):
2827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Invalid context.  Unknown rounding, for example.
2837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals invalid-operation if an invalid context was
28559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    detected during an operation.  This can occur if contexts are not checked
2867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    on creation and either the precision exceeds the capability of the
2877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    underlying concrete representation or an unknown or unsupported rounding
28859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    was specified.  These aspects of the context need only be checked when
28959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    the values are required to be used.  The result is [0,qNaN].
2907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
291cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
2927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, *args):
2937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return NaN
2947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Rounded(DecimalException):
2967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Number got rounded (not  necessarily changed during rounding).
2977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals rounded whenever the result of an operation is
2997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    rounded (that is, some zero or non-zero digits were discarded from the
30059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    coefficient), or if an overflow or underflow condition occurs.  The
3017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    result in all cases is unchanged.
3027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The rounded signal may be tested (or trapped) to determine if a given
3047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    operation (or sequence of operations) caused a loss of precision.
3057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
3065aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger    pass
3077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Subnormal(DecimalException):
3097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Exponent < Emin before rounding.
3107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals subnormal whenever the result of a conversion or
3127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    operation is subnormal (that is, its adjusted exponent is less than
31359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    Emin, before any rounding).  The result in all cases is unchanged.
3147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The subnormal signal may be tested (or trapped) to determine if a given
3167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    or operation (or sequence of operations) yielded a subnormal result.
3177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
3187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    pass
3197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Overflow(Inexact, Rounded):
3217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Numerical overflow.
3227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals overflow if the adjusted exponent of a result
3247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    (from a conversion or from an operation that is not an attempt to divide
3257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    by zero), after rounding, would be greater than the largest value that
3267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    can be handled by the implementation (the value Emax).
3277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The result depends on the rounding mode:
3297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    For round-half-up and round-half-even (and for round-half-down and
3317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    round-up, if implemented), the result of the operation is [sign,inf],
33259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    where sign is the sign of the intermediate result.  For round-down, the
3337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    result is the largest finite number that can be represented in the
33459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    current precision, with the sign of the intermediate result.  For
3357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    round-ceiling, the result is the same as for round-down if the sign of
33659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    the intermediate result is 1, or is [0,inf] otherwise.  For round-floor,
3377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    the result is the same as for round-down if the sign of the intermediate
33859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    result is 0, or is [1,inf] otherwise.  In all cases, Inexact and Rounded
3397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    will also be raised.
340cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis   """
341cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
3427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, sign, *args):
3437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
344353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                ROUND_HALF_DOWN, ROUND_UP):
3457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return Infsign[sign]
3467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if sign == 0:
3477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if context.rounding == ROUND_CEILING:
3487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return Infsign[sign]
34972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(sign, '9'*context.prec,
35072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                            context.Emax-context.prec+1)
3517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if sign == 1:
3527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if context.rounding == ROUND_FLOOR:
3537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return Infsign[sign]
35472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(sign, '9'*context.prec,
35572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                             context.Emax-context.prec+1)
3567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Underflow(Inexact, Rounded, Subnormal):
3597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Numerical underflow with result rounded to 0.
3607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals underflow if a result is inexact and the
3627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    adjusted exponent of the result would be smaller (more negative) than
3637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    the smallest value that can be handled by the implementation (the value
36459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    Emin).  That is, the result is both inexact and subnormal.
3657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The result after an underflow will be a subnormal number rounded, if
36759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    necessary, so that its exponent is not less than Etiny.  This may result
3687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    in 0 with the sign of the intermediate result and an exponent of Etiny.
3697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    In all cases, Inexact, Rounded, and Subnormal will also be raised.
3717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
3727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3735aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger# List of public traps and flags
374fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
375cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis           Underflow, InvalidOperation, Subnormal]
3767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3775aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger# Map conditions (per the spec) to signals
3785aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger_condition_map = {ConversionSyntax:InvalidOperation,
3795aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger                  DivisionImpossible:InvalidOperation,
3805aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger                  DivisionUndefined:InvalidOperation,
3815aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger                  InvalidContext:InvalidOperation}
3827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
38359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Context Functions ##################################################
3847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
385ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger# The getcontext() and setcontext() function manage access to a thread-local
386ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger# current context.  Py2.4 offers direct support for thread locals.  If that
387ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger# is not available, use threading.currentThread() which is slower but will
3887e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger# work for older Pythons.  If threads are not part of the build, create a
389cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis# mock threading object with threading.local() returning the module namespace.
3907e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger
3917e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettingertry:
3927e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    import threading
3937e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettingerexcept ImportError:
3947e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    # Python was compiled without threads; create a mock object instead
3957e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    import sys
39659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    class MockThreading(object):
3977e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger        def local(self, sys=sys):
3987e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger            return sys.modules[__name__]
3997e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    threading = MockThreading()
4007e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    del sys, MockThreading
401ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
402ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettingertry:
403ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    threading.local
404ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
405ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettingerexcept AttributeError:
406ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
40759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # To fix reloading, force it to create a new context
40859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # Old contexts have different exceptions in their dicts, making problems.
409ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    if hasattr(threading.currentThread(), '__decimal_context__'):
410ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        del threading.currentThread().__decimal_context__
411ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
412ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    def setcontext(context):
413ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """Set this thread's context to context."""
414ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        if context in (DefaultContext, BasicContext, ExtendedContext):
4159fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger            context = context.copy()
41661992efc4bb413ae7a19752215eca5af09be6b6dRaymond Hettinger            context.clear_flags()
4177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        threading.currentThread().__decimal_context__ = context
418ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
419ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    def getcontext():
420ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """Returns this thread's context.
421ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
422ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        If this thread does not yet have a context, returns
423ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        a new context and sets this thread's context.
424ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        New contexts are copies of DefaultContext.
425ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """
426ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        try:
427ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            return threading.currentThread().__decimal_context__
428ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        except AttributeError:
429ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            context = Context()
430ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            threading.currentThread().__decimal_context__ = context
431ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            return context
432ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
433ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettingerelse:
434ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
435ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    local = threading.local()
4369fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger    if hasattr(local, '__decimal_context__'):
4379fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        del local.__decimal_context__
438ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
439ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    def getcontext(_local=local):
440ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """Returns this thread's context.
441ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
442ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        If this thread does not yet have a context, returns
443ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        a new context and sets this thread's context.
444ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        New contexts are copies of DefaultContext.
445ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """
446ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        try:
447ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            return _local.__decimal_context__
448ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        except AttributeError:
449ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            context = Context()
450ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            _local.__decimal_context__ = context
451ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            return context
452ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
453ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    def setcontext(context, _local=local):
454ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """Set this thread's context to context."""
455ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        if context in (DefaultContext, BasicContext, ExtendedContext):
4569fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger            context = context.copy()
45761992efc4bb413ae7a19752215eca5af09be6b6dRaymond Hettinger            context.clear_flags()
458ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        _local.__decimal_context__ = context
459ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
460cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis    del threading, local        # Don't contaminate the namespace
4617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4628b6999b4c5fab174090be263ba90f193bdede141Nick Coghlandef localcontext(ctx=None):
4638b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """Return a context manager for a copy of the supplied context
4648b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan
4658b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    Uses a copy of the current context if no context is specified
4668b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    The returned context manager creates a local decimal context
4678b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    in a with statement:
4688b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan        def sin(x):
4698b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan             with localcontext() as ctx:
4708b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 ctx.prec += 2
4718b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # Rest of sin calculation algorithm
4728b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # uses a precision 2 greater than normal
47359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista             return +s  # Convert result to normal precision
4748b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan
4758b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan         def sin(x):
4768b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan             with localcontext(ExtendedContext):
4778b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # Rest of sin calculation algorithm
4788b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # uses the Extended Context from the
4798b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # General Decimal Arithmetic Specification
48059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista             return +s  # Convert result to normal context
4818b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan
4828b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """
483681d86743c21773bb00508dbacb05ed9012388d8Neal Norwitz    # The string below can't be included in the docstring until Python 2.6
4848b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    # as the doctest module doesn't understand __future__ statements
4858b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """
4868b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> from __future__ import with_statement
4878b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> print getcontext().prec
4888b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    28
4898b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> with localcontext():
4908b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...     ctx = getcontext()
491495df4716fce4156c1eb110f9342297164eecbb6Raymond Hettinger    ...     ctx.prec += 2
4928b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...     print ctx.prec
4938b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...
4948b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    30
4958b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> with localcontext(ExtendedContext):
4968b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...     print getcontext().prec
4978b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...
4988b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    9
4998b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> print getcontext().prec
5008b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    28
5018b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """
502ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlan    if ctx is None: ctx = getcontext()
503ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlan    return _ContextManager(ctx)
5048b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan
5057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
50659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Decimal class #######################################################
5077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
5087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Decimal(object):
5097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Floating point class for decimal arithmetic."""
5107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
511636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    __slots__ = ('_exp','_int','_sign', '_is_special')
512636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    # Generally, the value of the Decimal instance is given by
513636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    #  (-1)**_sign * _int * 10**_exp
514636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    # Special values are signified by _is_special == True
5157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
516dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger    # We're immutable, so use __new__ not __init__
517636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    def __new__(cls, value="0", context=None):
5187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Create a decimal point instance.
5197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
5207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        >>> Decimal('3.14')              # string input
5217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3.14")
52259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        >>> Decimal((0, (3, 1, 4), -2))  # tuple (sign, digit_tuple, exponent)
5237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3.14")
5247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        >>> Decimal(314)                 # int or long
5257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("314")
5267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        >>> Decimal(Decimal(314))        # another decimal instance
5277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("314")
5287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
5297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
53072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # Note that the coefficient, self._int, is actually stored as
53172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # a string rather than as a tuple of digits.  This speeds up
53272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # the "digits to integer" and "integer to digits" conversions
53372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # that are used in almost every arithmetic operation on
53472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # Decimals.  This is an internal detail: the as_tuple function
53572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # and the Decimal constructor still deal with tuples of
53672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # digits.
53772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista
538636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        self = object.__new__(cls)
539636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
5400d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        # From a string
5410d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        # REs insist on real strings, so we can too.
5420d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        if isinstance(value, basestring):
5430d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            m = _parser(value)
5440d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            if m is None:
5450d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                if context is None:
5460d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    context = getcontext()
5470d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                return context._raise_error(ConversionSyntax,
5480d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                                "Invalid literal for Decimal: %r" % value)
549636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
5500d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            if m.group('sign') == "-":
5510d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                self._sign = 1
5520d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            else:
5530d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                self._sign = 0
5540d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            intpart = m.group('int')
5550d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            if intpart is not None:
5560d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                # finite number
5570d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                fracpart = m.group('frac')
5580d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                exp = int(m.group('exp') or '0')
5590d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                if fracpart is not None:
5600d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    self._int = (intpart+fracpart).lstrip('0') or '0'
5610d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    self._exp = exp - len(fracpart)
5620d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                else:
5630d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    self._int = intpart.lstrip('0') or '0'
5640d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    self._exp = exp
5650d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                self._is_special = False
5660d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            else:
5670d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                diag = m.group('diag')
5680d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                if diag is not None:
5690d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    # NaN
5700d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    self._int = diag.lstrip('0')
5710d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    if m.group('signal'):
5720d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                        self._exp = 'N'
5730d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    else:
5740d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                        self._exp = 'n'
5750d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                else:
5760d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    # infinity
5770d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    self._int = '0'
5780d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    self._exp = 'F'
5790d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                self._is_special = True
580636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return self
581636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
582636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        # From an integer
5837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if isinstance(value, (int,long)):
584636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if value >= 0:
585636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                self._sign = 0
586636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            else:
587636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                self._sign = 1
588636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self._exp = 0
58972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self._int = str(abs(value))
5900d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._is_special = False
5910d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            return self
5920d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista
5930d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        # From another decimal
5940d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        if isinstance(value, Decimal):
5950d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._exp  = value._exp
5960d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._sign = value._sign
5970d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._int  = value._int
5980d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._is_special  = value._is_special
5990d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            return self
6000d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista
6010d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        # From an internal working value
6020d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        if isinstance(value, _WorkRep):
6030d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._sign = value.sign
6040d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._int = str(value.int)
6050d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._exp = int(value.exp)
6060d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            self._is_special = False
607636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return self
608636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
609636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        # tuple/list conversion (possibly from as_tuple())
610636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if isinstance(value, (list,tuple)):
611636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if len(value) != 3:
6129b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                raise ValueError('Invalid tuple size in creation of Decimal '
6139b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                 'from list or tuple.  The list or tuple '
6149b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                 'should have exactly three elements.')
6159b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista            # process sign.  The isinstance test rejects floats
6169b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista            if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
6179b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                raise ValueError("Invalid sign.  The first value in the tuple "
6189b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                 "should be an integer; either 0 for a "
6199b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                 "positive number or 1 for a negative number.")
620636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self._sign = value[0]
6219b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista            if value[2] == 'F':
6229b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                # infinity: value[1] is ignored
62372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                self._int = '0'
624636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                self._exp = value[2]
625636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                self._is_special = True
626636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            else:
6279b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                # process and validate the digits in value[1]
6289b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                digits = []
6299b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                for digit in value[1]:
6309b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    if isinstance(digit, (int, long)) and 0 <= digit <= 9:
6319b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                        # skip leading zeros
6329b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                        if digits or digit != 0:
6339b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                            digits.append(digit)
6349b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    else:
6359b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                        raise ValueError("The second value in the tuple must "
6369b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                         "be composed of integers in the range "
6379b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                         "0 through 9.")
6389b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                if value[2] in ('n', 'N'):
6399b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    # NaN: digits form the diagnostic
64072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                    self._int = ''.join(map(str, digits))
6419b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    self._exp = value[2]
6429b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    self._is_special = True
6439b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                elif isinstance(value[2], (int, long)):
6449b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    # finite number: digits give the coefficient
64572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                    self._int = ''.join(map(str, digits or [0]))
6469b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    self._exp = value[2]
6479b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    self._is_special = False
6489b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                else:
6499b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                    raise ValueError("The third value in the tuple must "
6509b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                     "be an integer, or one of the "
6519b5e23148badbb0d11fffd05cf9d432f35631a4aFacundo Batista                                     "strings 'F', 'n', 'N'.")
652636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return self
653636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
654636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if isinstance(value, float):
655636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            raise TypeError("Cannot convert float to Decimal.  " +
656636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                            "First convert the float to a string")
6577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
658636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        raise TypeError("Cannot convert %r to Decimal" % value)
6597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _isnan(self):
6617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns whether the number is not actually one.
6627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        0 if a number
664353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        1 if NaN  (it could be a normal quiet NaN or a phantom one)
6657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        2 if sNaN
6667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
667636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
668636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            exp = self._exp
669636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if exp == 'n':
670636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return 1
671636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            elif exp == 'N':
672636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return 2
6737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return 0
6747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _isinfinity(self):
6767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns whether the number is infinite
6777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        0 if finite or not a number
6797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        1 if +INF
6807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        -1 if -INF
6817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
6827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._exp == 'F':
6837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if self._sign:
6847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return -1
6857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return 1
6867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return 0
6877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
688353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _check_nans(self, other=None, context=None):
6897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns whether the number is not actually one.
6907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self, other are sNaN, signal
6927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self, other are NaN return nan
6937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return 0
6947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
6957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Done before operations.
6967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
6977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
698636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        self_is_nan = self._isnan()
699636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if other is None:
700636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            other_is_nan = False
701636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        else:
702636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            other_is_nan = other._isnan()
703636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
704636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self_is_nan or other_is_nan:
705636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if context is None:
706636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                context = getcontext()
707636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
708636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self_is_nan == 2:
709636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return context._raise_error(InvalidOperation, 'sNaN',
710636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                                        1, self)
711636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if other_is_nan == 2:
712636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return context._raise_error(InvalidOperation, 'sNaN',
713636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                                        1, other)
714636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self_is_nan:
715353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self._fix_nan(context)
716636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
717353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return other._fix_nan(context)
7187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return 0
7197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __nonzero__(self):
7211a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is nonzero; otherwise return False.
7227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7231a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        NaNs and infinities are considered nonzero.
7247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
72572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return self._is_special or self._int != '0'
7267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
727353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def __cmp__(self, other):
728636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
729267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
730353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # Never return NotImplemented
731353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return 1
7327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
733636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
734353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # check for nans, without raising on a signaling nan
735353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self._isnan() or other._isnan():
73659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                return 1  # Comparison involving NaN's always reports self > other
737636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
738636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            # INF = INF
739636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return cmp(self._isinfinity(), other._isinfinity())
7407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
741353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # check for zeros;  note that cmp(0, -0) should return 0
742353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
743353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if not other:
744353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return 0
745353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
746353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return -((-1)**other._sign)
747353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other:
748353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return (-1)**self._sign
7497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
75059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # If different signs, neg one is less
7517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if other._sign < self._sign:
7527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return -1
7537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign < other._sign:
7547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return 1
7557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
756636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        self_adjusted = self.adjusted()
757636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other_adjusted = other.adjusted()
758353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_adjusted == other_adjusted:
75972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self_padded = self._int + '0'*(self._exp - other._exp)
76072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            other_padded = other._int + '0'*(other._exp - self._exp)
761353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return cmp(self_padded, other_padded) * (-1)**self._sign
762353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif self_adjusted > other_adjusted:
7637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return (-1)**self._sign
764353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else: # self_adjusted < other_adjusted
7657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return -((-1)**self._sign)
7667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7670aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger    def __eq__(self, other):
7680aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger        if not isinstance(other, (Decimal, int, long)):
769267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return NotImplemented
7700aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger        return self.__cmp__(other) == 0
7710aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger
7720aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger    def __ne__(self, other):
7730aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger        if not isinstance(other, (Decimal, int, long)):
774267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return NotImplemented
7750aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger        return self.__cmp__(other) != 0
7760aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger
7777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def compare(self, other, context=None):
7787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Compares one to another.
7797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        -1 => a < b
7817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        0  => a = b
7827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        1  => a > b
7837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        NaN => one is NaN
7847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Like __cmp__, but returns Decimal instances.
7857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
786353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
7877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
78859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # Compare(NaN, NaN) = NaN
789636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if (self._is_special or other and other._is_special):
790636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
791636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
792636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
7937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
794353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal(self.__cmp__(other))
7957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __hash__(self):
7977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """x.__hash__() <==> hash(x)"""
7987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Decimal integers must hash the same as the ints
7997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Non-integer decimals are normalized and hashed as strings
8001fb9f528bd69efa135bacda917ec7bb166068d5dGeorg Brandl        # Normalization assures that hash(100E-1) == hash(10)
801bea3f6f5c788eb4f0f7639913ff89654152864c0Raymond Hettinger        if self._is_special:
802bea3f6f5c788eb4f0f7639913ff89654152864c0Raymond Hettinger            if self._isnan():
803bea3f6f5c788eb4f0f7639913ff89654152864c0Raymond Hettinger                raise TypeError('Cannot hash a NaN value.')
804bea3f6f5c788eb4f0f7639913ff89654152864c0Raymond Hettinger            return hash(str(self))
8058c202440699cef19602acc24822366d0d7c32083Facundo Batista        if not self:
8068c202440699cef19602acc24822366d0d7c32083Facundo Batista            return 0
8078c202440699cef19602acc24822366d0d7c32083Facundo Batista        if self._isinteger():
8088c202440699cef19602acc24822366d0d7c32083Facundo Batista            op = _WorkRep(self.to_integral_value())
8098c202440699cef19602acc24822366d0d7c32083Facundo Batista            # to make computation feasible for Decimals with large
8108c202440699cef19602acc24822366d0d7c32083Facundo Batista            # exponent, we use the fact that hash(n) == hash(m) for
8118c202440699cef19602acc24822366d0d7c32083Facundo Batista            # any two nonzero integers n and m such that (i) n and m
8128c202440699cef19602acc24822366d0d7c32083Facundo Batista            # have the same sign, and (ii) n is congruent to m modulo
8138c202440699cef19602acc24822366d0d7c32083Facundo Batista            # 2**64-1.  So we can replace hash((-1)**s*c*10**e) with
8148c202440699cef19602acc24822366d0d7c32083Facundo Batista            # hash((-1)**s*c*pow(10, e, 2**64-1).
8158c202440699cef19602acc24822366d0d7c32083Facundo Batista            return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
8167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return hash(str(self.normalize()))
8177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def as_tuple(self):
8197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Represents the number as a triple tuple.
8207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        To show the internals exactly as they are.
8227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
82372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return (self._sign, tuple(map(int, self._int)), self._exp)
8247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __repr__(self):
8267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Represents the number as an instance of Decimal."""
8277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Invariant:  eval(repr(d)) == d
8287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return 'Decimal("%s")' % str(self)
8297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
830353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def __str__(self, eng=False, context=None):
8317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return string representation of the number in scientific notation.
8327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Captures all of the information in the underlying representation.
8347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
8357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
83662edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        sign = ['', '-'][self._sign]
837e5a0a9609faea9afdc6f81f1f6dfa07b1437e3aeRaymond Hettinger        if self._is_special:
83862edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            if self._exp == 'F':
83962edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista                return sign + 'Infinity'
84062edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            elif self._exp == 'n':
84162edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista                return sign + 'NaN' + self._int
84262edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            else: # self._exp == 'N'
84362edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista                return sign + 'sNaN' + self._int
84462edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista
84562edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        # number of digits of self._int to left of decimal point
84662edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        leftdigits = self._exp + len(self._int)
84762edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista
84862edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        # dotplace is number of digits of self._int to the left of the
84962edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        # decimal point in the mantissa of the output string (that is,
85062edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        # after adjusting the exponent)
85162edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        if self._exp <= 0 and leftdigits > -6:
85262edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            # no exponent required
85362edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            dotplace = leftdigits
85462edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        elif not eng:
85562edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            # usual scientific notation: 1 digit on left of the point
8567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            dotplace = 1
85762edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        elif self._int == '0':
85862edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            # engineering notation, zero
85962edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            dotplace = (leftdigits + 1) % 3 - 1
8607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
86162edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            # engineering notation, nonzero
86262edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            dotplace = (leftdigits - 1) % 3 + 1
86362edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista
86462edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        if dotplace <= 0:
86562edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            intpart = '0'
86662edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            fracpart = '.' + '0'*(-dotplace) + self._int
86762edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        elif dotplace >= len(self._int):
86862edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            intpart = self._int+'0'*(dotplace-len(self._int))
86962edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            fracpart = ''
87062edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        else:
87162edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            intpart = self._int[:dotplace]
87262edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            fracpart = '.' + self._int[dotplace:]
87362edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        if leftdigits == dotplace:
87462edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            exp = ''
87562edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        else:
87662edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            if context is None:
87762edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista                context = getcontext()
87862edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
87962edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista
88062edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        return sign + intpart + fracpart + exp
8817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def to_eng_string(self, context=None):
8837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Convert to engineering-type string.
8847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Engineering notation has an exponent which is a multiple of 3, so there
8867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        are up to 3 digits left of the decimal place.
8877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Same rules for when in exponential and when as a value as in __str__.
8897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
890353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self.__str__(eng=True, context=context)
8917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __neg__(self, context=None):
8937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns a copy with the sign switched.
8947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Rounds, if it has reason.
8967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
897636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
898636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
899636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
900636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
9017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
9037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            # -Decimal('0') is Decimal('0'), not Decimal('-0')
904353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.copy_sign(Dec_0)
9057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
906353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.copy_negate()
907636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
908636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
909636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
910e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        return ans._fix(context)
9117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __pos__(self, context=None):
9137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns a copy, unless it is a sNaN.
9147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Rounds the number (if more then precision digits)
9167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
917636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
918636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
919636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
920636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
9217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
9237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            # + (-0) = 0
924353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.copy_sign(Dec_0)
925353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
926353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal(self)
9277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
928636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
929636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
930e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        return ans._fix(context)
9317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
932e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista    def __abs__(self, round=True, context=None):
9337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the absolute value of self.
9347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
935e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        If the keyword argument 'round' is false, do not round.  The
936e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        expression self.__abs__(round=False) is equivalent to
937e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        self.copy_abs().
9387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
939e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        if not round:
940e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            return self.copy_abs()
941e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista
942636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
943636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
944636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
945636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
9467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign:
9487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = self.__neg__(context=context)
9497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
9507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = self.__pos__(context=context)
9517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
9537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __add__(self, other, context=None):
9557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns self + other.
9567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        -INF + INF (or the reverse) cause InvalidOperation errors.
9587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
959636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
960267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
961267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
962636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
9637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
9647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
9657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
966636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
967636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
968636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
969636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
9707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
971636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity():
97259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                # If both INF, same sign => same as both, opposite => error.
973636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if self._sign != other._sign and other._isinfinity():
974636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    return context._raise_error(InvalidOperation, '-INF + INF')
975636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Decimal(self)
976636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if other._isinfinity():
97759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                return Decimal(other)  # Can't both be infinity here
9787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exp = min(self._exp, other._exp)
9807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        negativezero = 0
9817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context.rounding == ROUND_FLOOR and self._sign != other._sign:
98259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If the answer is 0, the sign should be negative, in this case.
9837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            negativezero = 1
9847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self and not other:
9867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            sign = min(self._sign, other._sign)
9877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if negativezero:
9887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                sign = 1
98972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(sign, '0', exp)
990e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            ans = ans._fix(context)
991353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
9927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
99399b5548298ffc2ae5f03bd9ef873ce45a9844f0eFacundo Batista            exp = max(exp, other._exp - context.prec-1)
994353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = other._rescale(exp, context.rounding)
995e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            ans = ans._fix(context)
9967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
9977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not other:
99899b5548298ffc2ae5f03bd9ef873ce45a9844f0eFacundo Batista            exp = max(exp, self._exp - context.prec-1)
999353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._rescale(exp, context.rounding)
1000e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            ans = ans._fix(context)
10017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
10027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        op1 = _WorkRep(self)
10047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        op2 = _WorkRep(other)
1005e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        op1, op2 = _normalize(op1, op2, context.prec)
10067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        result = _WorkRep()
10087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if op1.sign != op2.sign:
10097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            # Equal and opposite
101017931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            if op1.int == op2.int:
101172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(negativezero, '0', exp)
1012e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista                ans = ans._fix(context)
1013353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return ans
101417931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            if op1.int < op2.int:
10157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                op1, op2 = op2, op1
101659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                # OK, now abs(op1) > abs(op2)
101717931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            if op1.sign == 1:
101817931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger                result.sign = 1
10197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                op1.sign, op2.sign = op2.sign, op1.sign
10207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            else:
102117931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger                result.sign = 0
102259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                # So we know the sign, and op1 > 0.
102317931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        elif op1.sign == 1:
10247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            result.sign = 1
102517931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            op1.sign, op2.sign = (0, 0)
102617931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        else:
102717931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            result.sign = 0
102859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # Now, op1 > abs(op2) > 0
10297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
103017931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        if op2.sign == 0:
1031636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            result.int = op1.int + op2.int
10327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
1033636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            result.int = op1.int - op2.int
10347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        result.exp = op1.exp
10367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        ans = Decimal(result)
1037e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        ans = ans._fix(context)
10387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
10397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __radd__ = __add__
10417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __sub__(self, other, context=None):
1043353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return self - other"""
1044636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1045267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1046267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
10477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1048636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
1049636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context=context)
1050636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
1051636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
10527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1053353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self - other is computed as self + other.copy_negate()
1054353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self.__add__(other.copy_negate(), context=context)
10557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rsub__(self, other, context=None):
1057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return other - self"""
1058636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1059267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1060267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
10617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1062353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return other.__sub__(self, context=context)
10637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __mul__(self, other, context=None):
10657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return self * other.
10667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        (+-) INF * 0 (or its reverse) raise InvalidOperation.
10687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1069636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1070267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1071267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
1072636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
10737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
10747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
10757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1076d87ac8f24da5dce860b559b69e6af59edd2c3eecRaymond Hettinger        resultsign = self._sign ^ other._sign
10777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1078636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
1079636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
1080636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
1081636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
1082636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1083636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity():
1084636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if not other:
1085636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    return context._raise_error(InvalidOperation, '(+-)INF * 0')
1086636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Infsign[resultsign]
1087636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1088636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if other._isinfinity():
1089636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if not self:
1090636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    return context._raise_error(InvalidOperation, '0 * (+-)INF')
1091636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Infsign[resultsign]
10927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        resultexp = self._exp + other._exp
10947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Special case for multiplying by zero
10967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self or not other:
109772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(resultsign, '0', resultexp)
1098e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            # Fixing in case the exponent is out of bounds
1099e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            ans = ans._fix(context)
11007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
11017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Special case for multiplying by power of 10
110372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        if self._int == '1':
110472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(resultsign, other._int, resultexp)
1105e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            ans = ans._fix(context)
11067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
110772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        if other._int == '1':
110872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(resultsign, self._int, resultexp)
1109e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            ans = ans._fix(context)
11107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
11117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1112636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        op1 = _WorkRep(self)
1113636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        op2 = _WorkRep(other)
1114636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
111572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
1116e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        ans = ans._fix(context)
11177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
11197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __rmul__ = __mul__
11207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __div__(self, other, context=None):
11227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return self / other."""
1123636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1124267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1125cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return NotImplemented
1126636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
11277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
11287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
11297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1130636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        sign = self._sign ^ other._sign
1131636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1132636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
1133636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
1134636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
11357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return ans
11367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1137636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity() and other._isinfinity():
11387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
11397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if self._isinfinity():
1141636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Infsign[sign]
1142636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1143636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if other._isinfinity():
1144636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                context._raise_error(Clamped, 'Division by infinity')
114572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(sign, '0', context.Etiny())
1146636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1147636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        # Special cases for zeroes
1148636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if not other:
1149cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if not self:
1150cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(DivisionUndefined, '0 / 0')
1151636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return context._raise_error(DivisionByZero, 'x / 0', sign)
11527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1153cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if not self:
1154cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            exp = self._exp - other._exp
1155cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            coeff = 0
1156cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        else:
1157cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            # OK, so neither = 0, INF or NaN
1158cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            shift = len(other._int) - len(self._int) + context.prec + 1
1159cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            exp = self._exp - other._exp - shift
1160cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            op1 = _WorkRep(self)
1161cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            op2 = _WorkRep(other)
1162cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if shift >= 0:
1163cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1164cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1165cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1166cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if remainder:
1167cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                # result is not exact; adjust to ensure correct rounding
1168cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                if coeff % 5 == 0:
1169cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                    coeff += 1
1170cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1171cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                # result is exact; get as close to ideal exponent as possible
1172cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                ideal_exp = self._exp - other._exp
1173cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                while exp < ideal_exp and coeff % 10 == 0:
1174cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                    coeff //= 10
1175cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                    exp += 1
11767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
117772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        ans = _dec_from_triple(sign, str(coeff), exp)
1178cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return ans._fix(context)
11797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1180cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista    __truediv__ = __div__
11817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1182cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista    def _divide(self, other, context):
1183cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        """Return (self // other, self % other), to context.prec precision.
11847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1185cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        Assumes that neither self nor other is a NaN, that self is not
1186cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        infinite and that other is nonzero.
1187cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        """
1188cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        sign = self._sign ^ other._sign
1189cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if other._isinfinity():
1190cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            ideal_exp = self._exp
1191cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        else:
1192cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            ideal_exp = min(self._exp, other._exp)
11937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1194cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        expdiff = self.adjusted() - other.adjusted()
1195cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if not self or other._isinfinity() or expdiff <= -2:
119672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return (_dec_from_triple(sign, '0', 0),
1197cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                    self._rescale(ideal_exp, context.rounding))
1198cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if expdiff <= context.prec:
1199cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            op1 = _WorkRep(self)
1200cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            op2 = _WorkRep(other)
1201cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if op1.exp >= op2.exp:
1202cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                op1.int *= 10**(op1.exp - op2.exp)
1203cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1204cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                op2.int *= 10**(op2.exp - op1.exp)
1205cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            q, r = divmod(op1.int, op2.int)
1206cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if q < 10**context.prec:
120772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return (_dec_from_triple(sign, str(q), 0),
120872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                        _dec_from_triple(self._sign, str(r), ideal_exp))
12097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1210cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        # Here the quotient is too large to be representable
1211cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        ans = context._raise_error(DivisionImpossible,
1212cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                                   'quotient too large in //, % or divmod')
1213cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return ans, ans
12147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rdiv__(self, other, context=None):
12167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Swaps self/other and returns __div__."""
1217636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1218267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1219267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
12207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return other.__div__(self, context=context)
12217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __rtruediv__ = __rdiv__
12227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __divmod__(self, other, context=None):
12247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1225cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        Return (self // other, self % other)
12267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1227cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        other = _convert_other(other)
1228cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if other is NotImplemented:
1229cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return other
1230cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1231cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if context is None:
1232cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            context = getcontext()
1233cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1234cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        ans = self._check_nans(other, context)
1235cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if ans:
1236cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return (ans, ans)
1237cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1238cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        sign = self._sign ^ other._sign
1239cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if self._isinfinity():
1240cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if other._isinfinity():
1241cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1242cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return ans, ans
1243cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1244cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return (Infsign[sign],
1245cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                        context._raise_error(InvalidOperation, 'INF % x'))
1246cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1247cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if not other:
1248cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if not self:
1249cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1250cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return ans, ans
1251cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1252cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return (context._raise_error(DivisionByZero, 'x // 0', sign),
1253cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                        context._raise_error(InvalidOperation, 'x % 0'))
1254cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1255cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        quotient, remainder = self._divide(other, context)
1256e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        remainder = remainder._fix(context)
1257cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return quotient, remainder
12587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rdivmod__(self, other, context=None):
12607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Swaps self/other and returns __divmod__."""
1261636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1262267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1263267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
12647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return other.__divmod__(self, context=context)
12657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __mod__(self, other, context=None):
12677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
12687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self % other
12697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1270636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1271267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1272267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
12737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1274cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if context is None:
1275cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            context = getcontext()
12767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1277cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        ans = self._check_nans(other, context)
1278cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if ans:
1279cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return ans
12807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1281cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if self._isinfinity():
1282cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return context._raise_error(InvalidOperation, 'INF % x')
1283cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        elif not other:
1284cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if self:
1285cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(InvalidOperation, 'x % 0')
1286cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1287cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(DivisionUndefined, '0 % 0')
1288cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1289cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        remainder = self._divide(other, context)[1]
1290e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        remainder = remainder._fix(context)
1291cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return remainder
12927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rmod__(self, other, context=None):
12947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Swaps self/other and returns __mod__."""
1295636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1296267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1297267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
12987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return other.__mod__(self, context=context)
12997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def remainder_near(self, other, context=None):
13017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
13027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Remainder nearest to 0-  abs(remainder-near) <= other/2
13037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1304636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
1305636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
13067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1307353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
13087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1309353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
1310353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
1311353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
13127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1313353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self == +/-infinity -> InvalidOperation
1314353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
1315353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1316353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'remainder_near(infinity, x)')
13177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1318353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # other == 0 -> either InvalidOperation or DivisionUndefined
1319353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other:
1320353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self:
1321353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation,
1322353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                            'remainder_near(x, 0)')
1323353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1324353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(DivisionUndefined,
1325353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                            'remainder_near(0, 0)')
13267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1327353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # other = +/-infinity -> remainder = self
1328353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._isinfinity():
1329353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal(self)
1330353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
13317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1332353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self = 0 -> remainder = self, with ideal exponent
1333353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ideal_exponent = min(self._exp, other._exp)
1334353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
133572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(self._sign, '0', ideal_exponent)
1336353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
13377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1338353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # catch most cases of large or small quotient
1339353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        expdiff = self.adjusted() - other.adjusted()
1340353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if expdiff >= context.prec + 1:
1341353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # expdiff >= prec+1 => abs(self/other) > 10**prec
1342cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return context._raise_error(DivisionImpossible)
1343353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if expdiff <= -2:
1344353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # expdiff <= -2 => abs(self/other) < 0.1
1345353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._rescale(ideal_exponent, context.rounding)
1346353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
13477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1348353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # adjust both arguments to have the same exponent, then divide
1349353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op1 = _WorkRep(self)
1350353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op2 = _WorkRep(other)
1351353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if op1.exp >= op2.exp:
1352353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            op1.int *= 10**(op1.exp - op2.exp)
13537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
1354353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            op2.int *= 10**(op2.exp - op1.exp)
1355353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        q, r = divmod(op1.int, op2.int)
1356353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # remainder is r*10**ideal_exponent; other is +/-op2.int *
1357353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 10**ideal_exponent.   Apply correction to ensure that
1358353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # abs(remainder) <= abs(other)/2
1359353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if 2*r + (q&1) > op2.int:
1360353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            r -= op2.int
1361353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            q += 1
1362353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1363353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if q >= 10**context.prec:
1364cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return context._raise_error(DivisionImpossible)
1365353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1366353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # result has same sign as self unless r is negative
1367353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        sign = self._sign
1368353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if r < 0:
1369353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sign = 1-sign
1370353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            r = -r
13717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
137272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        ans = _dec_from_triple(sign, str(r), ideal_exponent)
1373353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans._fix(context)
13747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __floordiv__(self, other, context=None):
13767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """self // other"""
1377cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        other = _convert_other(other)
1378cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if other is NotImplemented:
1379cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return other
1380cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1381cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if context is None:
1382cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            context = getcontext()
1383cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1384cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        ans = self._check_nans(other, context)
1385cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if ans:
1386cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return ans
1387cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1388cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if self._isinfinity():
1389cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if other._isinfinity():
1390cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(InvalidOperation, 'INF // INF')
1391cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1392cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return Infsign[self._sign ^ other._sign]
1393cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1394cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if not other:
1395cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if self:
1396cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(DivisionByZero, 'x // 0',
1397cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                                            self._sign ^ other._sign)
1398cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1399cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(DivisionUndefined, '0 // 0')
1400cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1401cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return self._divide(other, context)[0]
14027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rfloordiv__(self, other, context=None):
14047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Swaps self/other and returns __floordiv__."""
1405636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1406267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1407267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
14087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return other.__floordiv__(self, context=context)
14097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __float__(self):
14117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Float representation."""
14127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return float(str(self))
14137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __int__(self):
141546b0802ccd9a9c47b27a285526fbb2a8bee5b8cbBrett Cannon        """Converts self to an int, truncating if necessary."""
1416636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
1417636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isnan():
1418636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                context = getcontext()
1419636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return context._raise_error(InvalidContext)
1420636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            elif self._isinfinity():
142159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                raise OverflowError("Cannot convert infinity to long")
1422353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        s = (-1)**self._sign
14237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._exp >= 0:
142472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return s*int(self._int)*10**self._exp
1425605ed0248375bbf87bbd1d80afc7c6918fd3ce2bRaymond Hettinger        else:
142672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return s*int(self._int[:self._exp] or '0')
14277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __long__(self):
14297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Converts to a long.
14307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Equivalent to long(int(self))
14327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
14337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return long(self.__int__())
14347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1435353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _fix_nan(self, context):
1436353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Decapitate the payload of a NaN to fit the context"""
1437353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        payload = self._int
1438353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1439353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # maximum length of payload is precision if _clamp=0,
1440353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # precision-1 if _clamp=1.
1441353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        max_payload_len = context.prec - context._clamp
1442353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if len(payload) > max_payload_len:
144372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            payload = payload[len(payload)-max_payload_len:].lstrip('0')
144472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(self._sign, payload, self._exp, True)
14456c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        return Decimal(self)
1446353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1447dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger    def _fix(self, context):
14487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Round if it is necessary to keep self within prec precision.
14497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Rounds and fixes the exponent.  Does not raise on a sNaN.
14517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Arguments:
14537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self - Decimal instance
14547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        context - context used.
14557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1456636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
14577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
14587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
14597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1460353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
1461353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self._isnan():
1462353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # decapitate payload if necessary
1463353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self._fix_nan(context)
1464353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1465353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # self is +/-Infinity; return unaltered
14666c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                return Decimal(self)
14677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1468353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if self is zero then exponent should be between Etiny and
1469353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1470353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Etiny = context.Etiny()
1471353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Etop = context.Etop()
14727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
1473353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            exp_max = [context.Emax, Etop][context._clamp]
1474353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            new_exp = min(max(self._exp, Etiny), exp_max)
1475353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if new_exp != self._exp:
1476353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Clamped)
147772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(self._sign, '0', new_exp)
14787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            else:
14796c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                return Decimal(self)
14807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1481353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp_min is the smallest allowable exponent of the result,
1482353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # equal to max(self.adjusted()-context.prec+1, Etiny)
1483353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exp_min = len(self._int) + self._exp - context.prec
1484353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if exp_min > Etop:
1485353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # overflow: exp_min > Etop iff self.adjusted() > Emax
1486353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
1487353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Rounded)
1488353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(Overflow, 'above Emax', self._sign)
1489353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_is_subnormal = exp_min < Etiny
1490353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_is_subnormal:
1491353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Subnormal)
1492353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            exp_min = Etiny
14937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1494353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # round if self has too many digits
1495353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp < exp_min:
14967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context._raise_error(Rounded)
14972ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            digits = len(self._int) + self._exp - exp_min
14982ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            if digits < 0:
14992ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista                self = _dec_from_triple(self._sign, '1', exp_min-1)
15002ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista                digits = 0
15012ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            this_function = getattr(self, self._pick_rounding_function[context.rounding])
15022ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            changed = this_function(digits)
15032ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            coeff = self._int[:digits] or '0'
15042ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            if changed == 1:
15052ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista                coeff = str(int(coeff)+1)
15062ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            ans = _dec_from_triple(self._sign, coeff, exp_min)
15072ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista
15082ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            if changed:
1509353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Inexact)
1510353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_is_subnormal:
1511353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    context._raise_error(Underflow)
1512353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if not ans:
1513353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        # raise Clamped on underflow to 0
1514353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        context._raise_error(Clamped)
1515353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                elif len(ans._int) == context.prec+1:
1516353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    # we get here only if rescaling rounds the
1517353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    # cofficient up to exactly 10**context.prec
1518353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if ans._exp < Etop:
151972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                        ans = _dec_from_triple(ans._sign,
152072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                                   ans._int[:-1], ans._exp+1)
1521353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    else:
1522353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        # Inexact and Rounded have already been raised
1523353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        ans = context._raise_error(Overflow, 'above Emax',
1524353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                                   self._sign)
15257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
15267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1527353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # fold down if _clamp == 1 and self has too few digits
1528353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context._clamp == 1 and self._exp > Etop:
1529353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Clamped)
153072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self_padded = self._int + '0'*(self._exp - Etop)
153172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(self._sign, self_padded, Etop)
15327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1533353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # here self was representable to begin with; return unchanged
15346c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        return Decimal(self)
15357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
15367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    _pick_rounding_function = {}
15377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1538353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # for each of the rounding functions below:
1539353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #   self is a finite, nonzero Decimal
1540353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #   prec is an integer satisfying 0 <= prec < len(self._int)
15412ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    #
15422ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    # each function returns either -1, 0, or 1, as follows:
15432ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    #   1 indicates that self should be rounded up (away from zero)
15442ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    #   0 indicates that self should be truncated, and that all the
15452ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    #     digits to be truncated are zeros (so the value is unchanged)
15462ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    #  -1 indicates that there are nonzero digits to be truncated
15477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1548353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_down(self, prec):
1549353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Also known as round-towards-0, truncate."""
15502ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        if _all_zeros(self._int, prec):
15512ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return 0
15522ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        else:
15532ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -1
15547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1555353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_up(self, prec):
1556353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds away from 0."""
15572ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        return -self._round_down(prec)
15587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1559353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_half_up(self, prec):
1560353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds 5 up (away from 0)"""
156172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        if self._int[prec] in '56789':
15622ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return 1
15632ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        elif _all_zeros(self._int, prec):
15642ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return 0
1565353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
15662ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -1
15677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1568353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_half_down(self, prec):
15697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Round 5 down"""
15702ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        if _exact_half(self._int, prec):
15712ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -1
15722ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        else:
15732ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return self._round_half_up(prec)
15747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1575353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_half_even(self, prec):
1576353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Round 5 to even, rest to nearest."""
15772ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        if _exact_half(self._int, prec) and \
15782ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista                (prec == 0 or self._int[prec-1] in '02468'):
15792ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -1
1580353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
15812ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return self._round_half_up(prec)
15827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1583353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_ceiling(self, prec):
15847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Rounds up (not away from 0 if negative.)"""
15857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign:
1586353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_down(prec)
15877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
15882ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -self._round_down(prec)
15897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1590353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_floor(self, prec):
15917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Rounds down (not towards 0 if negative)"""
15927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self._sign:
1593353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_down(prec)
15947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
15952ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -self._round_down(prec)
15967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1597353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_05up(self, prec):
1598353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Round down unless digit prec-1 is 0 or 5."""
15992ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        if prec and self._int[prec-1] not in '05':
1600353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_down(prec)
16012ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        else:
16022ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -self._round_down(prec)
1603353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1604353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def fma(self, other, third, context=None):
1605353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Fused multiply-add.
16067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1607353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Returns self*other+third with no rounding of the intermediate
1608353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        product self*other.
1609353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1610353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self and other are multiplied together, with no rounding of
1611353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        the result.  The third operand is then added to the result,
1612353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        and a single final rounding is performed.
16137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1614353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1615353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
16167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
161758f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista        # compute product; raise InvalidOperation if either operand is
161858f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista        # a signaling NaN or if the product is zero times infinity.
161958f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista        if self._is_special or other._is_special:
162058f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            if context is None:
162158f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                context = getcontext()
162258f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            if self._exp == 'N':
162358f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                return context._raise_error(InvalidOperation, 'sNaN',
162458f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                                        1, self)
162558f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            if other._exp == 'N':
162658f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                return context._raise_error(InvalidOperation, 'sNaN',
162758f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                                        1, other)
162858f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            if self._exp == 'n':
162958f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                product = self
163058f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            elif other._exp == 'n':
163158f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                product = other
163258f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            elif self._exp == 'F':
163358f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                if not other:
163458f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                    return context._raise_error(InvalidOperation,
163558f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                                                'INF * 0 in fma')
163658f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                product = Infsign[self._sign ^ other._sign]
163758f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            elif other._exp == 'F':
163858f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                if not self:
163958f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                    return context._raise_error(InvalidOperation,
164058f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                                                '0 * INF in fma')
164158f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                product = Infsign[self._sign ^ other._sign]
164258f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista        else:
164358f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            product = _dec_from_triple(self._sign ^ other._sign,
164458f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                                       str(int(self._int) * int(other._int)),
164558f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                                       self._exp + other._exp)
16467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
164758f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista        third = _convert_other(third, raiseit=True)
164858f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista        return product.__add__(third, context)
16497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1650353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _power_modulo(self, other, modulo, context=None):
1651353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Three argument version of __pow__"""
16527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1653353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if can't convert other and modulo to Decimal, raise
1654353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # TypeError; there's no point returning NotImplemented (no
1655353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # equivalent of __rpow__ for three argument pow)
1656353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
1657353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        modulo = _convert_other(modulo, raiseit=True)
16587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1659353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
1660353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
16617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1662353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # deal with NaNs: if there are any sNaNs then first one wins,
1663353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (i.e. behaviour for NaNs is identical to that of fma)
1664353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_is_nan = self._isnan()
1665353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other_is_nan = other._isnan()
1666353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        modulo_is_nan = modulo._isnan()
1667353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_is_nan or other_is_nan or modulo_is_nan:
1668353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self_is_nan == 2:
1669353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation, 'sNaN',
1670353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, self)
1671353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other_is_nan == 2:
1672353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation, 'sNaN',
1673353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, other)
1674353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if modulo_is_nan == 2:
1675353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation, 'sNaN',
1676353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, modulo)
1677353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self_is_nan:
16786c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                return self._fix_nan(context)
1679353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other_is_nan:
16806c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                return other._fix_nan(context)
16816c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return modulo._fix_nan(context)
1682353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1683353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # check inputs: we apply same restrictions as Python's pow()
1684353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (self._isinteger() and
1685353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                other._isinteger() and
1686353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                modulo._isinteger()):
1687353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1688353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'pow() 3rd argument not allowed '
1689353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'unless all arguments are integers')
1690353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other < 0:
1691353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1692353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'pow() 2nd argument cannot be '
1693353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'negative when 3rd argument specified')
1694353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not modulo:
1695353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1696353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'pow() 3rd argument cannot be 0')
1697353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1698353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # additional restriction for decimal: the modulus must be less
1699353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # than 10**prec in absolute value
1700353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if modulo.adjusted() >= context.prec:
1701353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1702353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'insufficient precision: pow() 3rd '
1703353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'argument must not have more than '
1704353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'precision digits')
1705353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1706353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # define 0**0 == NaN, for consistency with two-argument pow
1707353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (even though it hurts!)
1708353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other and not self:
1709353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1710353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'at least one of pow() 1st argument '
1711353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'and 2nd argument must be nonzero ;'
1712353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        '0**0 is not defined')
1713353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1714353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute sign of result
1715353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._iseven():
1716353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sign = 0
1717353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
1718353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sign = self._sign
1719353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1720353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # convert modulo to a Python integer, and self and other to
1721353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Decimal integers (i.e. force their exponents to be >= 0)
1722353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        modulo = abs(int(modulo))
1723353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        base = _WorkRep(self.to_integral_value())
1724353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exponent = _WorkRep(other.to_integral_value())
1725353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1726353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute result using integer pow()
1727353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1728353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        for i in xrange(exponent.exp):
1729353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            base = pow(base, 10, modulo)
1730353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        base = pow(base, exponent.int, modulo)
1731353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
173272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(sign, str(base), 0)
1733353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1734353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _power_exact(self, other, p):
1735353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Attempt to compute self**other exactly.
1736353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1737353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Given Decimals self and other and an integer p, attempt to
1738353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        compute an exact result for the power self**other, with p
1739353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        digits of precision.  Return None if self**other is not
1740353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exactly representable in p digits.
1741353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1742353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Assumes that elimination of special cases has already been
1743353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        performed: self and other must both be nonspecial; self must
1744353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        be positive and not numerically equal to 1; other must be
1745353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        nonzero.  For efficiency, other._exp should not be too large,
1746353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        so that 10**abs(other._exp) is a feasible calculation."""
1747353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1748353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # In the comments below, we write x for the value of self and
1749353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # y for the value of other.  Write x = xc*10**xe and y =
1750353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # yc*10**ye.
1751353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1752353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # The main purpose of this method is to identify the *failure*
1753353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # of x**y to be exactly representable with as little effort as
1754353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # possible.  So we look for cheap and easy tests that
1755353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # eliminate the possibility of x**y being exact.  Only if all
1756353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # these tests are passed do we go on to actually compute x**y.
1757353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1758353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Here's the main idea.  First normalize both x and y.  We
1759353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # express y as a rational m/n, with m and n relatively prime
1760353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # and n>0.  Then for x**y to be exactly representable (at
1761353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # *any* precision), xc must be the nth power of a positive
1762353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # integer and xe must be divisible by n.  If m is negative
1763353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # then additionally xc must be a power of either 2 or 5, hence
1764353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # a power of 2**n or 5**n.
1765353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1766353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # There's a limit to how small |y| can be: if y=m/n as above
1767353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # then:
1768353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1769353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #  (1) if xc != 1 then for the result to be representable we
1770353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      need xc**(1/n) >= 2, and hence also xc**|y| >= 2.  So
1771353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1772353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      2**(1/|y|), hence xc**|y| < 2 and the result is not
1773353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      representable.
1774353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1775353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #  (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1.  Hence if
1776353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      |y| < 1/|xe| then the result is not representable.
1777353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1778353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Note that since x is not equal to 1, at least one of (1) and
1779353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (2) must apply.  Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1780353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1781353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1782353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # There's also a limit to how large y can be, at least if it's
1783353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # positive: the normalized result will have coefficient xc**y,
1784353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # so if it's representable then xc**y < 10**p, and y <
1785353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # p/log10(xc).  Hence if y*log10(xc) >= p then the result is
1786353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # not exactly representable.
1787353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1788353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1789353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # so |y| < 1/xe and the result is not representable.
1790353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1791353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # < 1/nbits(xc).
1792353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1793353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        x = _WorkRep(self)
1794353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        xc, xe = x.int, x.exp
1795353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while xc % 10 == 0:
1796353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xc //= 10
1797353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xe += 1
1798353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1799353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        y = _WorkRep(other)
1800353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        yc, ye = y.int, y.exp
1801353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while yc % 10 == 0:
1802353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            yc //= 10
1803353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ye += 1
1804353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1805353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # case where xc == 1: result is 10**(xe*y), with xe*y
1806353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # required to be an integer
1807353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if xc == 1:
1808353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ye >= 0:
1809353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exponent = xe*yc*10**ye
1810353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1811353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exponent, remainder = divmod(xe*yc, 10**-ye)
1812353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if remainder:
1813353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1814353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if y.sign == 1:
1815353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exponent = -exponent
1816353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # if other is a nonnegative integer, use ideal exponent
1817353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._isinteger() and other._sign == 0:
1818353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                ideal_exponent = self._exp*int(other)
1819353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                zeros = min(exponent-ideal_exponent, p-1)
1820353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1821353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                zeros = 0
182272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
1823353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1824353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # case where y is negative: xc must be either a power
1825353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # of 2 or a power of 5.
1826353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if y.sign == 1:
1827353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            last_digit = xc % 10
1828353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if last_digit in (2,4,6,8):
1829353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # quick test for power of 2
1830353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if xc & -xc != xc:
1831353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1832353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # now xc is a power of 2; e is its exponent
1833353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                e = _nbits(xc)-1
1834353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # find e*y and xe*y; both must be integers
1835353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if ye >= 0:
1836353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    y_as_int = yc*10**ye
1837353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e = e*y_as_int
1838353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xe = xe*y_as_int
1839353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                else:
1840353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    ten_pow = 10**-ye
1841353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e, remainder = divmod(e*yc, ten_pow)
1842353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if remainder:
1843353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return None
1844353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xe, remainder = divmod(xe*yc, ten_pow)
1845353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if remainder:
1846353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return None
1847353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1848353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if e*65 >= p*93: # 93/65 > log(10)/log(5)
1849353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1850353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                xc = 5**e
1851353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1852353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            elif last_digit == 5:
1853353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # e >= log_5(xc) if xc is a power of 5; we have
1854353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # equality all the way up to xc=5**2658
1855353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                e = _nbits(xc)*28//65
1856353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                xc, remainder = divmod(5**e, xc)
1857353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if remainder:
1858353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1859353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                while xc % 5 == 0:
1860353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xc //= 5
1861353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e -= 1
1862353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if ye >= 0:
1863353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    y_as_integer = yc*10**ye
1864353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e = e*y_as_integer
1865353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xe = xe*y_as_integer
1866353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                else:
1867353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    ten_pow = 10**-ye
1868353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e, remainder = divmod(e*yc, ten_pow)
1869353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if remainder:
1870353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return None
1871353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xe, remainder = divmod(xe*yc, ten_pow)
1872353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if remainder:
1873353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return None
1874353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if e*3 >= p*10: # 10/3 > log(10)/log(2)
1875353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1876353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                xc = 2**e
1877353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1878353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
18797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1880353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if xc >= 10**p:
1881353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1882353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xe = -e-xe
188372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(0, str(xc), xe)
18847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1885353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # now y is positive; find m and n such that y = m/n
1886353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ye >= 0:
1887353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            m, n = yc*10**ye, 1
1888353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
1889353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1890353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1891353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xc_bits = _nbits(xc)
1892353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1893353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1894353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            m, n = yc, 10**(-ye)
1895353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while m % 2 == n % 2 == 0:
1896353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                m //= 2
1897353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n //= 2
1898353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while m % 5 == n % 5 == 0:
1899353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                m //= 5
1900353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n //= 5
1901353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1902353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute nth root of xc*10**xe
1903353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if n > 1:
1904353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # if 1 < xc < 2**n then xc isn't an nth power
1905353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if xc != 1 and xc_bits <= n:
1906353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1907353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1908353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xe, rem = divmod(xe, n)
1909353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if rem != 0:
1910353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1911353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1912353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # compute nth root of xc using Newton's method
1913353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            a = 1L << -(-_nbits(xc)//n) # initial estimate
1914353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while True:
1915353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                q, r = divmod(xc, a**(n-1))
1916353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if a <= q:
1917353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
1918353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                else:
1919353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    a = (a*(n-1) + q)//n
1920353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if not (a == q and r == 0):
1921353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1922353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xc = a
1923353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1924353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # now xc*10**xe is the nth root of the original xc*10**xe
1925353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute mth power of xc*10**xe
1926353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1927353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1928353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 10**p and the result is not representable.
1929353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if xc > 1 and m > p*100//_log10_lb(xc):
1930353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return None
1931353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        xc = xc**m
1932353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        xe *= m
1933353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if xc > 10**p:
1934353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return None
1935353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1936353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # by this point the result *is* exactly representable
1937353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # adjust the exponent to get as close as possible to the ideal
1938353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exponent, if necessary
1939353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        str_xc = str(xc)
1940353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._isinteger() and other._sign == 0:
1941353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ideal_exponent = self._exp*int(other)
1942353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            zeros = min(xe-ideal_exponent, p-len(str_xc))
1943353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
1944353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            zeros = 0
194572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
1946cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
1947353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def __pow__(self, other, modulo=None, context=None):
1948353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return self ** other [ % modulo].
19497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1950353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        With two arguments, compute self**other.
19517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1952353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        With three arguments, compute (self**other) % modulo.  For the
1953353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        three argument form, the following restrictions on the
1954353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        arguments hold:
19557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1956353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - all three arguments must be integral
1957353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - other must be nonnegative
1958353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - either self or other (or both) must be nonzero
1959353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - modulo must be nonzero and must have at most p digits,
1960353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista           where p is the context precision.
19617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1962353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        If any of these restrictions is violated the InvalidOperation
1963353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        flag is raised.
1964353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1965353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result of pow(self, other, modulo) is identical to the
1966353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        result that would be obtained by computing (self**other) %
1967353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        modulo with unbounded precision, but is computed more
1968353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        efficiently.  It is always exact.
1969353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
1970353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1971353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if modulo is not None:
1972353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._power_modulo(other, modulo, context)
19737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1974636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1975267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1976267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
19777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1978353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
1979353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
19807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1981353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # either argument is a NaN => result is NaN
1982353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
1983353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
1984353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
19857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1986353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
1987353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other:
1988353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if not self:
1989353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation, '0 ** 0')
1990353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1991353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_p1
19927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1993353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # result has sign 1 iff self._sign is 1 and other is an odd integer
1994353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        result_sign = 0
1995353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign == 1:
1996353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._isinteger():
1997353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if not other._iseven():
1998353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    result_sign = 1
1999353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2000353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # -ve**noninteger = NaN
2001353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # (-0)**noninteger = 0**noninteger
2002353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self:
2003353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return context._raise_error(InvalidOperation,
2004353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        'x ** y with x negative and y not an integer')
2005353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # negate self, without doing any unwanted rounding
200672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self = self.copy_negate()
2007353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2008353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2009353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2010353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._sign == 0:
201172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(result_sign, '0', 0)
2012353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2013353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Infsign[result_sign]
2014353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2015353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
2016353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
2017353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._sign == 0:
2018353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Infsign[result_sign]
2019353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
202072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(result_sign, '0', 0)
2021353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2022353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 1**other = 1, but the choice of exponent and the flags
2023353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # depend on the exponent of self, and on whether other is a
2024353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # positive integer, a negative integer, or neither
2025353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self == Dec_p1:
2026353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._isinteger():
2027353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # exp = max(self._exp*max(int(other), 0),
2028353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # 1-context.prec) but evaluating int(other) directly
2029353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # is dangerous until we know other is small (other
2030353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # could be 1e999999999)
2031353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other._sign == 1:
2032353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    multiplier = 0
2033353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                elif other > context.prec:
2034353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    multiplier = context.prec
2035353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                else:
2036353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    multiplier = int(other)
2037353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2038353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exp = self._exp * multiplier
2039353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if exp < 1-context.prec:
2040353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    exp = 1-context.prec
2041353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    context._raise_error(Rounded)
2042353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2043353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Inexact)
2044353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Rounded)
2045353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exp = 1-context.prec
2046353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
204772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
2048353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2049353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute adjusted exponent of self
2050353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_adj = self.adjusted()
2051353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2052353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self ** infinity is infinity if self > 1, 0 if self < 1
2053353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self ** -infinity is infinity if self < 1, 0 if self > 1
2054353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._isinfinity():
2055353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if (other._sign == 0) == (self_adj < 0):
205672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(result_sign, '0', 0)
2057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2058353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Infsign[result_sign]
2059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2060353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # from here on, the result always goes through the call
2061353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # to _fix at the end of this function.
2062353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = None
2063353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2064353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # crude test to catch cases of extreme overflow/underflow.  If
2065353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2066353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2067353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self**other >= 10**(Emax+1), so overflow occurs.  The test
2068353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # for underflow is similar.
2069353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        bound = self._log10_exp_bound() + other.adjusted()
2070353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if (self_adj >= 0) == (other._sign == 0):
2071353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # self > 1 and other +ve, or self < 1 and other -ve
2072353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # possibility of overflow
2073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if bound >= len(str(context.Emax)):
207472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(result_sign, '1', context.Emax+1)
2075353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2076353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # self > 1 and other -ve, or self < 1 and other +ve
2077353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # possibility of underflow to 0
2078353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            Etiny = context.Etiny()
2079353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if bound >= len(str(-Etiny)):
208072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(result_sign, '1', Etiny-1)
2081353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2082353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # try for an exact result with precision +1
2083353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans is None:
2084353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._power_exact(other, context.prec + 1)
2085353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans is not None and result_sign == 1:
208672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(1, ans._int, ans._exp)
2087353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2088353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # usual case: inexact result, x**y computed directly as exp(y*log(x))
2089353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans is None:
2090353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            p = context.prec
2091353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            x = _WorkRep(self)
2092353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xc, xe = x.int, x.exp
2093353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            y = _WorkRep(other)
2094353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            yc, ye = y.int, y.exp
2095353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if y.sign == 1:
2096353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                yc = -yc
2097353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2098353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # compute correctly rounded result:  start with precision +3,
2099353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # then increase precision until result is unambiguously roundable
2100353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            extra = 3
2101353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while True:
2102353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2103353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if coeff % (5*10**(len(str(coeff))-p-1)):
2104353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
2105353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                extra += 3
2106353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
210772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(result_sign, str(coeff), exp)
2108353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2109353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the specification says that for non-integer other we need to
2110353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # raise Inexact, even when the result is actually exact.  In
2111353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the same way, we need to raise Underflow here if the result
2112353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # is subnormal.  (The call to _fix will take care of raising
2113353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Rounded and Subnormal, as usual.)
2114353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other._isinteger():
2115353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
2116353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # pad with zeros up to length context.prec+1 if necessary
2117353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if len(ans._int) <= context.prec:
2118353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                expdiff = context.prec+1 - len(ans._int)
211972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
212072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                       ans._exp-expdiff)
2121353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans.adjusted() < context.Emin:
2122353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Underflow)
2123353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2124353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # unlike exp, ln and log10, the power function respects the
2125353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # rounding mode; no need to use ROUND_HALF_EVEN here
2126353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2127353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
2128353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2129353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def __rpow__(self, other, context=None):
2130353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Swaps self/other and returns __pow__."""
2131353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other)
2132353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other is NotImplemented:
2133353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return other
2134353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return other.__pow__(self, context=context)
2135353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2136353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def normalize(self, context=None):
2137353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
2138353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2139353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2140353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2141353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2142353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
2143353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._check_nans(context=context)
2144353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans:
2145353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return ans
2146353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2147353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        dup = self._fix(context)
2148353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if dup._isinfinity():
2149353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return dup
2150353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2151353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not dup:
215272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(dup._sign, '0', 0)
2153353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exp_max = [context.Emax, context.Etop()][context._clamp]
2154353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        end = len(dup._int)
21557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exp = dup._exp
215672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        while dup._int[end-1] == '0' and exp < exp_max:
21577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            exp += 1
21587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            end -= 1
215972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(dup._sign, dup._int[:end], exp)
21607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2161bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista    def quantize(self, exp, rounding=None, context=None, watchexp=True):
21627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Quantize self so its exponent is the same as that of exp.
21637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
21647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Similar to self._rescale(exp._exp) but with error checking.
21657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2166bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista        exp = _convert_other(exp, raiseit=True)
2167bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista
2168353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2169353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2170353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if rounding is None:
2171353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rounding = context.rounding
2172353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2173636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or exp._is_special:
2174636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(exp, context)
2175636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
2176636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
21777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2178636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if exp._isinfinity() or self._isinfinity():
2179636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if exp._isinfinity() and self._isinfinity():
21806c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return Decimal(self)  # if both are inf, it is OK
2181636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return context._raise_error(InvalidOperation,
2182636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                                        'quantize with one INF')
2183353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2184bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista        # if we're not watching exponents, do a simple rescale
2185bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista        if not watchexp:
2186bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista            ans = self._rescale(exp._exp, rounding)
2187bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista            # raise Inexact and Rounded where appropriate
2188bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista            if ans._exp > self._exp:
2189bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista                context._raise_error(Rounded)
2190bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista                if ans != self:
2191bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista                    context._raise_error(Inexact)
2192bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista            return ans
2193bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista
2194353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp._exp should be between Etiny and Emax
2195353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (context.Etiny() <= exp._exp <= context.Emax):
2196353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2197353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                   'target exponent out of bounds in quantize')
2198353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2199353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
220072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(self._sign, '0', exp._exp)
2201353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
2202353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2203353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_adjusted = self.adjusted()
2204353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_adjusted > context.Emax:
2205353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2206353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'exponent of quantize result too large for current context')
2207353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_adjusted - exp._exp + 1 > context.prec:
2208353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2209353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'quantize result has too many digits for current context')
2210353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2211353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._rescale(exp._exp, rounding)
2212353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans.adjusted() > context.Emax:
2213353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2214353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'exponent of quantize result too large for current context')
2215353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if len(ans._int) > context.prec:
2216353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2217353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'quantize result has too many digits for current context')
2218353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2219353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # raise appropriate flags
2220353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans._exp > self._exp:
2221353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Rounded)
2222353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans != self:
2223353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Inexact)
2224353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans and ans.adjusted() < context.Emin:
2225353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Subnormal)
2226353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2227353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # call to fix takes care of any necessary folddown
2228353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2229353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
22307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
22317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def same_quantum(self, other):
22321a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self and other have the same exponent; otherwise
22331a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return False.
22347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
22351a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        If either operand is a special value, the following rules are used:
22361a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista           * return True if both operands are infinities
22371a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista           * return True if both operands are NaNs
22381a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista           * otherwise, return False.
22397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
22401a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        other = _convert_other(other, raiseit=True)
2241636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
22421a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista            return (self.is_nan() and other.is_nan() or
22431a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista                    self.is_infinite() and other.is_infinite())
22447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return self._exp == other._exp
22457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2246353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _rescale(self, exp, rounding):
2247353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rescale self so that the exponent is exp, either by padding with zeros
2248353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        or by truncating digits, using the given rounding mode.
2249353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2250353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Specials are returned without change.  This operation is
2251353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        quiet: it raises no flags, and uses no information from the
2252353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.
22537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
22547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exp = exp to scale to (an integer)
2255353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = rounding mode
22567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2257636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
22586c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
22597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
226072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(self._sign, '0', exp)
22617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2262353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp >= exp:
2263353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # pad answer with zeros if necessary
226472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(self._sign,
226572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                        self._int + '0'*(self._exp - exp), exp)
22667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2267353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # too many digits; round and lose data.  If self.adjusted() <
2268353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp-1, replace self by 10**(exp-1) before rounding
2269353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        digits = len(self._int) + self._exp - exp
22707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if digits < 0:
227172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self = _dec_from_triple(self._sign, '1', exp-1)
2272353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            digits = 0
2273353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        this_function = getattr(self, self._pick_rounding_function[rounding])
22742ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        changed = this_function(digits)
22752ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        coeff = self._int[:digits] or '0'
22762ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        if changed == 1:
22772ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            coeff = str(int(coeff)+1)
22782ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        return _dec_from_triple(self._sign, coeff, exp)
22797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2280353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def to_integral_exact(self, rounding=None, context=None):
2281353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds to a nearby integer.
22827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2283353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        If no rounding mode is specified, take the rounding mode from
2284353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        the context.  This method raises the Rounded and Inexact flags
2285353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        when appropriate.
22867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2287353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        See also: to_integral_value, which does exactly the same as
2288353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        this method except that it doesn't raise Inexact or Rounded.
2289353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2290636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
2291636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
2292636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
2293636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
22946c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
22957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._exp >= 0:
22966c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
2297353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
229872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(self._sign, '0', 0)
2299636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
2300636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
2301353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if rounding is None:
2302353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rounding = context.rounding
2303353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._raise_error(Rounded)
2304353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._rescale(0, rounding)
2305353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans != self:
2306353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
23077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
23087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2309353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def to_integral_value(self, rounding=None, context=None):
2310353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds to the nearest integer, without raising inexact, rounded."""
2311353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2312353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2313353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if rounding is None:
2314353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rounding = context.rounding
2315353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
2316353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._check_nans(context=context)
2317353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans:
2318353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return ans
23196c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
2320353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp >= 0:
23216c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
2322353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2323353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._rescale(0, rounding)
23247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2325353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # the method name changed, but we provide also the old one, for compatibility
2326353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    to_integral = to_integral_value
2327353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2328353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def sqrt(self, context=None):
2329353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return the square root of self."""
2330636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
2331636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
2332636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
2333636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
23347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2335636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity() and self._sign == 0:
2336636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Decimal(self)
23377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
23387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
2339353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # exponent = self._exp // 2.  sqrt(-0) = -0
234072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(self._sign, '0', self._exp // 2)
2341353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
23427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2343636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
2344636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
2345636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
23467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign == 1:
23477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
23487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2349353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # At this point self represents a positive number.  Let p be
2350353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the desired precision and express self in the form c*100**e
2351353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # with c a positive real number and e an integer, c and e
2352353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # being chosen so that 100**(p-1) <= c < 100**p.  Then the
2353353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2354353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # <= sqrt(c) < 10**p, so the closest representable Decimal at
2355353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # precision p is n*10**e where n = round_half_even(sqrt(c)),
2356353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the closest integer to sqrt(c) with the even integer chosen
2357353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # in the case of a tie.
2358353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
2359353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # To ensure correct rounding in all cases, we use the
2360353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # following trick: we compute the square root to an extra
2361353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # place (precision p+1 instead of precision p), rounding down.
2362353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Then, if the result is inexact and its last digit is 0 or 5,
2363353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # we increase the last digit to 1 or 6 respectively; if it's
2364353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exact we leave the last digit alone.  Now the final round to
2365353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # p places (or fewer in the case of underflow) will round
2366353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # correctly and raise the appropriate flags.
2367353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2368353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # use an extra digit of precision
2369353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        prec = context.prec+1
2370353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2371353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # write argument in the form c*100**e where e = self._exp//2
2372353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # is the 'ideal' exponent, to be used if the square root is
2373353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exactly representable.  l is the number of 'digits' of c in
2374353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # base 100, so that 100**(l-1) <= c < 100**l.
2375353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op = _WorkRep(self)
2376353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        e = op.exp >> 1
2377353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if op.exp & 1:
2378353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = op.int * 10
2379353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            l = (len(self._int) >> 1) + 1
23807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
2381353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = op.int
2382353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            l = len(self._int)+1 >> 1
2383353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2384353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # rescale so that c has exactly prec base 100 'digits'
2385353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        shift = prec-l
2386353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if shift >= 0:
2387353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c *= 100**shift
2388353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            exact = True
23897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
2390353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c, remainder = divmod(c, 100**-shift)
2391353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            exact = not remainder
2392353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        e -= shift
2393353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2394353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # find n = floor(sqrt(c)) using Newton's method
2395353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        n = 10**prec
2396353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while True:
2397353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            q = c//n
2398353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if n <= q:
23997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                break
2400353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2401353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n = n + q >> 1
2402353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exact = exact and n*n == c
2403353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2404353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if exact:
2405353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # result is exact; rescale to use ideal exponent e
2406353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if shift >= 0:
2407353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # assert n % 10**shift == 0
2408353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n //= 10**shift
2409353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2410353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n *= 10**-shift
2411353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            e += shift
24127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
2413353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # result is not exact; fix last digit as described above
2414353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if n % 5 == 0:
2415353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n += 1
24167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
241772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        ans = _dec_from_triple(0, str(n), e)
24187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2419353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # round, and fit to current context
2420353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context._shallow_copy()
2421353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = context._set_rounding(ROUND_HALF_EVEN)
2422dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger        ans = ans._fix(context)
2423353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.rounding = rounding
24247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2425353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
24267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
24277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def max(self, other, context=None):
24287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the larger value.
24297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2430353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Like max(self, other) except if one is not a number, returns
24317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        NaN (and signals if one is sNaN).  Also rounds.
24327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2433353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
2434636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
24356c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        if context is None:
24366c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            context = getcontext()
24376c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista
2438636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
243959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If one operand is a quiet NaN and the other is number, then the
2440636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            # number is always returned
2441636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            sn = self._isnan()
2442636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            on = other._isnan()
2443636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if sn or on:
2444636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if on == 1 and sn != 2:
24456c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return self._fix_nan(context)
2446636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if sn == 1 and on != 2:
24476c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return other._fix_nan(context)
2448636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return self._check_nans(other, context)
24497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2450d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        c = self.__cmp__(other)
2451d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        if c == 0:
245259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If both operands are finite and equal in numerical value
2453d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger            # then an ordering is applied:
2454d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger            #
245559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If the signs differ then max returns the operand with the
2456d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger            # positive sign and min returns the operand with the negative sign
2457d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger            #
245859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If the signs are the same then the exponent is used to select
2459353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # the result.  This is exactly the ordering used in compare_total.
2460353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = self.compare_total(other)
2461353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2462353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == -1:
24637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = other
2464353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2465353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self
2466636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
2467e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        return ans._fix(context)
24687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
24697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def min(self, other, context=None):
24707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the smaller value.
24717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
247259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        Like min(self, other) except if one is not a number, returns
24737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        NaN (and signals if one is sNaN).  Also rounds.
24747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2475353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
2476636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
24776c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        if context is None:
24786c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            context = getcontext()
24796c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista
2480636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
248159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If one operand is a quiet NaN and the other is number, then the
2482636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            # number is always returned
2483636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            sn = self._isnan()
2484636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            on = other._isnan()
2485636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if sn or on:
2486636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if on == 1 and sn != 2:
24876c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return self._fix_nan(context)
2488636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if sn == 1 and on != 2:
24896c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return other._fix_nan(context)
2490636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return self._check_nans(other, context)
24917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2492d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        c = self.__cmp__(other)
2493d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        if c == 0:
2494353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = self.compare_total(other)
2495353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2496353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == -1:
2497353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self
2498353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
24997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = other
2500636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
2501e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        return ans._fix(context)
25027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
25037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _isinteger(self):
25047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns whether self is an integer"""
2505353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
2506353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return False
25077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._exp >= 0:
25087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return True
25097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rest = self._int[self._exp:]
251072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return rest == '0'*len(rest)
25117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
25127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _iseven(self):
2513353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns True if self is even.  Assumes self is an integer."""
2514353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self or self._exp > 0:
2515353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return True
251672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return self._int[-1+self._exp] in '02468'
25177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
25187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def adjusted(self):
25197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return the adjusted exponent of self"""
25207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        try:
25217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return self._exp + len(self._int) - 1
252259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # If NaN or Infinity, self._exp is string
25237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        except TypeError:
25247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return 0
25257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2526353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def canonical(self, context=None):
2527353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the same Decimal object.
2528353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2529353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        As we do not have different encodings for the same number, the
2530353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        received object already is in its canonical form.
2531353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2532353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self
2533353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2534353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_signal(self, other, context=None):
2535353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares self to the other operand numerically.
2536353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2537353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        It's pretty much like compare(), but all NaNs signal, with signaling
2538353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        NaNs taking precedence over quiet NaNs.
2539353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2540353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2541353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2542353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2543353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_is_nan = self._isnan()
2544353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other_is_nan = other._isnan()
2545353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_is_nan == 2:
2546353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation, 'sNaN',
2547353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, self)
2548353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other_is_nan == 2:
2549353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation, 'sNaN',
2550353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, other)
2551353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_is_nan:
2552353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2553353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, self)
2554353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other_is_nan:
2555353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2556353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        1, other)
2557353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self.compare(other, context=context)
2558353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2559353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_total(self, other):
2560353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares self to other using the abstract representations.
2561353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2562353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        This is not like the standard compare, which use their numerical
2563353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        value. Note that a total ordering is defined for all possible abstract
2564353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        representations.
2565353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2566353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if one is negative and the other is positive, it's easy
2567353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign and not other._sign:
2568353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_n1
2569353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self._sign and other._sign:
2570353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_p1
2571353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        sign = self._sign
2572353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2573353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # let's handle both NaN types
2574353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_nan = self._isnan()
2575353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other_nan = other._isnan()
2576353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_nan or other_nan:
2577353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self_nan == other_nan:
2578353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self._int < other._int:
2579353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if sign:
2580353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return Dec_p1
2581353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    else:
2582353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return Dec_n1
2583353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self._int > other._int:
2584353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if sign:
2585353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return Dec_n1
2586353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    else:
2587353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return Dec_p1
2588353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_0
2589353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2590353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sign:
2591353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_nan == 1:
2592353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_n1
2593353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other_nan == 1:
2594353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_p1
2595353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_nan == 2:
2596353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_n1
2597353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other_nan == 2:
2598353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_p1
2599353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2600353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_nan == 1:
2601353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_p1
2602353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other_nan == 1:
2603353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_n1
2604353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_nan == 2:
2605353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_p1
2606353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other_nan == 2:
2607353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_n1
2608353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2609353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self < other:
2610353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_n1
2611353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self > other:
2612353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_p1
2613353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2614353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp < other._exp:
2615353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sign:
2616353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_p1
2617353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2618353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_n1
2619353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp > other._exp:
2620353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sign:
2621353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_n1
2622353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2623353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_p1
2624353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Dec_0
2625353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2626353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2627353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_total_mag(self, other):
2628353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares self to other using abstract repr., ignoring sign.
2629353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2630353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Like compare_total, but with operand's sign ignored and assumed to be 0.
2631353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2632353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        s = self.copy_abs()
2633353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        o = other.copy_abs()
2634353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return s.compare_total(o)
2635353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2636353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_abs(self):
2637353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy with the sign set to 0. """
263872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(0, self._int, self._exp, self._is_special)
2639353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2640353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_negate(self):
2641353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy with the sign inverted."""
2642353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign:
264372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(0, self._int, self._exp, self._is_special)
2644353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
264572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(1, self._int, self._exp, self._is_special)
2646353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2647353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_sign(self, other):
2648353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns self with the sign of other."""
264972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(other._sign, self._int,
265072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                self._exp, self._is_special)
2651353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2652353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def exp(self, context=None):
2653353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns e ** self."""
2654353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2655353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2656353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2657353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2658353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp(NaN) = NaN
2659353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
2660353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
2661353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
2662353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2663353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp(-Infinity) = 0
2664353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == -1:
2665353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_0
2666353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2667353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp(0) = 1
2668353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2669353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_p1
2670353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2671353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp(Infinity) = Infinity
2672353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
2673353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Decimal(self)
2674353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2675353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the result is now guaranteed to be inexact (the true
2676353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # mathematical result is transcendental). There's no need to
2677353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # raise Rounded and Inexact here---they'll always be raised as
2678353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # a result of the call to _fix.
2679353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        p = context.prec
2680353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        adj = self.adjusted()
2681353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2682353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # we only need to do any computation for quite a small range
2683353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # of adjusted exponents---for example, -29 <= adj <= 10 for
2684353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the default context.  For smaller exponent the result is
2685353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # indistinguishable from 1 at the given precision, while for
2686353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # larger exponent the result either overflows or underflows.
2687353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2688353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # overflow
268972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(0, '1', context.Emax+1)
2690353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2691353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # underflow to 0
269272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(0, '1', context.Etiny()-1)
2693353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif self._sign == 0 and adj < -p:
2694353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # p+1 digits; final round will raise correct flags
269572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
2696353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif self._sign == 1 and adj < -p-1:
2697353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # p+1 digits; final round will raise correct flags
269872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(0, '9'*(p+1), -p-1)
2699353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # general case
2700353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2701353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            op = _WorkRep(self)
2702353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c, e = op.int, op.exp
2703353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if op.sign == 1:
2704353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                c = -c
2705353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2706353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # compute correctly rounded result: increase precision by
2707353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # 3 digits at a time until we get an unambiguously
2708353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # roundable result
2709353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            extra = 3
2710353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while True:
2711353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                coeff, exp = _dexp(c, e, p+extra)
2712353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if coeff % (5*10**(len(str(coeff))-p-1)):
2713353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
2714353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                extra += 3
2715353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
271672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(0, str(coeff), exp)
2717353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2718353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # at this stage, ans should round correctly with *any*
2719353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # rounding mode, not just with ROUND_HALF_EVEN
2720353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context._shallow_copy()
2721353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = context._set_rounding(ROUND_HALF_EVEN)
2722353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2723353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.rounding = rounding
2724353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2725353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
2726353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2727353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_canonical(self):
27281a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is canonical; otherwise return False.
27291a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista
27301a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        Currently, the encoding of a Decimal instance is always
27311a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        canonical, so this method returns True for any Decimal.
27321a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """
27331a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return True
2734353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2735353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_finite(self):
27361a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is finite; otherwise return False.
2737353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
27381a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        A Decimal instance is considered finite if it is neither
27391a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        infinite nor a NaN.
2740353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
27411a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return not self._is_special
2742353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2743353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_infinite(self):
27441a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is infinite; otherwise return False."""
27451a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self._exp == 'F'
2746353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2747353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_nan(self):
27481a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is a qNaN or sNaN; otherwise return False."""
27491a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self._exp in ('n', 'N')
2750353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2751353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_normal(self, context=None):
27521a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is a normal number; otherwise return False."""
27531a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        if self._is_special or not self:
27541a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista            return False
2755353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2756353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
27571a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return context.Emin <= self.adjusted() <= context.Emax
2758353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2759353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_qnan(self):
27601a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is a quiet NaN; otherwise return False."""
27611a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self._exp == 'n'
2762353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2763353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_signed(self):
27641a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is negative; otherwise return False."""
27651a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self._sign == 1
2766353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2767353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_snan(self):
27681a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is a signaling NaN; otherwise return False."""
27691a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self._exp == 'N'
2770353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2771353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_subnormal(self, context=None):
27721a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is subnormal; otherwise return False."""
27731a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        if self._is_special or not self:
27741a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista            return False
2775353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2776353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
27771a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self.adjusted() < context.Emin
2778353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2779353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_zero(self):
27801a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is a zero; otherwise return False."""
278172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return not self._is_special and self._int == '0'
2782353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2783353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _ln_exp_bound(self):
2784353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compute a lower bound for the adjusted exponent of self.ln().
2785353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        In other words, compute r such that self.ln() >= 10**r.  Assumes
2786353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        that self is finite and positive and that self != 1.
2787353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2788353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2789353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2790353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        adj = self._exp + len(self._int) - 1
2791353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj >= 1:
2792353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2793353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(str(adj*23//10)) - 1
2794353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj <= -2:
2795353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # argument <= 0.1
2796353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(str((-1-adj)*23//10)) - 1
2797353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op = _WorkRep(self)
2798353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c, e = op.int, op.exp
2799353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj == 0:
2800353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # 1 < self < 10
2801353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            num = str(c-10**-e)
2802353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            den = str(c)
2803353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(num) - len(den) - (num < den)
2804353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # adj == -1, 0.1 <= self < 1
2805353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return e + len(str(10**-e - c)) - 1
2806353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2807353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2808353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def ln(self, context=None):
2809353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the natural (base e) logarithm of self."""
2810353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2811353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2812353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2813353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2814353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(NaN) = NaN
2815353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
2816353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
2817353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
2818353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2819353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(0.0) == -Infinity
2820353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2821353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return negInf
2822353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2823353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(Infinity) = Infinity
2824353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
2825353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Inf
2826353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2827353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(1.0) == 0.0
2828353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self == Dec_p1:
2829353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_0
2830353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2831353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(negative) raises InvalidOperation
2832353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign == 1:
2833353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2834353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'ln of a negative value')
2835353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2836353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # result is irrational, so necessarily inexact
2837353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op = _WorkRep(self)
2838353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c, e = op.int, op.exp
2839353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        p = context.prec
2840353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2841353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # correctly rounded result: repeatedly increase precision by 3
2842353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # until we get an unambiguously roundable result
2843353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        places = p - self._ln_exp_bound() + 2 # at least p+3 places
2844353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while True:
2845353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            coeff = _dlog(c, e, places)
2846353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # assert len(str(abs(coeff)))-p >= 1
2847353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2848353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                break
2849353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            places += 3
285072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
2851353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2852353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context._shallow_copy()
2853353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = context._set_rounding(ROUND_HALF_EVEN)
2854353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2855353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.rounding = rounding
2856353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
2857353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2858353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _log10_exp_bound(self):
2859353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compute a lower bound for the adjusted exponent of self.log10().
2860353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        In other words, find r such that self.log10() >= 10**r.
2861353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Assumes that self is finite and positive and that self != 1.
2862353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2863353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2864353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # For x >= 10 or x < 0.1 we only need a bound on the integer
2865353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # part of log10(self), and this comes directly from the
2866353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exponent of x.  For 0.1 <= x <= 10 we use the inequalities
2867353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2868353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (1-1/x)/2.31 > 0.  If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2869353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2870353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        adj = self._exp + len(self._int) - 1
2871353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj >= 1:
2872353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # self >= 10
2873353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(str(adj))-1
2874353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj <= -2:
2875353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # self < 0.1
2876353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(str(-1-adj))-1
2877353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op = _WorkRep(self)
2878353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c, e = op.int, op.exp
2879353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj == 0:
2880353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # 1 < self < 10
2881353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            num = str(c-10**-e)
2882353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            den = str(231*c)
2883353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(num) - len(den) - (num < den) + 2
2884353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # adj == -1, 0.1 <= self < 1
2885353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        num = str(10**-e-c)
2886353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return len(num) + e - (num < "231") - 1
2887353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2888353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def log10(self, context=None):
2889353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the base 10 logarithm of self."""
2890353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2891353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2892353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2893353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2894353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(NaN) = NaN
2895353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
2896353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
2897353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
2898353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2899353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(0.0) == -Infinity
2900353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2901353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return negInf
2902353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2903353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(Infinity) = Infinity
2904353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
2905353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Inf
2906353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2907353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(negative or -Infinity) raises InvalidOperation
2908353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign == 1:
2909353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2910353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'log10 of a negative value')
2911353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2912353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(10**n) = n
291372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
2914353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # answer may need rounding
2915353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal(self._exp + len(self._int) - 1)
2916353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2917353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # result is irrational, so necessarily inexact
2918353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            op = _WorkRep(self)
2919353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c, e = op.int, op.exp
2920353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            p = context.prec
2921353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2922353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # correctly rounded result: repeatedly increase precision
2923353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # until result is unambiguously roundable
2924353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            places = p-self._log10_exp_bound()+2
2925353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while True:
2926353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                coeff = _dlog10(c, e, places)
2927353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # assert len(str(abs(coeff)))-p >= 1
2928353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2929353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
2930353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                places += 3
293172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
2932353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2933353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context._shallow_copy()
2934353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = context._set_rounding(ROUND_HALF_EVEN)
2935353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2936353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.rounding = rounding
2937353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
2938353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2939353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logb(self, context=None):
2940353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """ Returns the exponent of the magnitude of self's MSD.
2941353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2942353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result is the integer which is the exponent of the magnitude
2943353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        of the most significant digit of self (as though it were truncated
2944353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        to a single digit while maintaining the value of that digit and
2945353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        without limiting the resulting exponent).
2946353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2947353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # logb(NaN) = NaN
2948353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
2949353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
2950353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
2951353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2952353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2953353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2954353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2955353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # logb(+/-Inf) = +Inf
2956353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
2957353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Inf
2958353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2959353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # logb(0) = -Inf, DivisionByZero
2960353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2961cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return context._raise_error(DivisionByZero, 'logb(0)', 1)
2962353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2963353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # otherwise, simply return the adjusted exponent of self, as a
2964353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Decimal.  Note that no attempt is made to fit the result
2965353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # into the current context.
2966353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal(self.adjusted())
2967353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2968353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _islogical(self):
2969353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return True if self is a logical operand.
2970353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2971353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        For being logical, it must be a finite numbers with a sign of 0,
2972353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        an exponent of 0, and a coefficient whose digits must all be
2973353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        either 0 or 1.
2974353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2975353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign != 0 or self._exp != 0:
2976353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return False
2977353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        for dig in self._int:
297872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            if dig not in '01':
2979353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return False
2980353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return True
2981353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2982353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _fill_logical(self, context, opa, opb):
2983353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        dif = context.prec - len(opa)
2984353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if dif > 0:
298572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            opa = '0'*dif + opa
2986353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif dif < 0:
2987353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            opa = opa[-context.prec:]
2988353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        dif = context.prec - len(opb)
2989353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if dif > 0:
299072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            opb = '0'*dif + opb
2991353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif dif < 0:
2992353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            opb = opb[-context.prec:]
2993353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return opa, opb
2994353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2995353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_and(self, other, context=None):
2996353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies an 'and' operation between self and other's digits."""
2997353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2998353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2999353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self._islogical() or not other._islogical():
3000353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3001353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3002353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # fill to context.prec
3003353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        (opa, opb) = self._fill_logical(context, self._int, other._int)
3004353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3005353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # make the operation, and clean starting zeroes
300672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
300772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3008353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3009353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_invert(self, context=None):
3010353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Invert all its digits."""
3011353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3012353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
301372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
301472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                context)
3015353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3016353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_or(self, other, context=None):
3017353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies an 'or' operation between self and other's digits."""
3018353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3019353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3020353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self._islogical() or not other._islogical():
3021353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3022353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3023353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # fill to context.prec
3024353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        (opa, opb) = self._fill_logical(context, self._int, other._int)
3025353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3026353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # make the operation, and clean starting zeroes
302772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
302872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3029353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3030353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_xor(self, other, context=None):
3031353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies an 'xor' operation between self and other's digits."""
3032353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3033353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3034353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self._islogical() or not other._islogical():
3035353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3036353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3037353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # fill to context.prec
3038353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        (opa, opb) = self._fill_logical(context, self._int, other._int)
3039353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3040353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # make the operation, and clean starting zeroes
304172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
304272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3043353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3044353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def max_mag(self, other, context=None):
3045353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values numerically with their sign ignored."""
3046353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
3047353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
30486c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        if context is None:
30496c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            context = getcontext()
30506c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista
3051353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special or other._is_special:
3052353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # If one operand is a quiet NaN and the other is number, then the
3053353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # number is always returned
3054353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sn = self._isnan()
3055353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            on = other._isnan()
3056353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sn or on:
3057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if on == 1 and sn != 2:
30586c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return self._fix_nan(context)
3059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if sn == 1 and on != 2:
30606c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return other._fix_nan(context)
3061353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self._check_nans(other, context)
3062353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3063353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c = self.copy_abs().__cmp__(other.copy_abs())
3064353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == 0:
3065353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = self.compare_total(other)
3066353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3067353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == -1:
3068353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = other
3069353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
3070353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self
3071353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3072e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        return ans._fix(context)
3073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3074353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def min_mag(self, other, context=None):
3075353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values numerically with their sign ignored."""
3076353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
3077353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
30786c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        if context is None:
30796c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            context = getcontext()
30806c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista
3081353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special or other._is_special:
3082353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # If one operand is a quiet NaN and the other is number, then the
3083353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # number is always returned
3084353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sn = self._isnan()
3085353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            on = other._isnan()
3086353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sn or on:
3087353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if on == 1 and sn != 2:
30886c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return self._fix_nan(context)
3089353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if sn == 1 and on != 2:
30906c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return other._fix_nan(context)
3091353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self._check_nans(other, context)
3092353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3093353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c = self.copy_abs().__cmp__(other.copy_abs())
3094353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == 0:
3095353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = self.compare_total(other)
3096353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3097353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == -1:
3098353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self
3099353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
3100353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = other
3101353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3102e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        return ans._fix(context)
3103353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3104353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_minus(self, context=None):
3105353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the largest representable number smaller than itself."""
3106353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3107353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3108353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3109353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
3110353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3111353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3112353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3113353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == -1:
3114353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return negInf
3115353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
311672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(0, '9'*context.prec, context.Etop())
3117353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3118353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context.copy()
3119353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._set_rounding(ROUND_FLOOR)
3120353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._ignore_all_flags()
3121353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        new_self = self._fix(context)
3122353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if new_self != self:
3123353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return new_self
312472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
312572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                            context)
3126353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3127353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_plus(self, context=None):
3128353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the smallest representable number larger than itself."""
3129353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3130353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3131353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3132353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
3133353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3134353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3135353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3136353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
3137353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Inf
3138353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == -1:
313972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(1, '9'*context.prec, context.Etop())
3140353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3141353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context.copy()
3142353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._set_rounding(ROUND_CEILING)
3143353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._ignore_all_flags()
3144353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        new_self = self._fix(context)
3145353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if new_self != self:
3146353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return new_self
314772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
314872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                            context)
3149353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3150353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_toward(self, other, context=None):
3151353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the number closest to self, in the direction towards other.
3152353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3153353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result is the closest representable number to self
3154353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        (excluding self) that is in the direction towards other,
3155353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        unless both have the same value.  If the two operands are
3156353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        numerically equal, then the result is a copy of self with the
3157353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        sign set to be the same as the sign of other.
3158353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3159353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
3160353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3161353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3162353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3163353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3164353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
3165353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3166353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3167353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3168353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        comparison = self.__cmp__(other)
3169353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if comparison == 0:
317072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return self.copy_sign(other)
3171353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3172353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if comparison == -1:
3173353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.next_plus(context)
3174353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else: # comparison == 1
3175353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.next_minus(context)
3176353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3177353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # decide which flags to raise using value of ans
3178353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans._isinfinity():
3179353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Overflow,
3180353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                 'Infinite result from next_toward',
3181353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                 ans._sign)
3182353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Rounded)
3183353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
3184353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif ans.adjusted() < context.Emin:
3185353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Underflow)
3186353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Subnormal)
3187353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Rounded)
3188353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
3189353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # if precision == 1 then we don't raise Clamped for a
3190353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # result 0E-Etiny.
3191353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if not ans:
3192353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Clamped)
3193353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3194353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
3195353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3196353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def number_class(self, context=None):
3197353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns an indication of the class of self.
3198353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3199353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The class is one of the following strings:
3200353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -sNaN
3201353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -NaN
3202353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Infinity
3203353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Normal
3204353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Subnormal
3205353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Zero
3206353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Zero
3207353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Subnormal
3208353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Normal
3209353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Infinity
3210353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3211353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self.is_snan():
3212353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "sNaN"
3213353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self.is_qnan():
3214353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "NaN"
3215353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        inf = self._isinfinity()
3216353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if inf == 1:
3217353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "+Infinity"
3218353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if inf == -1:
3219353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "-Infinity"
3220353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self.is_zero():
3221353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self._sign:
3222353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return "-Zero"
3223353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
3224353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return "+Zero"
3225353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3226353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3227353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self.is_subnormal(context=context):
3228353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self._sign:
3229353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return "-Subnormal"
3230353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
3231353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return "+Subnormal"
3232353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # just a normal, regular, boring number, :)
3233353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign:
3234353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "-Normal"
3235353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
3236353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "+Normal"
3237353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3238353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def radix(self):
3239353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Just returns 10, as this is Decimal, :)"""
3240353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal(10)
3241353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3242353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def rotate(self, other, context=None):
3243353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a rotated copy of self, value-of-other times."""
3244353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3245353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3246353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3247353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
3248353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3249353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3250353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3251353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._exp != 0:
3252353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3253353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (-context.prec <= int(other) <= context.prec):
3254353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3255353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3256353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
32576c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
3258353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3259353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # get values, pad if necessary
3260353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        torot = int(other)
3261353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotdig = self._int
3262353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        topad = context.prec - len(rotdig)
3263353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if topad:
326472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            rotdig = '0'*topad + rotdig
3265353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3266353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # let's rotate!
3267353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotated = rotdig[torot:] + rotdig[:torot]
326872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(self._sign,
326972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                rotated.lstrip('0') or '0', self._exp)
3270353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3271353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def scaleb (self, other, context=None):
3272353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns self operand after adding the second value to its exp."""
3273353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3274353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3275353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3276353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
3277353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3278353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3279353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3280353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._exp != 0:
3281353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3282353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        liminf = -2 * (context.Emax + context.prec)
3283353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        limsup =  2 * (context.Emax + context.prec)
3284353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (liminf <= int(other) <= limsup):
3285353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3286353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3287353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
32886c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
3289353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
329072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
3291353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        d = d._fix(context)
3292353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return d
3293353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3294353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def shift(self, other, context=None):
3295353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a shifted copy of self, value-of-other times."""
3296353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3297353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3298353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3299353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
3300353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3301353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3302353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3303353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._exp != 0:
3304353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3305353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (-context.prec <= int(other) <= context.prec):
3306353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3307353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3308353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
33096c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
3310353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3311353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # get values, pad if necessary
3312353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        torot = int(other)
3313353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not torot:
33146c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
3315353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotdig = self._int
3316353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        topad = context.prec - len(rotdig)
3317353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if topad:
331872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            rotdig = '0'*topad + rotdig
3319353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3320353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # let's shift!
3321353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if torot < 0:
3322353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rotated = rotdig[:torot]
3323353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
332472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            rotated = rotdig + '0'*torot
3325353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rotated = rotated[-context.prec:]
3326353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
332772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(self._sign,
332872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                    rotated.lstrip('0') or '0', self._exp)
3329353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
333059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # Support for pickling, copy, and deepcopy
33317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __reduce__(self):
33327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return (self.__class__, (str(self),))
33337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
33347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __copy__(self):
33357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if type(self) == Decimal:
3336cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis            return self     # I'm immutable; therefore I am my own clone
33377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return self.__class__(str(self))
33387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
33397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __deepcopy__(self, memo):
33407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if type(self) == Decimal:
3341cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis            return self     # My components are also immutable
33427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return self.__class__(str(self))
33437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
334472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batistadef _dec_from_triple(sign, coefficient, exponent, special=False):
334572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    """Create a decimal instance directly, without any validation,
334672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    normalization (e.g. removal of leading zeros) or argument
334772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    conversion.
334872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista
334972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    This function is for *internal use only*.
335072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    """
335172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista
335272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    self = object.__new__(Decimal)
335372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    self._sign = sign
335472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    self._int = coefficient
335572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    self._exp = exponent
335672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    self._is_special = special
335772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista
335872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    return self
335972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista
336059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Context class #######################################################
3361cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
33627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3363cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis# get rounding method function:
336459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batistarounding_functions = [name for name in Decimal.__dict__.keys()
336559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                                    if name.startswith('_round_')]
33667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerfor name in rounding_functions:
336759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
33687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    globalname = name[1:].upper()
33697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    val = globals()[globalname]
33707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Decimal._pick_rounding_function[val] = name
33717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
33729ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettingerdel name, val, globalname, rounding_functions
33737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3374ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlanclass _ContextManager(object):
33758b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """Context manager class to support localcontext().
33761a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum
3377ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlan      Sets a copy of the supplied context in __enter__() and restores
33788b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan      the previous decimal context in __exit__()
33798b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """
33801a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum    def __init__(self, new_context):
3381ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlan        self.new_context = new_context.copy()
33821a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum    def __enter__(self):
33831a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum        self.saved_context = getcontext()
33841a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum        setcontext(self.new_context)
33851a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum        return self.new_context
33861a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum    def __exit__(self, t, v, tb):
33871a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum        setcontext(self.saved_context)
33881a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum
33897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Context(object):
33907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Contains the context for a Decimal instance.
33917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
33927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Contains:
33937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    prec - precision (for use in rounding, division, square roots..)
339459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    rounding - rounding type (how you round)
3395bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger    traps - If traps[exception] = 1, then the exception is
33967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    raised when it is caused.  Otherwise, a value is
33977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    substituted in.
33987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    flags  - When an exception is caused, flags[exception] is incremented.
33997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger             (Whether or not the trap_enabler is set)
34007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger             Should be reset by user of Decimal instance.
34010ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettinger    Emin -   Minimum exponent
34020ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettinger    Emax -   Maximum exponent
34037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    capitals -      If 1, 1*10^1 is printed as 1E+1.
34047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    If 0, printed as 1e1
3405e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger    _clamp - If 1, change exponents if too high (Default 0)
34067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
34079ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger
34087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __init__(self, prec=None, rounding=None,
3409abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger                 traps=None, flags=None,
34100ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettinger                 Emin=None, Emax=None,
3411e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger                 capitals=None, _clamp=0,
3412abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger                 _ignored_flags=None):
3413abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger        if flags is None:
3414abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger            flags = []
3415abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger        if _ignored_flags is None:
3416abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger            _ignored_flags = []
3417bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        if not isinstance(flags, dict):
3418fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger            flags = dict([(s,s in flags) for s in _signals])
3419b91af521fddac47b14c57cd9ba736775334e6379Raymond Hettinger            del s
3420bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        if traps is not None and not isinstance(traps, dict):
3421fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger            traps = dict([(s,s in traps) for s in _signals])
3422b91af521fddac47b14c57cd9ba736775334e6379Raymond Hettinger            del s
34237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        for name, val in locals().items():
34247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if val is None:
3425eb2608415ee4eb8aaea746f6a313937e264d0cdaRaymond Hettinger                setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
34267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            else:
34277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                setattr(self, name, val)
34287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        del self.self
34297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3430b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger    def __repr__(self):
3431bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        """Show the current context."""
3432b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger        s = []
343359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
343459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
343559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                 % vars(self))
343659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        names = [f.__name__ for f, v in self.flags.items() if v]
343759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        s.append('flags=[' + ', '.join(names) + ']')
343859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        names = [t.__name__ for t, v in self.traps.items() if v]
343959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        s.append('traps=[' + ', '.join(names) + ']')
3440b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger        return ', '.join(s) + ')'
3441b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger
3442d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger    def clear_flags(self):
3443d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger        """Reset all flags to zero"""
3444d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger        for flag in self.flags:
3445b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger            self.flags[flag] = 0
3446d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger
34479fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger    def _shallow_copy(self):
34489fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        """Returns a shallow copy from self."""
3449e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        nc = Context(self.prec, self.rounding, self.traps,
3450e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista                     self.flags, self.Emin, self.Emax,
3451e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista                     self.capitals, self._clamp, self._ignored_flags)
34527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return nc
34539fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger
34549fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger    def copy(self):
34559fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        """Returns a deep copy from self."""
345659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        nc = Context(self.prec, self.rounding, self.traps.copy(),
3457e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista                     self.flags.copy(), self.Emin, self.Emax,
3458e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista                     self.capitals, self._clamp, self._ignored_flags)
34599fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        return nc
34609ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger    __copy__ = copy
34617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
34625aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger    def _raise_error(self, condition, explanation = None, *args):
34637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Handles an error
34647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
34657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the flag is in _ignored_flags, returns the default response.
34667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Otherwise, it increments the flag, then, if the corresponding
34677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        trap_enabler is set, it reaises the exception.  Otherwise, it returns
34687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        the default value after incrementing the flag.
34697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
34705aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger        error = _condition_map.get(condition, condition)
34717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if error in self._ignored_flags:
347259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # Don't touch the flag
34737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return error().handle(self, *args)
34747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
34757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self.flags[error] += 1
3476bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        if not self.traps[error]:
347759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # The errors define how to handle themselves.
34785aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger            return condition().handle(self, *args)
34797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
34807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Errors should only be risked on copies of the context
348159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # self._ignored_flags = []
34827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        raise error, explanation
34837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
34847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _ignore_all_flags(self):
34857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Ignore all flags, if they are raised"""
3486fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger        return self._ignore_flags(*_signals)
34877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
34887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _ignore_flags(self, *flags):
34897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Ignore the flags, if they are raised"""
34907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Do not mutate-- This way, copies of a context leave the original
34917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # alone.
34927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self._ignored_flags = (self._ignored_flags + list(flags))
34937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return list(flags)
34947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
34957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _regard_flags(self, *flags):
34967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Stop ignoring the flags, if they are raised"""
34977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if flags and isinstance(flags[0], (tuple,list)):
34987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            flags = flags[0]
34997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        for flag in flags:
35007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self._ignored_flags.remove(flag)
35017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35025aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger    def __hash__(self):
35035aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger        """A Context cannot be hashed."""
35045aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger        # We inherit object.__hash__, so we must deny this explicitly
350559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        raise TypeError("Cannot hash a Context.")
35065aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger
35077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def Etiny(self):
35087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns Etiny (= Emin - prec + 1)"""
35097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return int(self.Emin - self.prec + 1)
35107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def Etop(self):
3512e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger        """Returns maximum exponent (= Emax - prec + 1)"""
35137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return int(self.Emax - self.prec + 1)
35147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _set_rounding(self, type):
35167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Sets the rounding type.
35177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Sets the rounding type, and returns the current (previous)
35197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding type.  Often used like:
35207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        context = context.copy()
35227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # so you don't change the calling context
35237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # if an error occurs in the middle.
35247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding = context._set_rounding(ROUND_UP)
35257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        val = self.__sub__(other, context=context)
35267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        context._set_rounding(rounding)
35277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        This will make it round up for that operation.
35297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
35307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding = self.rounding
35317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self.rounding= type
35327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return rounding
35337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3534fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger    def create_decimal(self, num='0'):
35357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Creates a new Decimal instance but using self as context."""
35367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        d = Decimal(num, context=self)
3537353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if d._isnan() and len(d._int) > self.prec - self._clamp:
3538353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._raise_error(ConversionSyntax,
3539353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                     "diagnostic info too long in NaN")
3540dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger        return d._fix(self)
35417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
354259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # Methods
35437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def abs(self, a):
35447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the absolute value of the operand.
35457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the operand is negative, the result is the same as using the minus
354759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operation on the operand.  Otherwise, the result is the same as using
35487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        the plus operation on the operand.
35497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35509ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.abs(Decimal('2.1'))
35517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.1")
35529ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.abs(Decimal('-100'))
35537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("100")
35549ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.abs(Decimal('101.5'))
35557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("101.5")
35569ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.abs(Decimal('-101.5'))
35577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("101.5")
35587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
35597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__abs__(context=self)
35607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def add(self, a, b):
35627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return the sum of the two operands.
35637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35649ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
35657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("19.00")
35669ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
35677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.02E+4")
35687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
35697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__add__(b, context=self)
35707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _apply(self, a):
3572dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger        return str(a._fix(self))
35737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3574353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def canonical(self, a):
3575353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the same Decimal object.
3576353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3577353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        As we do not have different encodings for the same number, the
3578353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        received object already is in its canonical form.
3579353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3580353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.canonical(Decimal('2.50'))
3581353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.50")
3582353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3583353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.canonical(context=self)
3584353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
35857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def compare(self, a, b):
35867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Compares values numerically.
35877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the signs of the operands differ, a value representing each operand
35897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        ('-1' if the operand is less than zero, '0' if the operand is zero or
35907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        negative zero, or '1' if the operand is greater than zero) is used in
35917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        place of that operand for the comparison instead of the actual
35927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        operand.
35937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The comparison is then effected by subtracting the second operand from
35957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        the first and then returning a value according to the result of the
35967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        subtraction: '-1' if the result is less than zero, '0' if the result is
35977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        zero or negative zero, or '1' if the result is greater than zero.
35987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35999ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
36007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1")
36019ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
36027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0")
36039ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
36047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0")
36059ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
36067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
36079ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
36087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
36099ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
36107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1")
36117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
36127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.compare(b, context=self)
36137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3614353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_signal(self, a, b):
3615353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values of the two operands numerically.
3616353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3617353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        It's pretty much like compare(), but all NaNs signal, with signaling
3618353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        NaNs taking precedence over quiet NaNs.
3619353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3620353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext
3621353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3622353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1")
3623353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3624353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3625353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.flags[InvalidOperation] = 0
3626353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> print c.flags[InvalidOperation]
3627353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        0
3628353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3629353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("NaN")
3630353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> print c.flags[InvalidOperation]
3631353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        1
3632353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.flags[InvalidOperation] = 0
3633353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> print c.flags[InvalidOperation]
3634353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        0
3635353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3636353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("NaN")
3637353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> print c.flags[InvalidOperation]
3638353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        1
3639353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3640353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.compare_signal(b, context=self)
3641353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3642353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_total(self, a, b):
3643353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares two operands using their abstract representation.
3644353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3645353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        This is not like the standard compare, which use their numerical
3646353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        value. Note that a total ordering is defined for all possible abstract
3647353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        representations.
3648353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3649353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3650353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1")
3651353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('-127'),  Decimal('12'))
3652353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1")
3653353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3654353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1")
3655353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3656353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3657353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('12.300'))
3658353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3659353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('NaN'))
3660353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1")
3661353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3662353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.compare_total(b)
3663353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3664353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_total_mag(self, a, b):
3665353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares two operands using their abstract representation ignoring sign.
3666353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3667353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Like compare_total, but with operand's sign ignored and assumed to be 0.
3668353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3669353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.compare_total_mag(b)
3670353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3671353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_abs(self, a):
3672353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy of the operand with the sign set to 0.
3673353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3674353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_abs(Decimal('2.1'))
3675353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.1")
3676353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_abs(Decimal('-100'))
3677353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("100")
3678353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3679353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.copy_abs()
3680353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3681353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_decimal(self, a):
3682353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy of the decimal objet.
3683353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3684353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3685353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.1")
3686353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3687353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.00")
3688353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
36896c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        return Decimal(a)
3690353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3691353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_negate(self, a):
3692353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy of the operand with the sign inverted.
3693353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3694353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_negate(Decimal('101.5'))
3695353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-101.5")
3696353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3697353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("101.5")
3698353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3699353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.copy_negate()
3700353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3701353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_sign(self, a, b):
3702353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Copies the second operand's sign to the first one.
3703353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3704353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        In detail, it returns a copy of the first operand with the sign
3705353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        equal to the sign of the second operand.
3706353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3707353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3708353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.50")
3709353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3710353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.50")
3711353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3712353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.50")
3713353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3714353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.50")
3715353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3716353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.copy_sign(b)
3717353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
37187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def divide(self, a, b):
37197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Decimal division in a specified context.
37207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37219ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
37227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.333333333")
37239ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
37247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.666666667")
37259ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
37267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.5")
37279ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
37287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.1")
37299ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
37307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
37319ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
37327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("4.00")
37339ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
37347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.20")
37359ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
37367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("10")
37379ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
37387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1000")
37399ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
37407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.20E+6")
37417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
37427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__div__(b, context=self)
37437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def divide_int(self, a, b):
37457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Divides two numbers and returns the integer part of the result.
37467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37479ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
37487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0")
37499ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
37507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3")
37519ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
37527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3")
37537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
37547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__floordiv__(b, context=self)
37557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
37567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def divmod(self, a, b):
37577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__divmod__(b, context=self)
37587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3759353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def exp(self, a):
3760353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns e ** a.
3761353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3762353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
3763353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
3764353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
3765353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('-Infinity'))
3766353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3767353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('-1'))
3768353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0.367879441")
3769353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('0'))
3770353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3771353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('1'))
3772353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.71828183")
3773353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('0.693147181'))
3774353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.00000000")
3775353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('+Infinity'))
3776353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("Infinity")
3777353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3778353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.exp(context=self)
3779353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3780353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def fma(self, a, b, c):
3781353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a multiplied by b, plus c.
3782353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3783353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The first two operands are multiplied together, using multiply,
3784353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        the third operand is then added to the result of that
3785353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        multiplication, using add, all with only one final rounding.
3786353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3787353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3788353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("22")
3789353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3790353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-8")
3791353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3792353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.38435736E+12")
3793353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3794353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.fma(b, c, context=self)
3795353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3796353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_canonical(self, a):
37971a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is canonical; otherwise return False.
37981a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista
37991a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        Currently, the encoding of a Decimal instance is always
38001a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        canonical, so this method returns True for any Decimal.
3801353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3802353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_canonical(Decimal('2.50'))
38031a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3804353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
38051a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return a.is_canonical()
3806353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3807353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_finite(self, a):
38081a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is finite; otherwise return False.
3809353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
38101a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        A Decimal instance is considered finite if it is neither
38111a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        infinite nor a NaN.
3812353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3813353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('2.50'))
38141a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3815353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('-0.3'))
38161a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3817353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('0'))
38181a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3819353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('Inf'))
38201a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3821353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('NaN'))
38221a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3823353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3824353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_finite()
3825353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3826353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_infinite(self, a):
38271a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is infinite; otherwise return False.
3828353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3829353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_infinite(Decimal('2.50'))
38301a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3831353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_infinite(Decimal('-Inf'))
38321a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3833353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_infinite(Decimal('NaN'))
38341a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3835353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3836353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_infinite()
3837353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3838353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_nan(self, a):
38391a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is a qNaN or sNaN;
38401a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        otherwise return False.
3841353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3842353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_nan(Decimal('2.50'))
38431a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3844353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_nan(Decimal('NaN'))
38451a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3846353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_nan(Decimal('-sNaN'))
38471a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3848353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3849353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_nan()
3850353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3851353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_normal(self, a):
38521a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is a normal number;
38531a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        otherwise return False.
3854353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3855353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
3856353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
3857353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
3858353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('2.50'))
38591a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3860353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('0.1E-999'))
38611a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3862353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('0.00'))
38631a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3864353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('-Inf'))
38651a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3866353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('NaN'))
38671a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3868353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3869353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_normal(context=self)
3870353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3871353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_qnan(self, a):
38721a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is a quiet NaN; otherwise return False.
3873353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3874353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_qnan(Decimal('2.50'))
38751a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3876353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_qnan(Decimal('NaN'))
38771a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3878353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_qnan(Decimal('sNaN'))
38791a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3880353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3881353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_qnan()
3882353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3883353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_signed(self, a):
38841a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is negative; otherwise return False.
3885353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3886353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_signed(Decimal('2.50'))
38871a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3888353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_signed(Decimal('-12'))
38891a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3890353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_signed(Decimal('-0'))
38911a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3892353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3893353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_signed()
3894353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3895353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_snan(self, a):
38961a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is a signaling NaN;
38971a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        otherwise return False.
3898353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3899353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_snan(Decimal('2.50'))
39001a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3901353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_snan(Decimal('NaN'))
39021a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3903353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_snan(Decimal('sNaN'))
39041a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3905353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3906353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_snan()
3907353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3908353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_subnormal(self, a):
39091a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is subnormal; otherwise return False.
3910353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3911353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
3912353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
3913353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
3914353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('2.50'))
39151a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3916353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('0.1E-999'))
39171a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3918353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('0.00'))
39191a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3920353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('-Inf'))
39211a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3922353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('NaN'))
39231a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3924353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3925353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_subnormal(context=self)
3926353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3927353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_zero(self, a):
39281a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is a zero; otherwise return False.
3929353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3930353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_zero(Decimal('0'))
39311a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3932353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_zero(Decimal('2.50'))
39331a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3934353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_zero(Decimal('-0E+2'))
39351a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3936353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3937353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_zero()
3938353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3939353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def ln(self, a):
3940353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the natural (base e) logarithm of the operand.
3941353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3942353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
3943353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
3944353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
3945353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('0'))
3946353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-Infinity")
3947353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('1.000'))
3948353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3949353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('2.71828183'))
3950353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.00000000")
3951353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('10'))
3952353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.30258509")
3953353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('+Infinity'))
3954353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("Infinity")
3955353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3956353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.ln(context=self)
3957353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3958353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def log10(self, a):
3959353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the base 10 logarithm of the operand.
3960353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3961353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
3962353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
3963353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
3964353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('0'))
3965353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-Infinity")
3966353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('0.001'))
3967353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-3")
3968353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('1.000'))
3969353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3970353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('2'))
3971353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0.301029996")
3972353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('10'))
3973353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
3974353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('70'))
3975353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.84509804")
3976353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('+Infinity'))
3977353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("Infinity")
3978353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3979353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.log10(context=self)
3980353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3981353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logb(self, a):
3982353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """ Returns the exponent of the magnitude of the operand's MSD.
3983353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3984353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result is the integer which is the exponent of the magnitude
3985353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        of the most significant digit of the operand (as though the
3986353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        operand were truncated to a single digit while maintaining the
3987353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        value of that digit and without limiting the resulting exponent).
3988353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3989353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logb(Decimal('250'))
3990353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2")
3991353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logb(Decimal('2.50'))
3992353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
3993353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logb(Decimal('0.03'))
3994353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-2")
3995353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logb(Decimal('0'))
3996353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-Infinity")
3997353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3998353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logb(context=self)
3999353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4000353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_and(self, a, b):
4001353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies the logical operation 'and' between each operand's digits.
4002353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4003353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The operands must be both logical numbers.
4004353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4005353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4006353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4007353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4008353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4009353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4010353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4011353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4012353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4013353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4014353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1000")
4015353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4016353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("10")
4017353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4018353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logical_and(b, context=self)
4019353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4020353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_invert(self, a):
4021353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Invert all the digits in the operand.
4022353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4023353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The operand must be a logical number.
4024353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4025353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_invert(Decimal('0'))
4026353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("111111111")
4027353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_invert(Decimal('1'))
4028353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("111111110")
4029353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_invert(Decimal('111111111'))
4030353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4031353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_invert(Decimal('101010101'))
4032353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("10101010")
4033353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4034353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logical_invert(context=self)
4035353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4036353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_or(self, a, b):
4037353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies the logical operation 'or' between each operand's digits.
4038353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4039353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The operands must be both logical numbers.
4040353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4041353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4042353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4043353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4044353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4045353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4046353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4047353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4048353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4049353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4050353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1110")
4051353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4052353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1110")
4053353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4054353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logical_or(b, context=self)
4055353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4056353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_xor(self, a, b):
4057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies the logical operation 'xor' between each operand's digits.
4058353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The operands must be both logical numbers.
4060353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4061353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4062353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4063353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4064353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4065353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4066353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4067353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4068353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4069353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4070353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("110")
4071353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4072353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1101")
4073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4074353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logical_xor(b, context=self)
4075353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
40767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def max(self, a,b):
40777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """max compares two values numerically and returns the maximum.
40787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
40797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If either operand is a NaN then the general rules apply.
40807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Otherwise, the operands are compared as as though by the compare
408159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operation.  If they are numerically equal then the left-hand operand
408259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        is chosen as the result.  Otherwise the maximum (closer to positive
40837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        infinity) of the two operands is chosen as the result.
40847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
40859ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
40867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3")
40879ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
40887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3")
40899ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
4090d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        Decimal("1")
4091d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4092d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        Decimal("7")
40937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
40947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.max(b, context=self)
40957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4096353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def max_mag(self, a, b):
4097353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values numerically with their sign ignored."""
4098353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.max_mag(b, context=self)
4099353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
41007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def min(self, a,b):
41017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """min compares two values numerically and returns the minimum.
41027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If either operand is a NaN then the general rules apply.
41047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Otherwise, the operands are compared as as though by the compare
410559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operation.  If they are numerically equal then the left-hand operand
410659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        is chosen as the result.  Otherwise the minimum (closer to negative
41077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        infinity) of the two operands is chosen as the result.
41087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41099ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
41107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2")
41119ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
41127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-10")
41139ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
41147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.0")
4115d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4116d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        Decimal("7")
41177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
41187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.min(b, context=self)
41197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4120353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def min_mag(self, a, b):
4121353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values numerically with their sign ignored."""
4122353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.min_mag(b, context=self)
4123353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
41247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def minus(self, a):
41257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Minus corresponds to unary prefix minus in Python.
41267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The operation is evaluated using the same rules as subtract; the
41287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        operation minus(a) is calculated as subtract('0', a) where the '0'
41297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        has the same exponent as the operand.
41307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41319ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.minus(Decimal('1.3'))
41327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1.3")
41339ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.minus(Decimal('-1.3'))
41347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.3")
41357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
41367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__neg__(context=self)
41377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def multiply(self, a, b):
41397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """multiply multiplies two operands.
41407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4141cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis        If either operand is a special value then the general rules apply.
4142cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis        Otherwise, the operands are multiplied together ('long multiplication'),
4143cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis        resulting in a number which may be as long as the sum of the lengths
4144cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis        of the two operands.
41457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41469ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
41477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3.60")
41489ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
41497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("21")
41509ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
41517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.72")
41529ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
41537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0.0")
41549ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
41557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("4.28135971E+11")
41567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
41577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__mul__(b, context=self)
41587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4159353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_minus(self, a):
4160353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the largest representable number smaller than a.
4161353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4162353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4163353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4164353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4165353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.next_minus(Decimal('1'))
4166353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0.999999999")
4167353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_minus(Decimal('1E-1007'))
4168353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0E-1007")
4169353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4170353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.00000004")
4171353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_minus(Decimal('Infinity'))
4172353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("9.99999999E+999")
4173353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4174353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.next_minus(context=self)
4175353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4176353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_plus(self, a):
4177353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the smallest representable number larger than a.
4178353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4179353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4180353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4181353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4182353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.next_plus(Decimal('1'))
4183353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.00000001")
4184353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_plus(Decimal('-1E-1007'))
4185353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-0E-1007")
4186353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4187353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.00000002")
4188353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_plus(Decimal('-Infinity'))
4189353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-9.99999999E+999")
4190353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4191353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.next_plus(context=self)
4192353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4193353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_toward(self, a, b):
4194353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the number closest to a, in direction towards b.
4195353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4196353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result is the closest representable number from the first
4197353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        operand (but not the first operand) that is in the direction
4198353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        towards the second operand, unless the operands have the same
4199353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        value.
4200353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4201353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4202353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4203353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4204353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('1'), Decimal('2'))
4205353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.00000001")
4206353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4207353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-0E-1007")
4208353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4209353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.00000002")
4210353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('1'), Decimal('0'))
4211353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0.999999999")
4212353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4213353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0E-1007")
4214353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4215353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-1.00000004")
4216353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4217353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-0.00")
4218353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4219353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.next_toward(b, context=self)
4220353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
42217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def normalize(self, a):
4222e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger        """normalize reduces an operand to its simplest form.
42237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
42247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Essentially a plus operation with all trailing zeros removed from the
42257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        result.
42267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
42279ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('2.1'))
42287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.1")
42299ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('-2.0'))
42307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-2")
42319ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('1.200'))
42327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.2")
42339ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('-120'))
42347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1.2E+2")
42359ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('120.00'))
42367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.2E+2")
42379ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('0.00'))
42387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0")
42397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
42407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.normalize(context=self)
42417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4242353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def number_class(self, a):
4243353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns an indication of the class of the operand.
4244353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4245353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The class is one of the following strings:
4246353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -sNaN
4247353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -NaN
4248353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Infinity
4249353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Normal
4250353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Subnormal
4251353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Zero
4252353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Zero
4253353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Subnormal
4254353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Normal
4255353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Infinity
4256353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4257353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = Context(ExtendedContext)
4258353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4259353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4260353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('Infinity'))
4261353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Infinity'
4262353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('1E-10'))
4263353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Normal'
4264353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('2.50'))
4265353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Normal'
4266353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('0.1E-999'))
4267353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Subnormal'
4268353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('0'))
4269353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Zero'
4270353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-0'))
4271353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Zero'
4272353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-0.1E-999'))
4273353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Subnormal'
4274353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-1E-10'))
4275353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Normal'
4276353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-2.50'))
4277353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Normal'
4278353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-Infinity'))
4279353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Infinity'
4280353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('NaN'))
4281353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        'NaN'
4282353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-NaN'))
4283353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        'NaN'
4284353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('sNaN'))
4285353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        'sNaN'
4286353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4287353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.number_class(context=self)
4288353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
42897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def plus(self, a):
42907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Plus corresponds to unary prefix plus in Python.
42917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
42927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The operation is evaluated using the same rules as add; the
42937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        operation plus(a) is calculated as add('0', a) where the '0'
42947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        has the same exponent as the operand.
42957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
42969ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.plus(Decimal('1.3'))
42977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.3")
42989ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.plus(Decimal('-1.3'))
42997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1.3")
43007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
43017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__pos__(context=self)
43027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
43037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def power(self, a, b, modulo=None):
43047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Raises a to the power of b, to modulo if given.
43057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4306353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        With two arguments, compute a**b.  If a is negative then b
4307353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        must be integral.  The result will be inexact unless b is
4308353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        integral and the result is finite and can be expressed exactly
4309353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        in 'precision' digits.
4310353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4311353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        With three arguments, compute (a**b) % modulo.  For the
4312353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        three argument form, the following restrictions on the
4313353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        arguments hold:
4314353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4315353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - all three arguments must be integral
4316353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - b must be nonnegative
4317353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - at least one of a or b must be nonzero
4318353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - modulo must be nonzero and have at most 'precision' digits
4319353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4320353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result of pow(a, b, modulo) is identical to the result
4321353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        that would be obtained by computing (a**b) % modulo with
4322353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        unbounded precision, but is computed more efficiently.  It is
4323353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        always exact.
4324353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4325353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4326353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4327353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4328353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('2'), Decimal('3'))
43297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("8")
4330353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-2'), Decimal('3'))
4331353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-8")
4332353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('2'), Decimal('-3'))
43337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.125")
4334353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('1.7'), Decimal('8'))
43357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("69.7575744")
4336353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('10'), Decimal('0.301029996'))
4337353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2.00000000")
4338353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('Infinity'), Decimal('-1'))
43397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0")
4340353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('Infinity'), Decimal('0'))
43417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
4342353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('Infinity'), Decimal('1'))
43437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("Infinity")
4344353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-Infinity'), Decimal('-1'))
43457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0")
4346353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-Infinity'), Decimal('0'))
43477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
4348353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-Infinity'), Decimal('1'))
43497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-Infinity")
4350353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-Infinity'), Decimal('2'))
43517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("Infinity")
4352353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('0'), Decimal('0'))
43537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("NaN")
4354353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4355353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4356353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("11")
4357353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4358353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-11")
4359353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4360353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
4361353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4362353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("11")
4363353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4364353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("11729830")
4365353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4366353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-0")
4367353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4368353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1")
43697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
43707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__pow__(b, modulo, context=self)
43717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
43727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def quantize(self, a, b):
437359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
43747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
43757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The coefficient of the result is derived from that of the left-hand
437659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operand.  It may be rounded using the current rounding setting (if the
43777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exponent is being increased), multiplied by a positive power of ten (if
43787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        the exponent is being decreased), or is unchanged (if the exponent is
43797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        already equal to that of the right-hand operand).
43807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
43817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Unlike other operations, if the length of the coefficient after the
43827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        quantize operation would be greater than precision then an Invalid
438359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operation condition is raised.  This guarantees that, unless there is
438459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        an error condition, the exponent of the result of a quantize is always
43857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        equal to that of the right-hand operand.
43867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
43877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Also unlike other operations, quantize will never raise Underflow, even
43887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if the result is subnormal and inexact.
43897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
43909ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
43917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.170")
43929ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
43937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.17")
43949ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
43957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.2")
43969ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
43977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2")
43989ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
43997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0E+1")
44009ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
44017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-Infinity")
44029ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
44037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("NaN")
44049ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
44057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0")
44069ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
44077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0E+5")
44089ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
44097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("NaN")
44109ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
44117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("NaN")
44129ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
44137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("217.0")
44149ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
44157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("217")
44169ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
44177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.2E+2")
44189ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
44197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2E+2")
44207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
44217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.quantize(b, context=self)
44227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4423353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def radix(self):
4424353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Just returns 10, as this is Decimal, :)
4425353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4426353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.radix()
4427353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("10")
4428353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4429353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal(10)
4430353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
44317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def remainder(self, a, b):
44327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the remainder from integer division.
44337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The result is the residue of the dividend after the operation of
443559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        calculating integer division as described for divide-integer, rounded
44360d4c06e06e5ee1f3bb1fa8068114bd700d74864aNeal Norwitz        to precision digits if necessary.  The sign of the result, if
443759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        non-zero, is the same as that of the original dividend.
44387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        This operation will fail under the same conditions as integer division
44407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        (that is, if integer division on the same two operands would fail, the
44417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        remainder cannot be calculated).
44427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44439ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
44447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.1")
44459ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
44467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
44479ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
44487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1")
44499ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
44507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.2")
44519ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
44527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.1")
44539ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
44547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.0")
44557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
44567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__mod__(b, context=self)
44577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def remainder_near(self, a, b):
44597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns to be "a - b * n", where n is the integer nearest the exact
44607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        value of "x / b" (if two integers are equally near then the even one
446159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        is chosen).  If the result is equal to 0 then its sign will be the
44627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        sign of a.
44637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        This operation will fail under the same conditions as integer division
44657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        (that is, if integer division on the same two operands would fail, the
44667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        remainder cannot be calculated).
44677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44689ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
44697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0.9")
44709ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
44717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-2")
44729ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
44737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
44749ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
44757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-1")
44769ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
44777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.2")
44789ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
44797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.1")
44809ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
44817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0.3")
44827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
44837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.remainder_near(b, context=self)
44847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4485353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def rotate(self, a, b):
4486353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a rotated copy of a, b times.
4487353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4488353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The coefficient of the result is a rotated copy of the digits in
4489353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        the coefficient of the first operand.  The number of places of
4490353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotation is taken from the absolute value of the second operand,
4491353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        with the rotation being to the left if the second operand is
4492353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        positive or to the right otherwise.
4493353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4494353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4495353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("400000003")
4496353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4497353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("12")
4498353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4499353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("891234567")
4500353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4501353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("123456789")
4502353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4503353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("345678912")
4504353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4505353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.rotate(b, context=self)
4506353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
45077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def same_quantum(self, a, b):
45087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns True if the two operands have the same exponent.
45097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The result is never affected by either the sign or the coefficient of
45117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        either operand.
45127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45139ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
45147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        False
45159ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
45167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        True
45179ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
45187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        False
45199ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
45207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        True
45217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
45227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.same_quantum(b)
45237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4524353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def scaleb (self, a, b):
4525353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the first operand after adding the second value its exp.
4526353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4527353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4528353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0.0750")
4529353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4530353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("7.50")
4531353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4532353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("7.50E+3")
4533353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4534353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.scaleb (b, context=self)
4535353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4536353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def shift(self, a, b):
4537353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a shifted copy of a, b times.
4538353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4539353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The coefficient of the result is a shifted copy of the digits
4540353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        in the coefficient of the first operand.  The number of places
4541353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        to shift is taken from the absolute value of the second operand,
4542353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        with the shift being to the left if the second operand is
4543353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        positive or to the right otherwise.  Digits shifted into the
4544353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        coefficient are zeros.
4545353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4546353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4547353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("400000000")
4548353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4549353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("0")
4550353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4551353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1234567")
4552353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4553353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("123456789")
4554353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4555353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("345678900")
4556353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4557353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.shift(b, context=self)
4558353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
45597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def sqrt(self, a):
456059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        """Square root of a non-negative number to context precision.
45617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the result must be inexact, it is rounded using the round-half-even
45637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        algorithm.
45647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45659ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('0'))
45667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0")
45679ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('-0'))
45687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0")
45699ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('0.39'))
45707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.624499800")
45719ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('100'))
45727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("10")
45739ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('1'))
45747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1")
45759ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('1.0'))
45767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.0")
45779ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('1.00'))
45787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.0")
45799ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('7'))
45807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2.64575131")
45819ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('10'))
45827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("3.16227766")
45839ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.prec
45846ea484582238a65d44a76e3a831e3ba7c77a1a25Raymond Hettinger        9
45857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
45867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.sqrt(context=self)
45877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def subtract(self, a, b):
4589f33d01d304c349a7f555779c7c99930f1203adb7Georg Brandl        """Return the difference between the two operands.
45907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45919ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
45927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.23")
45939ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
45947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("0.00")
45959ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
45967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-0.77")
45977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
45987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__sub__(b, context=self)
45997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def to_eng_string(self, a):
46017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Converts a number to a string, using scientific notation.
46027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The operation is not affected by the context.
46047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
46057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.to_eng_string(context=self)
46067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def to_sci_string(self, a):
46087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Converts a number to a string, using scientific notation.
46097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The operation is not affected by the context.
46117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
46127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__str__(context=self)
46137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4614353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def to_integral_exact(self, a):
4615353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds to an integer.
4616353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4617353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        When the operand has a negative exponent, the result is the same
4618353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        as using the quantize() operation using the given operand as the
4619353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4620353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        of the operand as the precision setting; Inexact and Rounded flags
4621353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        are allowed in this operation.  The rounding mode is taken from the
4622353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.
4623353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4624353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4625353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("2")
4626353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('100'))
4627353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("100")
4628353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4629353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("100")
4630353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4631353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("102")
4632353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4633353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-102")
4634353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4635353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("1.0E+6")
4636353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4637353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("7.89E+77")
4638353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4639353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Decimal("-Infinity")
4640353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4641353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.to_integral_exact(context=self)
4642353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4643353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def to_integral_value(self, a):
46447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Rounds to an integer.
46457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        When the operand has a negative exponent, the result is the same
46477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        as using the quantize() operation using the given operand as the
46487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        left-hand-operand, 1E+0 as the right-hand-operand, and the precision
46497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        of the operand as the precision setting, except that no flags will
465059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        be set.  The rounding mode is taken from the context.
46517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4652353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('2.1'))
46537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("2")
4654353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('100'))
46557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("100")
4656353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('100.0'))
46577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("100")
4658353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('101.5'))
46597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("102")
4660353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
46617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-102")
4662353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
46637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("1.0E+6")
4664353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
46657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("7.89E+77")
4666353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
46677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Decimal("-Infinity")
46687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
4669353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.to_integral_value(context=self)
4670353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4671353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # the method name changed, but we provide also the old one, for compatibility
4672353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    to_integral = to_integral_value
46737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass _WorkRep(object):
46757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __slots__ = ('sign','int','exp')
467617931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger    # sign: 0 or 1
4677636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    # int:  int or long
46787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    # exp:  None, int, or string
46797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __init__(self, value=None):
46817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if value is None:
46827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.sign = None
4683636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self.int = 0
46847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.exp = None
468517931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        elif isinstance(value, Decimal):
468617931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            self.sign = value._sign
468772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self.int = int(value._int)
46887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.exp = value._exp
468917931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        else:
469017931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            # assert isinstance(value, tuple)
46917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.sign = value[0]
46927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.int = value[1]
46937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.exp = value[2]
46947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __repr__(self):
46967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
46977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __str__ = __repr__
46997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4702e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batistadef _normalize(op1, op2, prec = 0):
47037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Normalizes op1, op2 to have the same exp and length of coefficient.
47047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Done during addition.
47067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
4707353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if op1.exp < op2.exp:
47087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        tmp = op2
47097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        other = op1
47107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    else:
47117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        tmp = op1
47127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        other = op2
47137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4714353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4715353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Then adding 10**exp to tmp has the same effect (after rounding)
4716353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # as adding any positive quantity smaller than 10**exp; similarly
4717353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # for subtraction.  So if other is smaller than 10**exp we replace
4718353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # it with 10**exp.  This avoids tmp.exp - other.exp getting too large.
4719e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista    tmp_len = len(str(tmp.int))
4720e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista    other_len = len(str(other.int))
4721e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista    exp = tmp.exp + min(-1, tmp_len - prec - 2)
4722e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista    if other_len + other.exp - 1 < exp:
4723e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        other.int = 1
4724e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        other.exp = exp
4725636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
4726353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    tmp.int *= 10 ** (tmp.exp - other.exp)
4727353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    tmp.exp = other.exp
47287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    return op1, op2
47297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4730353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4731353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4732353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# This function from Tim Peters was taken from here:
4733353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4734353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# The correction being in the function definition is for speed, and
4735353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# the whole function is not resolved with math.log because of avoiding
4736353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# the use of floats.
4737353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _nbits(n, correction = {
4738353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '0': 4, '1': 3, '2': 2, '3': 2,
4739353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '4': 1, '5': 1, '6': 1, '7': 1,
4740353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '8': 0, '9': 0, 'a': 0, 'b': 0,
4741353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4742353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Number of bits in binary representation of the positive integer n,
4743353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    or 0 if n == 0.
4744353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
4745353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if n < 0:
4746353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        raise ValueError("The argument to _nbits should be nonnegative.")
4747353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    hex_n = "%x" % n
4748353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return 4*len(hex_n) - correction[hex_n[0]]
4749353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4750353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _sqrt_nearest(n, a):
4751353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Closest integer to the square root of the positive integer n.  a is
4752353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    an initial approximation to the square root.  Any positive integer
4753353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    will do for a, but the closer a is to the square root of n the
4754353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    faster convergence will be.
4755353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4756353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
4757353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if n <= 0 or a <= 0:
4758353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4759353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4760353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    b=0
4761353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    while a != b:
4762353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        b, a = a, a--n//a>>1
4763353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return a
4764353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4765353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _rshift_nearest(x, shift):
4766353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given an integer x and a nonnegative integer shift, return closest
4767353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    integer to x / 2**shift; use round-to-even in case of a tie.
4768353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4769353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
4770353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    b, q = 1L << shift, x >> shift
4771353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return q + (2*(x & (b-1)) + (q&1) > b)
4772353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4773353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _div_nearest(a, b):
4774353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Closest integer to a/b, a and b positive integers; rounds to even
4775353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    in the case of a tie.
4776353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4777353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
4778353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    q, r = divmod(a, b)
4779353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return q + (2*r + (q&1) > b)
4780353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4781353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _ilog(x, M, L = 8):
4782353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Integer approximation to M*log(x/M), with absolute error boundable
4783353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    in terms only of x/M.
4784353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4785353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    Given positive integers x and M, return an integer approximation to
4786353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    M * log(x/M).  For L = 8 and 0.1 <= x/M <= 10 the difference
4787353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    between the approximation and the exact result is at most 22.  For
4788353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15.  In
4789353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    both cases these are upper bounds on the error; it will usually be
4790353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    much smaller."""
4791353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4792353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # The basic algorithm is the following: let log1p be the function
4793353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # log1p(x) = log(1+x).  Then log(x/M) = log1p((x-M)/M).  We use
4794353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # the reduction
4795353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4796353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #    log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4797353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4798353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # repeatedly until the argument to log1p is small (< 2**-L in
4799353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # absolute value).  For small y we can use the Taylor series
4800353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # expansion
4801353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4802353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #    log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4803353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4804353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # truncating at T such that y**T is small enough.  The whole
4805353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # computation is carried out in a form of fixed-point arithmetic,
4806353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # with a real number z being represented by an integer
4807353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # approximation to z*M.  To avoid loss of precision, the y below
4808353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # is actually an integer approximation to 2**R*y*M, where R is the
4809353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # number of reductions performed so far.
4810353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4811353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    y = x-M
4812353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # argument reduction; R = number of reductions performed
4813353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    R = 0
4814353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    while (R <= L and long(abs(y)) << L-R >= M or
4815353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista           R > L and abs(y) >> R-L >= M):
4816353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        y = _div_nearest(long(M*y) << 1,
4817353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                         M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4818353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        R += 1
4819353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4820353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Taylor series with T terms
4821353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    T = -int(-10*len(str(M))//(3*L))
4822353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    yshift = _rshift_nearest(y, R)
4823353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    w = _div_nearest(M, T)
4824353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    for k in xrange(T-1, 0, -1):
4825353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4826353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4827353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return _div_nearest(w*y, M)
4828353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4829353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _dlog10(c, e, p):
4830353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given integers c, e and p with c > 0, p >= 0, compute an integer
4831353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    approximation to 10**p * log10(c*10**e), with an absolute error of
4832353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    at most 1.  Assumes that c*10**e is not exactly 1."""
4833353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4834353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # increase precision by 2; compensate for this by dividing
4835353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # final result by 100
4836353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    p += 2
4837353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4838353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # write c*10**e as d*10**f with either:
4839353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #   f >= 0 and 1 <= d <= 10, or
4840353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #   f <= 0 and 0.1 <= d <= 1.
4841353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Thus for c*10**e close to 1, f = 0
4842353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    l = len(str(c))
4843353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    f = e+l - (e+l >= 1)
4844353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4845353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if p > 0:
4846353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        M = 10**p
4847353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        k = e+p-f
4848353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if k >= 0:
4849353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c *= 10**k
4850353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
4851353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = _div_nearest(c, 10**-k)
4852353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4853353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = _ilog(c, M) # error < 5 + 22 = 27
4854be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        log_10 = _log10_digits(p) # error < 1
4855353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = _div_nearest(log_d*M, log_10)
4856353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_tenpower = f*M # exact
4857353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
4858353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = 0  # error < 2.31
4859353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4860353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4861353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return _div_nearest(log_tenpower+log_d, 100)
4862353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4863353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _dlog(c, e, p):
4864353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given integers c, e and p with c > 0, compute an integer
4865353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    approximation to 10**p * log(c*10**e), with an absolute error of
4866353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    at most 1.  Assumes that c*10**e is not exactly 1."""
4867353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4868353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Increase precision by 2. The precision increase is compensated
4869353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # for at the end with a division by 100.
4870353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    p += 2
4871353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4872353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4873353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # or f <= 0 and 0.1 <= d <= 1.  Then we can compute 10**p * log(c*10**e)
4874353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # as 10**p * log(d) + 10**p*f * log(10).
4875353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    l = len(str(c))
4876353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    f = e+l - (e+l >= 1)
4877353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4878353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # compute approximation to 10**p*log(d), with error < 27
4879353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if p > 0:
4880353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        k = e+p-f
4881353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if k >= 0:
4882353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c *= 10**k
4883353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
4884353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = _div_nearest(c, 10**-k)  # error of <= 0.5 in c
4885353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4886353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # _ilog magnifies existing error in c by a factor of at most 10
4887353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4888353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
4889353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # p <= 0: just approximate the whole thing by 0; error < 2.31
4890353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = 0
4891353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4892be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    # compute approximation to f*10**p*log(10), with error < 11.
4893353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if f:
4894be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        extra = len(str(abs(f)))-1
4895be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        if p + extra >= 0:
4896be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4897be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4898be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
4899353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
4900353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            f_log_ten = 0
4901353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
4902353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        f_log_ten = 0
4903353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4904be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
4905353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return _div_nearest(f_log_ten + log_d, 100)
4906353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4907be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batistaclass _Log10Memoize(object):
4908be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    """Class to compute, store, and allow retrieval of, digits of the
4909be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    constant log(10) = 2.302585....  This constant is needed by
4910be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4911be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    def __init__(self):
4912be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        self.digits = "23025850929940456840179914546843642076011014886"
4913be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista
4914be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    def getdigits(self, p):
4915be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        """Given an integer p >= 0, return floor(10**p)*log(10).
4916be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista
4917be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        For example, self.getdigits(3) returns 2302.
4918be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        """
4919be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        # digits are stored as a string, for quick conversion to
4920be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        # integer in the case that we've already computed enough
4921be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        # digits; the stored digits should always be correct
4922be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        # (truncated, not rounded to nearest).
4923be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        if p < 0:
4924be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            raise ValueError("p should be nonnegative")
4925be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista
4926be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        if p >= len(self.digits):
4927be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # compute p+3, p+6, p+9, ... digits; continue until at
4928be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # least one of the extra digits is nonzero
4929be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            extra = 3
4930be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            while True:
4931be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                # compute p+extra digits, correct to within 1ulp
4932be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                M = 10**(p+extra+2)
4933be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                digits = str(_div_nearest(_ilog(10*M, M), 100))
4934be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                if digits[-extra:] != '0'*extra:
4935be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                    break
4936be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                extra += 3
4937be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # keep all reliable digits so far; remove trailing zeros
4938be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # and next nonzero digit
4939be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            self.digits = digits.rstrip('0')[:-1]
4940be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        return int(self.digits[:p+1])
4941be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista
4942be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista_log10_digits = _Log10Memoize().getdigits
4943be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista
4944353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _iexp(x, M, L=8):
4945353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given integers x and M, M > 0, such that x/M is small in absolute
4946353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    value, compute an integer approximation to M*exp(x/M).  For 0 <=
4947353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4948353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    is usually much smaller)."""
4949353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4950353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Algorithm: to compute exp(z) for a real number z, first divide z
4951353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # by a suitable power R of 2 so that |z/2**R| < 2**-L.  Then
4952353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
4953353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # series
4954353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4955353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #     expm1(x) = x + x**2/2! + x**3/3! + ...
4956353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4957353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Now use the identity
4958353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4959353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #     expm1(2x) = expm1(x)*(expm1(x)+2)
4960353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4961353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # R times to compute the sequence expm1(z/2**R),
4962353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
4963353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4964353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Find R such that x/2**R/M <= 2**-L
4965353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    R = _nbits((long(x)<<L)//M)
4966353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4967353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Taylor series.  (2**L)**T > M
4968353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    T = -int(-10*len(str(M))//(3*L))
4969353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    y = _div_nearest(x, T)
4970353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    Mshift = long(M)<<R
4971353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    for i in xrange(T-1, 0, -1):
4972353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        y = _div_nearest(x*(Mshift + y), Mshift * i)
4973353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4974353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Expansion
4975353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    for k in xrange(R-1, -1, -1):
4976353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Mshift = long(M)<<(k+2)
4977353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        y = _div_nearest(y*(y+Mshift), Mshift)
4978353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4979353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return M+y
4980353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4981353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _dexp(c, e, p):
4982353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Compute an approximation to exp(c*10**e), with p decimal places of
4983353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    precision.
4984353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4985be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    Returns integers d, f such that:
4986353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4987353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista      10**(p-1) <= d <= 10**p, and
4988353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista      (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
4989353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4990353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    In other words, d*10**f is an approximation to exp(c*10**e) with p
4991353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    digits of precision, and with an error in d of at most 1.  This is
4992353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    almost, but not quite, the same as the error being < 1ulp: when d
4993353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    = 10**(p-1) the error could be up to 10 ulp."""
4994353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4995353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
4996353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    p += 2
4997353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4998be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    # compute log(10) with extra precision = adjusted exponent of c*10**e
4999353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    extra = max(0, e + len(str(c)) - 1)
5000353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    q = p + extra
5001353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5002be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
5003353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # rounding down
5004353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    shift = e+q
5005353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if shift >= 0:
5006353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        cshift = c*10**shift
5007353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
5008353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        cshift = c//10**-shift
5009be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    quot, rem = divmod(cshift, _log10_digits(q))
5010353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5011353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # reduce remainder back to original precision
5012353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    rem = _div_nearest(rem, 10**extra)
5013353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5014353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # error in result of _iexp < 120;  error after division < 0.62
5015353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5016353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5017353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _dpower(xc, xe, yc, ye, p):
5018353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5019353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    y = yc*10**ye, compute x**y.  Returns a pair of integers (c, e) such that:
5020353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5021353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista      10**(p-1) <= c <= 10**p, and
5022353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista      (c-1)*10**e < x**y < (c+1)*10**e
5023353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5024353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    in other words, c*10**e is an approximation to x**y with p digits
5025353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    of precision, and with an error in c of at most 1.  (This is
5026353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    almost, but not quite, the same as the error being < 1ulp: when c
5027353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    == 10**(p-1) we can only guarantee error < 10ulp.)
5028353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5029353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    We assume that: x is positive and not equal to 1, and y is nonzero.
5030353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
5031353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5032353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Find b such that 10**(b-1) <= |y| <= 10**b
5033353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    b = len(str(abs(yc))) + ye
5034353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5035353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5036353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    lxc = _dlog(xc, xe, p+b+1)
5037353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5038353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5039353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    shift = ye-b
5040353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if shift >= 0:
5041353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        pc = lxc*yc*10**shift
5042353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
5043353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        pc = _div_nearest(lxc*yc, 10**-shift)
5044353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5045353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if pc == 0:
5046353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # we prefer a result that isn't exactly 1; this makes it
5047353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # easier to compute a correctly rounded result in __pow__
5048353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5049353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            coeff, exp = 10**(p-1)+1, 1-p
5050353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
5051353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            coeff, exp = 10**p-1, -p
5052353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
5053353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        coeff, exp = _dexp(pc, -(p+1), p+1)
5054353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        coeff = _div_nearest(coeff, 10)
5055353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exp += 1
5056353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return coeff, exp
5058353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _log10_lb(c, correction = {
5060353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5061353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '6': 23, '7': 16, '8': 10, '9': 5}):
5062353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Compute a lower bound for 100*log10(c) for a positive integer c."""
5063353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if c <= 0:
5064353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        raise ValueError("The argument to _log10_lb should be nonnegative.")
5065353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    str_c = str(c)
5066353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return 100*len(str_c) - correction[str_c[0]]
5067353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
506859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Helper Functions ####################################################
50697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
5070353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _convert_other(other, raiseit=False):
5071636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    """Convert other to Decimal.
5072636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
5073636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    Verifies that it's ok to use in an implicit construction.
5074636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    """
5075636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    if isinstance(other, Decimal):
5076636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        return other
5077636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    if isinstance(other, (int, long)):
5078636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        return Decimal(other)
5079353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if raiseit:
5080353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        raise TypeError("Unable to convert %s to Decimal" % other)
5081267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger    return NotImplemented
5082636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
508359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Setup Specific Contexts ############################################
50847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
50857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# The default context prototype used by Context()
5086fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger# Is mutable, so that new contexts can have different default values
50877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
50887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerDefaultContext = Context(
50896ea484582238a65d44a76e3a831e3ba7c77a1a25Raymond Hettinger        prec=28, rounding=ROUND_HALF_EVEN,
5090bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        traps=[DivisionByZero, Overflow, InvalidOperation],
5091bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        flags=[],
509299148e7eaad7741fbfb0822009b7c9b216ecc227Raymond Hettinger        Emax=999999999,
509399148e7eaad7741fbfb0822009b7c9b216ecc227Raymond Hettinger        Emin=-999999999,
5094e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger        capitals=1
50957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger)
50967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
50977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# Pre-made alternate contexts offered by the specification
50987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# Don't change these; the user should be able to select these
50997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# contexts and be able to reproduce results from other implementations
51007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# of the spec.
51017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51029ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond HettingerBasicContext = Context(
51037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        prec=9, rounding=ROUND_HALF_UP,
5104bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5105bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        flags=[],
51067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger)
51077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51089ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond HettingerExtendedContext = Context(
51096ea484582238a65d44a76e3a831e3ba7c77a1a25Raymond Hettinger        prec=9, rounding=ROUND_HALF_EVEN,
5110bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        traps=[],
5111bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        flags=[],
51127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger)
51137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
511559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### crud for parsing strings #############################################
51167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerimport re
51177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
511872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# Regular expression used for parsing numeric strings.  Additional
511972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# comments:
512072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista#
512172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
512272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# whitespace.  But note that the specification disallows whitespace in
512372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# a numeric string.
512472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista#
512572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# 2. For finite numbers (not infinities and NaNs) the body of the
512672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# number between the optional sign and the optional exponent must have
512772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# at least one decimal digit, possibly after the decimal point.  The
512872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# lookahead expression '(?=\d|\.\d)' checks this.
512972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista#
513072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# As the flag UNICODE is not enabled here, we're explicitly avoiding any
513172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# other meaning for \d than the numbers [0-9].
51327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
513372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batistaimport re
513472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista_parser = re.compile(r"""     # A numeric string consists of:
51357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger#    \s*
513672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    (?P<sign>[-+])?           # an optional sign, followed by either...
51377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    (
513872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        (?=\d|\.\d)           # ...a number (with at least one digit)
513972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        (?P<int>\d*)          # consisting of a (possibly empty) integer part
514072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        (\.(?P<frac>\d*))?    # followed by an optional fractional part
514172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
51427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    |
514372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        Inf(inity)?           # ...an infinity, or...
514472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    |
514572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        (?P<signal>s)?        # ...an (optionally signaling)
514672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        NaN                   # NaN
514772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        (?P<diag>\d*)         # with (possibly empty) diagnostic information.
51487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    )
51497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger#    \s*
51507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    $
515172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista""", re.VERBOSE | re.IGNORECASE).match
51527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51532ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista_all_zeros = re.compile('0*$').match
51542ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista_exact_half = re.compile('50*$').match
51557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerdel re
51567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51570d4c06e06e5ee1f3bb1fa8068114bd700d74864aNeal Norwitz
515872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista##### Useful Constants (internal use only) ################################
51597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
516072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# Reusable defaults
516172bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaInf = Decimal('Inf')
516272bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistanegInf = Decimal('-Inf')
516372bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaNaN = Decimal('NaN')
516472bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaDec_0 = Decimal(0)
516572bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaDec_p1 = Decimal(1)
516672bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaDec_n1 = Decimal(-1)
516772bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaDec_p2 = Decimal(2)
516872bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaDec_n2 = Decimal(-2)
51697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
517072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# Infsign[sign] is infinity w/ that sign
517172bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaInfsign = (Inf, negInf)
51727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerif __name__ == '__main__':
51767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    import doctest, sys
51777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    doctest.testmod(sys.modules[__name__])
5178