decimal.py revision 6a123cb7827859748a0096570dfbb5ceba0e59dc
17c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# Copyright (c) 2004 Python Software Foundation.
27c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# All rights reserved.
37c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# Written by Eric Price <eprice at tjhsst.edu>
57c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger#    and Facundo Batista <facundo at taniquetil.com.ar>
67c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger#    and Raymond Hettinger <python at rcn.com>
71f34eb17b501687c1251678bcffab9accd432591Fred Drake#    and Aahz <aahz at pobox.com>
87c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger#    and Tim Peters
97c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1027dbcf2162c61d5ba248c57c89ff4fa3d85a21c7Raymond Hettinger# This module is currently Py2.3 compatible and should be kept that way
1127dbcf2162c61d5ba248c57c89ff4fa3d85a21c7Raymond Hettinger# unless a major compelling advantage arises.  IOW, 2.3 compatibility is
1227dbcf2162c61d5ba248c57c89ff4fa3d85a21c7Raymond Hettinger# strongly preferred, but not guaranteed.
1327dbcf2162c61d5ba248c57c89ff4fa3d85a21c7Raymond Hettinger
1427dbcf2162c61d5ba248c57c89ff4fa3d85a21c7Raymond Hettinger# Also, this module should be kept in sync with the latest updates of
1527dbcf2162c61d5ba248c57c89ff4fa3d85a21c7Raymond Hettinger# the IBM specification as it evolves.  Those updates will be treated
1627dbcf2162c61d5ba248c57c89ff4fa3d85a21c7Raymond Hettinger# as bug fixes (deviation from the spec is a compatibility, usability
1727dbcf2162c61d5ba248c57c89ff4fa3d85a21c7Raymond Hettinger# bug) and will be backported.  At this point the spec is stabilizing
1827dbcf2162c61d5ba248c57c89ff4fa3d85a21c7Raymond Hettinger# and the updates are becoming fewer, smaller, and less significant.
197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger"""
217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerThis is a Py2.3 implementation of decimal floating point arithmetic based on
227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerthe General Decimal Arithmetic Specification:
237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    www2.hursley.ibm.com/decimal/decarith.html
257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
260ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettingerand IEEE standard 854-1987:
277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerDecimal floating point has finite precision with arbitrarily large bounds.
317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo BatistaThe purpose of this module is to support arithmetic using familiar
3359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista"schoolhouse" rules and to avoid some of the tricky representation
347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerissues associated with binary floating point.  The package is especially
357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingeruseful for financial applications or for contexts where users have
367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerexpectations that are at odds with binary floating point (for instance,
377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerin binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
38abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettingerof the expected Decimal('0.00') returned by decimal floating point).
397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerHere are some examples of using the decimal module:
417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> from decimal import *
43bd7f76dd04780304c397323ae994092ce759d5a2Raymond Hettinger>>> setcontext(ExtendedContext)
447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> Decimal(0)
45abe32371878dcaea31c835e10144fdaa2eca6492Raymond HettingerDecimal('0')
46abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger>>> Decimal('1')
47abe32371878dcaea31c835e10144fdaa2eca6492Raymond HettingerDecimal('1')
48abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger>>> Decimal('-.0123')
49abe32371878dcaea31c835e10144fdaa2eca6492Raymond HettingerDecimal('-0.0123')
507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> Decimal(123456)
51abe32371878dcaea31c835e10144fdaa2eca6492Raymond HettingerDecimal('123456')
52abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger>>> Decimal('123.45e12345678901234567890')
53abe32371878dcaea31c835e10144fdaa2eca6492Raymond HettingerDecimal('1.2345E+12345678901234567892')
54abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger>>> Decimal('1.33') + Decimal('1.27')
55abe32371878dcaea31c835e10144fdaa2eca6492Raymond HettingerDecimal('2.60')
56abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger>>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
57abe32371878dcaea31c835e10144fdaa2eca6492Raymond HettingerDecimal('-2.20')
587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> dig = Decimal(1)
597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print dig / Decimal(3)
607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger0.333333333
617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> getcontext().prec = 18
627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print dig / Decimal(3)
637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger0.333333333333333333
647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print dig.sqrt()
657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger1
667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print Decimal(3).sqrt()
677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger1.73205080756887729
687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print Decimal(3) ** 123
697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger4.85192780976896427E+58
707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> inf = Decimal(1) / Decimal(0)
717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print inf
727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerInfinity
737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> neginf = Decimal(-1) / Decimal(0)
747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print neginf
757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger-Infinity
767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print neginf + inf
777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerNaN
787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print neginf * inf
797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger-Infinity
807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print dig / 0
817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerInfinity
82bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger>>> getcontext().traps[DivisionByZero] = 1
837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print dig / 0
847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerTraceback (most recent call last):
857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger  ...
867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger  ...
877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger  ...
887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerDivisionByZero: x / 0
897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> c = Context()
90bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger>>> c.traps[InvalidOperation] = 0
915aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger>>> print c.flags[InvalidOperation]
927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger0
937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> c.divide(Decimal(0), Decimal(0))
94abe32371878dcaea31c835e10144fdaa2eca6492Raymond HettingerDecimal('NaN')
95bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger>>> c.traps[InvalidOperation] = 1
965aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger>>> print c.flags[InvalidOperation]
977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger1
985aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger>>> c.flags[InvalidOperation] = 0
995aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger>>> print c.flags[InvalidOperation]
1007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger0
1017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print c.divide(Decimal(0), Decimal(0))
1027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerTraceback (most recent call last):
1037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger  ...
1047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger  ...
1057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger  ...
1065aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond HettingerInvalidOperation: 0 / 0
1075aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger>>> print c.flags[InvalidOperation]
1087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger1
1095aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger>>> c.flags[InvalidOperation] = 0
110bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger>>> c.traps[InvalidOperation] = 0
1117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>> print c.divide(Decimal(0), Decimal(0))
1127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerNaN
1135aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger>>> print c.flags[InvalidOperation]
1147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger1
1157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger>>>
1167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger"""
1177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger__all__ = [
1197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    # Two major classes
1207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    'Decimal', 'Context',
1217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    # Contexts
1239ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger    'DefaultContext', 'BasicContext', 'ExtendedContext',
1247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    # Exceptions
126d87ac8f24da5dce860b559b69e6af59edd2c3eecRaymond Hettinger    'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
127d87ac8f24da5dce860b559b69e6af59edd2c3eecRaymond Hettinger    'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
1287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    # Constants for use in setting up contexts
1307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
131353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
1327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    # Functions for manipulating contexts
1348b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    'setcontext', 'getcontext', 'localcontext'
1357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger]
1367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
137eb2608415ee4eb8aaea746f6a313937e264d0cdaRaymond Hettingerimport copy as _copy
1387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
139097a1903035f9ee2efb1953306123f183124125dRaymond Hettingertry:
140097a1903035f9ee2efb1953306123f183124125dRaymond Hettinger    from collections import namedtuple as _namedtuple
141097a1903035f9ee2efb1953306123f183124125dRaymond Hettinger    DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
142097a1903035f9ee2efb1953306123f183124125dRaymond Hettingerexcept ImportError:
143097a1903035f9ee2efb1953306123f183124125dRaymond Hettinger    DecimalTuple = lambda *args: args
144097a1903035f9ee2efb1953306123f183124125dRaymond Hettinger
14559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista# Rounding
1460ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_DOWN = 'ROUND_DOWN'
1470ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_HALF_UP = 'ROUND_HALF_UP'
1480ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
1490ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_CEILING = 'ROUND_CEILING'
1500ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_FLOOR = 'ROUND_FLOOR'
1510ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_UP = 'ROUND_UP'
1520ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond HettingerROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
153353750c405c9099d0be69c6af1d17037b38c4ddfFacundo BatistaROUND_05UP = 'ROUND_05UP'
1547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
15559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista# Errors
1567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass DecimalException(ArithmeticError):
1585aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger    """Base exception class.
1597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Used exceptions derive from this.
1617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    If an exception derives from another exception besides this (such as
1627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
1637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    called if the others are present.  This isn't actually used for
1647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    anything, though.
1657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
166cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis    handle  -- Called when context._raise_error is called and the
167cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis               trap_enabler is set.  First argument is self, second is the
168cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis               context.  More arguments can be given, those being after
169cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis               the explanation in _raise_error (For example,
170cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis               context._raise_error(NewError, '(-x)!', self._sign) would
171cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis               call NewError().handle(context, self._sign).)
172cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
1737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    To define a new exception, it should be sufficient to have it derive
1747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    from DecimalException.
1757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
1767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, *args):
1777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        pass
1787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Clamped(DecimalException):
1817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Exponent of a 0 changed to fit bounds.
1827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals clamped if the exponent of a result has been
1847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    altered in order to fit the constraints of a specific concrete
18559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    representation.  This may occur when the exponent of a zero result would
18659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    be outside the bounds of a representation, or when a large normal
18759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    number would have an encoded exponent that cannot be represented.  In
1887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    this latter case, the exponent is reduced to fit and the corresponding
1897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    number of zero digits are appended to the coefficient ("fold-down").
1907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
1917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass InvalidOperation(DecimalException):
1937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """An invalid operation was performed.
1947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Various bad things cause this:
1967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Something creates a signaling NaN
1987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    -INF + INF
19959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    0 * (+-)INF
20059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    (+-)INF / (+-)INF
2017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    x % 0
2027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    (+-)INF % x
2037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    x._rescale( non-integer )
2047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    sqrt(-x) , x > 0
2057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    0 ** 0
2067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    x ** (non-integer)
2077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    x ** (+-)INF
2087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    An operand is invalid
209353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
210353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    The result of the operation after these is a quiet positive NaN,
211353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    except when the cause is a signaling NaN, in which case the result is
212353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    also a quiet NaN, but with the original sign, and an optional
213353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    diagnostic information.
2147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
2157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, *args):
2167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if args:
2170f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista            ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
2180f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista            return ans._fix_nan(context)
2197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return NaN
2207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass ConversionSyntax(InvalidOperation):
2227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Trying to convert badly formed string.
2237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals invalid-operation if an string is being
2257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    converted to a number and it does not conform to the numeric string
22659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    syntax.  The result is [0,qNaN].
2277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
228cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis    def handle(self, context, *args):
229353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return NaN
2307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass DivisionByZero(DecimalException, ZeroDivisionError):
2327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Division by 0.
2337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals division-by-zero if division of a finite number
2357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    by zero was attempted (during a divide-integer or divide operation, or a
2367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    power operation with negative right-hand operand), and the dividend was
2377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    not zero.
2387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The result of the operation is [sign,inf], where sign is the exclusive
2407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    or of the signs of the operands for divide, or is 1 for an odd power of
2417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    -0, for power.
2427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
243cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
244cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista    def handle(self, context, sign, *args):
2457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return Infsign[sign]
2467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass DivisionImpossible(InvalidOperation):
2487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Cannot perform the division adequately.
2497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals invalid-operation if the integer result of a
2517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    divide-integer or remainder operation had too many digits (would be
25259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    longer than precision).  The result is [0,qNaN].
2537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
254cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
2557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, *args):
256cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return NaN
2577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass DivisionUndefined(InvalidOperation, ZeroDivisionError):
2597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Undefined result of division.
2607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals invalid-operation if division by zero was
2627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    attempted (during a divide-integer, divide, or remainder operation), and
26359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    the dividend is also zero.  The result is [0,qNaN].
2647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
265cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
266cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista    def handle(self, context, *args):
2677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return NaN
2687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Inexact(DecimalException):
2707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Had to round, losing information.
2717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals inexact whenever the result of an operation is
2737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    not exact (that is, it needed to be rounded and any discarded digits
27459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    were non-zero), or if an overflow or underflow condition occurs.  The
2757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    result in all cases is unchanged.
2767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The inexact signal may be tested (or trapped) to determine if a given
2787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    operation (or sequence of operations) was inexact.
2797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
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    """
3067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Subnormal(DecimalException):
3087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Exponent < Emin before rounding.
3097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals subnormal whenever the result of a conversion or
3117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    operation is subnormal (that is, its adjusted exponent is less than
31259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    Emin, before any rounding).  The result in all cases is unchanged.
3137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The subnormal signal may be tested (or trapped) to determine if a given
3157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    or operation (or sequence of operations) yielded a subnormal result.
3167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
3177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Overflow(Inexact, Rounded):
3197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Numerical overflow.
3207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals overflow if the adjusted exponent of a result
3227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    (from a conversion or from an operation that is not an attempt to divide
3237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    by zero), after rounding, would be greater than the largest value that
3247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    can be handled by the implementation (the value Emax).
3257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The result depends on the rounding mode:
3277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    For round-half-up and round-half-even (and for round-half-down and
3297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    round-up, if implemented), the result of the operation is [sign,inf],
33059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    where sign is the sign of the intermediate result.  For round-down, the
3317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    result is the largest finite number that can be represented in the
33259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    current precision, with the sign of the intermediate result.  For
3337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    round-ceiling, the result is the same as for round-down if the sign of
33459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    the intermediate result is 1, or is [0,inf] otherwise.  For round-floor,
3357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    the result is the same as for round-down if the sign of the intermediate
33659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    result is 0, or is [1,inf] otherwise.  In all cases, Inexact and Rounded
3377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    will also be raised.
3380f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista    """
339cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
3407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def handle(self, context, sign, *args):
3417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
342353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                ROUND_HALF_DOWN, ROUND_UP):
3437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return Infsign[sign]
3447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if sign == 0:
3457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if context.rounding == ROUND_CEILING:
3467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return Infsign[sign]
34772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(sign, '9'*context.prec,
34872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                            context.Emax-context.prec+1)
3497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if sign == 1:
3507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if context.rounding == ROUND_FLOOR:
3517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return Infsign[sign]
35272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(sign, '9'*context.prec,
35372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                             context.Emax-context.prec+1)
3547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Underflow(Inexact, Rounded, Subnormal):
3577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Numerical underflow with result rounded to 0.
3587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    This occurs and signals underflow if a result is inexact and the
3607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    adjusted exponent of the result would be smaller (more negative) than
3617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    the smallest value that can be handled by the implementation (the value
36259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    Emin).  That is, the result is both inexact and subnormal.
3637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    The result after an underflow will be a subnormal number rounded, if
36559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    necessary, so that its exponent is not less than Etiny.  This may result
3667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    in 0 with the sign of the intermediate result and an exponent of Etiny.
3677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    In all cases, Inexact, Rounded, and Subnormal will also be raised.
3697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
3707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3715aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger# List of public traps and flags
372fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
373cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis           Underflow, InvalidOperation, Subnormal]
3747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3755aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger# Map conditions (per the spec) to signals
3765aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger_condition_map = {ConversionSyntax:InvalidOperation,
3775aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger                  DivisionImpossible:InvalidOperation,
3785aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger                  DivisionUndefined:InvalidOperation,
3795aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger                  InvalidContext:InvalidOperation}
3807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
38159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Context Functions ##################################################
3827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
383ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger# The getcontext() and setcontext() function manage access to a thread-local
384ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger# current context.  Py2.4 offers direct support for thread locals.  If that
385ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger# is not available, use threading.currentThread() which is slower but will
3867e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger# work for older Pythons.  If threads are not part of the build, create a
387cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis# mock threading object with threading.local() returning the module namespace.
3887e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger
3897e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettingertry:
3907e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    import threading
3917e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettingerexcept ImportError:
3927e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    # Python was compiled without threads; create a mock object instead
3937e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    import sys
39459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    class MockThreading(object):
3957e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger        def local(self, sys=sys):
3967e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger            return sys.modules[__name__]
3977e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    threading = MockThreading()
3987e71fa5cfa250968eafdb77356621e3a9bbb0648Raymond Hettinger    del sys, MockThreading
399ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
400ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettingertry:
401ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    threading.local
402ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
403ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettingerexcept AttributeError:
404ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
40559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # To fix reloading, force it to create a new context
40659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # Old contexts have different exceptions in their dicts, making problems.
407ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    if hasattr(threading.currentThread(), '__decimal_context__'):
408ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        del threading.currentThread().__decimal_context__
409ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
410ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    def setcontext(context):
411ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """Set this thread's context to context."""
412ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        if context in (DefaultContext, BasicContext, ExtendedContext):
4139fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger            context = context.copy()
41461992efc4bb413ae7a19752215eca5af09be6b6dRaymond Hettinger            context.clear_flags()
4157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        threading.currentThread().__decimal_context__ = context
416ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
417ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    def getcontext():
418ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """Returns this thread's context.
419ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
420ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        If this thread does not yet have a context, returns
421ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        a new context and sets this thread's context.
422ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        New contexts are copies of DefaultContext.
423ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """
424ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        try:
425ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            return threading.currentThread().__decimal_context__
426ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        except AttributeError:
427ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            context = Context()
428ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            threading.currentThread().__decimal_context__ = context
429ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            return context
430ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
431ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettingerelse:
432ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
433ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    local = threading.local()
4349fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger    if hasattr(local, '__decimal_context__'):
4359fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        del local.__decimal_context__
436ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
437ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    def getcontext(_local=local):
438ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """Returns this thread's context.
439ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
440ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        If this thread does not yet have a context, returns
441ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        a new context and sets this thread's context.
442ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        New contexts are copies of DefaultContext.
443ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """
444ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        try:
445ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            return _local.__decimal_context__
446ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        except AttributeError:
447ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            context = Context()
448ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            _local.__decimal_context__ = context
449ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger            return context
450ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
451ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger    def setcontext(context, _local=local):
452ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        """Set this thread's context to context."""
453ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        if context in (DefaultContext, BasicContext, ExtendedContext):
4549fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger            context = context.copy()
45561992efc4bb413ae7a19752215eca5af09be6b6dRaymond Hettinger            context.clear_flags()
456ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger        _local.__decimal_context__ = context
457ef66debd7ef590304466d13dde4082632750fa7cRaymond Hettinger
458cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis    del threading, local        # Don't contaminate the namespace
4597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4608b6999b4c5fab174090be263ba90f193bdede141Nick Coghlandef localcontext(ctx=None):
4618b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """Return a context manager for a copy of the supplied context
4628b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan
4638b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    Uses a copy of the current context if no context is specified
4648b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    The returned context manager creates a local decimal context
4658b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    in a with statement:
4668b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan        def sin(x):
4678b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan             with localcontext() as ctx:
4688b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 ctx.prec += 2
4698b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # Rest of sin calculation algorithm
4708b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # uses a precision 2 greater than normal
47159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista             return +s  # Convert result to normal precision
4728b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan
4738b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan         def sin(x):
4748b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan             with localcontext(ExtendedContext):
4758b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # Rest of sin calculation algorithm
4768b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # uses the Extended Context from the
4778b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan                 # General Decimal Arithmetic Specification
47859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista             return +s  # Convert result to normal context
4798b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan
4808b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """
481681d86743c21773bb00508dbacb05ed9012388d8Neal Norwitz    # The string below can't be included in the docstring until Python 2.6
4828b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    # as the doctest module doesn't understand __future__ statements
4838b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """
4848b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> from __future__ import with_statement
4858b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> print getcontext().prec
4868b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    28
4878b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> with localcontext():
4888b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...     ctx = getcontext()
489495df4716fce4156c1eb110f9342297164eecbb6Raymond Hettinger    ...     ctx.prec += 2
4908b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...     print ctx.prec
4918b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...
4928b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    30
4938b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> with localcontext(ExtendedContext):
4948b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...     print getcontext().prec
4958b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    ...
4968b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    9
4978b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    >>> print getcontext().prec
4988b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    28
4998b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """
500ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlan    if ctx is None: ctx = getcontext()
501ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlan    return _ContextManager(ctx)
5028b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan
5037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
50459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Decimal class #######################################################
5057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
5067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Decimal(object):
5077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Floating point class for decimal arithmetic."""
5087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
509636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    __slots__ = ('_exp','_int','_sign', '_is_special')
510636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    # Generally, the value of the Decimal instance is given by
511636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    #  (-1)**_sign * _int * 10**_exp
512636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    # Special values are signified by _is_special == True
5137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
514dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger    # We're immutable, so use __new__ not __init__
515636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    def __new__(cls, value="0", context=None):
5167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Create a decimal point instance.
5177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
5187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        >>> Decimal('3.14')              # string input
519abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('3.14')
52059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        >>> Decimal((0, (3, 1, 4), -2))  # tuple (sign, digit_tuple, exponent)
521abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('3.14')
5227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        >>> Decimal(314)                 # int or long
523abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('314')
5247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        >>> Decimal(Decimal(314))        # another decimal instance
525abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('314')
52659bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson        >>> Decimal('  3.14  \\n')        # leading and trailing whitespace okay
527abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('3.14')
5287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
5297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
53072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # Note that the coefficient, self._int, is actually stored as
53172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # a string rather than as a tuple of digits.  This speeds up
53272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # the "digits to integer" and "integer to digits" conversions
53372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # that are used in almost every arithmetic operation on
53472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # Decimals.  This is an internal detail: the as_tuple function
53572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # and the Decimal constructor still deal with tuples of
53672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        # digits.
53772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista
538636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        self = object.__new__(cls)
539636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
5400d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        # From a string
5410d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        # REs insist on real strings, so we can too.
5420d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista        if isinstance(value, basestring):
54359bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson            m = _parser(value.strip())
5440d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            if m is None:
5450d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                if context is None:
5460d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                    context = getcontext()
5470d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                return context._raise_error(ConversionSyntax,
5480d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                                "Invalid literal for Decimal: %r" % value)
549636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
5500d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            if m.group('sign') == "-":
5510d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                self._sign = 1
5520d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            else:
5530d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                self._sign = 0
5540d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            intpart = m.group('int')
5550d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista            if intpart is not None:
5560d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                # finite number
5570d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                fracpart = m.group('frac')
5580d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                exp = int(m.group('exp') or '0')
5590d157a0154140dc6dcd491d62df3a2b66367be15Facundo Batista                if fracpart is not None:
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
6640f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista        1 if NaN
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',
7100f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista                                        self)
711636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if other_is_nan == 2:
712636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return context._raise_error(InvalidOperation, 'sNaN',
7130f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista                                        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
7202fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    def _compare_check_nans(self, other, context):
7212fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        """Version of _check_nans used for the signaling comparisons
7222fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        compare_signal, __le__, __lt__, __ge__, __gt__.
7232fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson
7242fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        Signal InvalidOperation if either self or other is a (quiet
7252fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        or signaling) NaN.  Signaling NaNs take precedence over quiet
7262fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        NaNs.
7272fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson
7282fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        Return 0 if neither operand is a NaN.
7292fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson
7302fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        """
7312fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if context is None:
7322fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            context = getcontext()
7332fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson
7342fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if self._is_special or other._is_special:
7352fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            if self.is_snan():
7362fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                return context._raise_error(InvalidOperation,
7372fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                                            'comparison involving sNaN',
7382fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                                            self)
7392fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            elif other.is_snan():
7402fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                return context._raise_error(InvalidOperation,
7412fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                                            'comparison involving sNaN',
7422fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                                            other)
7432fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            elif self.is_qnan():
7442fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                return context._raise_error(InvalidOperation,
7452fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                                            'comparison involving NaN',
7462fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                                            self)
7472fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            elif other.is_qnan():
7482fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                return context._raise_error(InvalidOperation,
7492fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                                            'comparison involving NaN',
7502fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson                                            other)
7512fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        return 0
7522fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson
7537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __nonzero__(self):
7541a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is nonzero; otherwise return False.
7557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7561a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        NaNs and infinities are considered nonzero.
7577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
75872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return self._is_special or self._int != '0'
7597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7602fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    def _cmp(self, other):
7612fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        """Compare the two non-NaN decimal instances self and other.
7627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7632fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        Returns -1 if self < other, 0 if self == other and 1
7642fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if self > other.  This routine is for internal use only."""
765636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
7662fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if self._is_special or other._is_special:
767636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return cmp(self._isinfinity(), other._isinfinity())
7687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
769353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # check for zeros;  note that cmp(0, -0) should return 0
770353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
771353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if not other:
772353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return 0
773353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
774353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return -((-1)**other._sign)
775353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other:
776353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return (-1)**self._sign
7777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
77859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # If different signs, neg one is less
7797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if other._sign < self._sign:
7807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return -1
7817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign < other._sign:
7827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return 1
7837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
784636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        self_adjusted = self.adjusted()
785636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other_adjusted = other.adjusted()
786353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_adjusted == other_adjusted:
78772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self_padded = self._int + '0'*(self._exp - other._exp)
78872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            other_padded = other._int + '0'*(other._exp - self._exp)
789353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return cmp(self_padded, other_padded) * (-1)**self._sign
790353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif self_adjusted > other_adjusted:
7917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return (-1)**self._sign
792353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else: # self_adjusted < other_adjusted
7937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return -((-1)**self._sign)
7947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
7952fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    # Note: The Decimal standard doesn't cover rich comparisons for
7962fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    # Decimals.  In particular, the specification is silent on the
7972fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    # subject of what should happen for a comparison involving a NaN.
7982fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    # We take the following approach:
7992fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    #
8002fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    #   == comparisons involving a NaN always return False
8012fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    #   != comparisons involving a NaN always return True
8022fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    #   <, >, <= and >= comparisons involving a (quiet or signaling)
8032fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    #      NaN signal InvalidOperation, and return False if the
8043a94ee05f77d0200cfb7988d02f3fdf292932a94Mark Dickinson    #      InvalidOperation is not trapped.
8052fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    #
8062fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    # This behavior is designed to conform as closely as possible to
8072fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    # that specified by IEEE 754.
8082fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson
8090aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger    def __eq__(self, other):
8102fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        other = _convert_other(other)
8112fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if other is NotImplemented:
8122fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return other
8132fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if self.is_nan() or other.is_nan():
8142fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return False
8152fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        return self._cmp(other) == 0
8160aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger
8170aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger    def __ne__(self, other):
8182fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        other = _convert_other(other)
8192fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if other is NotImplemented:
8202fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return other
8212fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if self.is_nan() or other.is_nan():
8222fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return True
8232fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        return self._cmp(other) != 0
8242fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson
8252fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    def __lt__(self, other, context=None):
8262fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        other = _convert_other(other)
8272fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if other is NotImplemented:
8282fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return other
8292fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        ans = self._compare_check_nans(other, context)
8302fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if ans:
8312fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return False
8322fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        return self._cmp(other) < 0
8332fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson
8342fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    def __le__(self, other, context=None):
8352fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        other = _convert_other(other)
8362fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if other is NotImplemented:
8372fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return other
8382fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        ans = self._compare_check_nans(other, context)
8392fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if ans:
8402fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return False
8412fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        return self._cmp(other) <= 0
8422fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson
8432fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    def __gt__(self, other, context=None):
8442fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        other = _convert_other(other)
8452fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if other is NotImplemented:
8462fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return other
8472fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        ans = self._compare_check_nans(other, context)
8482fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if ans:
8492fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return False
8502fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        return self._cmp(other) > 0
8512fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson
8522fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson    def __ge__(self, other, context=None):
8532fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        other = _convert_other(other)
8542fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if other is NotImplemented:
8552fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return other
8562fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        ans = self._compare_check_nans(other, context)
8572fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if ans:
8582fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return False
8592fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        return self._cmp(other) >= 0
8600aeac107cadd1472e5ea109f7f29e6a6527ae1ecRaymond Hettinger
8617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def compare(self, other, context=None):
8627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Compares one to another.
8637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        -1 => a < b
8657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        0  => a = b
8667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        1  => a > b
8677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        NaN => one is NaN
8687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Like __cmp__, but returns Decimal instances.
8697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
870353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
8717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
87259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # Compare(NaN, NaN) = NaN
873636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if (self._is_special or other and other._is_special):
874636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
875636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
876636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
8777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8782fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        return Decimal(self._cmp(other))
8797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
8807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __hash__(self):
8817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """x.__hash__() <==> hash(x)"""
8827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Decimal integers must hash the same as the ints
88352b25795c02442fc40f8932d05e5d728266339a4Facundo Batista        #
88452b25795c02442fc40f8932d05e5d728266339a4Facundo Batista        # The hash of a nonspecial noninteger Decimal must depend only
88552b25795c02442fc40f8932d05e5d728266339a4Facundo Batista        # on the value of that Decimal, and not on its representation.
886abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
887bea3f6f5c788eb4f0f7639913ff89654152864c0Raymond Hettinger        if self._is_special:
888bea3f6f5c788eb4f0f7639913ff89654152864c0Raymond Hettinger            if self._isnan():
889bea3f6f5c788eb4f0f7639913ff89654152864c0Raymond Hettinger                raise TypeError('Cannot hash a NaN value.')
890bea3f6f5c788eb4f0f7639913ff89654152864c0Raymond Hettinger            return hash(str(self))
8918c202440699cef19602acc24822366d0d7c32083Facundo Batista        if not self:
8928c202440699cef19602acc24822366d0d7c32083Facundo Batista            return 0
8938c202440699cef19602acc24822366d0d7c32083Facundo Batista        if self._isinteger():
8948c202440699cef19602acc24822366d0d7c32083Facundo Batista            op = _WorkRep(self.to_integral_value())
8958c202440699cef19602acc24822366d0d7c32083Facundo Batista            # to make computation feasible for Decimals with large
8968c202440699cef19602acc24822366d0d7c32083Facundo Batista            # exponent, we use the fact that hash(n) == hash(m) for
8978c202440699cef19602acc24822366d0d7c32083Facundo Batista            # any two nonzero integers n and m such that (i) n and m
8988c202440699cef19602acc24822366d0d7c32083Facundo Batista            # have the same sign, and (ii) n is congruent to m modulo
8998c202440699cef19602acc24822366d0d7c32083Facundo Batista            # 2**64-1.  So we can replace hash((-1)**s*c*10**e) with
9008c202440699cef19602acc24822366d0d7c32083Facundo Batista            # hash((-1)**s*c*pow(10, e, 2**64-1).
9018c202440699cef19602acc24822366d0d7c32083Facundo Batista            return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
90252b25795c02442fc40f8932d05e5d728266339a4Facundo Batista        # The value of a nonzero nonspecial Decimal instance is
90352b25795c02442fc40f8932d05e5d728266339a4Facundo Batista        # faithfully represented by the triple consisting of its sign,
90452b25795c02442fc40f8932d05e5d728266339a4Facundo Batista        # its adjusted exponent, and its coefficient with trailing
90552b25795c02442fc40f8932d05e5d728266339a4Facundo Batista        # zeros removed.
90652b25795c02442fc40f8932d05e5d728266339a4Facundo Batista        return hash((self._sign,
90752b25795c02442fc40f8932d05e5d728266339a4Facundo Batista                     self._exp+len(self._int),
90852b25795c02442fc40f8932d05e5d728266339a4Facundo Batista                     self._int.rstrip('0')))
9097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def as_tuple(self):
9117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Represents the number as a triple tuple.
9127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        To show the internals exactly as they are.
9147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
915097a1903035f9ee2efb1953306123f183124125dRaymond Hettinger        return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
9167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __repr__(self):
9187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Represents the number as an instance of Decimal."""
9197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Invariant:  eval(repr(d)) == d
920abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        return "Decimal('%s')" % str(self)
9217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
922353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def __str__(self, eng=False, context=None):
9237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return string representation of the number in scientific notation.
9247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Captures all of the information in the underlying representation.
9267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
9277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
92862edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        sign = ['', '-'][self._sign]
929e5a0a9609faea9afdc6f81f1f6dfa07b1437e3aeRaymond Hettinger        if self._is_special:
93062edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            if self._exp == 'F':
93162edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista                return sign + 'Infinity'
93262edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            elif self._exp == 'n':
93362edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista                return sign + 'NaN' + self._int
93462edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            else: # self._exp == 'N'
93562edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista                return sign + 'sNaN' + self._int
93662edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista
93762edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        # number of digits of self._int to left of decimal point
93862edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        leftdigits = self._exp + len(self._int)
93962edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista
94062edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        # dotplace is number of digits of self._int to the left of the
94162edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        # decimal point in the mantissa of the output string (that is,
94262edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        # after adjusting the exponent)
94362edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        if self._exp <= 0 and leftdigits > -6:
94462edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            # no exponent required
94562edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            dotplace = leftdigits
94662edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        elif not eng:
94762edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            # usual scientific notation: 1 digit on left of the point
9487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            dotplace = 1
94962edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        elif self._int == '0':
95062edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            # engineering notation, zero
95162edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            dotplace = (leftdigits + 1) % 3 - 1
9527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
95362edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            # engineering notation, nonzero
95462edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            dotplace = (leftdigits - 1) % 3 + 1
95562edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista
95662edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        if dotplace <= 0:
95762edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            intpart = '0'
95862edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            fracpart = '.' + '0'*(-dotplace) + self._int
95962edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        elif dotplace >= len(self._int):
96062edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            intpart = self._int+'0'*(dotplace-len(self._int))
96162edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            fracpart = ''
96262edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        else:
96362edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            intpart = self._int[:dotplace]
96462edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            fracpart = '.' + self._int[dotplace:]
96562edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        if leftdigits == dotplace:
96662edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            exp = ''
96762edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        else:
96862edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            if context is None:
96962edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista                context = getcontext()
97062edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista            exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
97162edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista
97262edb71556d26f924a0e2e949af9cd3c211dea23Facundo Batista        return sign + intpart + fracpart + exp
9737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def to_eng_string(self, context=None):
9757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Convert to engineering-type string.
9767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Engineering notation has an exponent which is a multiple of 3, so there
9787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        are up to 3 digits left of the decimal place.
9797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Same rules for when in exponential and when as a value as in __str__.
9817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
982353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self.__str__(eng=True, context=context)
9837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __neg__(self, context=None):
9857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns a copy with the sign switched.
9867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Rounds, if it has reason.
9887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
989636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
990636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
991636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
992636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
9937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
9947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
9957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            # -Decimal('0') is Decimal('0'), not Decimal('-0')
9960f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista            ans = self.copy_abs()
9977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
998353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.copy_negate()
999636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1000636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
1001636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
1002e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        return ans._fix(context)
10037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __pos__(self, context=None):
10057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns a copy, unless it is a sNaN.
10067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Rounds the number (if more then precision digits)
10087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1009636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
1010636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
1011636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
1012636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
10137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
10157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            # + (-0) = 0
10160f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista            ans = self.copy_abs()
1017353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
1018353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal(self)
10197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1020636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
1021636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
1022e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        return ans._fix(context)
10237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1024e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista    def __abs__(self, round=True, context=None):
10257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the absolute value of self.
10267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1027e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        If the keyword argument 'round' is false, do not round.  The
1028e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        expression self.__abs__(round=False) is equivalent to
1029e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        self.copy_abs().
10307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1031e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        if not round:
1032e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            return self.copy_abs()
1033e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista
1034636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
1035636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
1036636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
1037636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
10387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign:
10407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = self.__neg__(context=context)
10417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
10427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = self.__pos__(context=context)
10437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
10457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __add__(self, other, context=None):
10477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns self + other.
10487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        -INF + INF (or the reverse) cause InvalidOperation errors.
10507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1051636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1052267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1053267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
1054636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
10557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
10567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
10577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1058636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
1059636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
1060636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
1061636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
10627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1063636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity():
106459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                # If both INF, same sign => same as both, opposite => error.
1065636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if self._sign != other._sign and other._isinfinity():
1066636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    return context._raise_error(InvalidOperation, '-INF + INF')
1067636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Decimal(self)
1068636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if other._isinfinity():
106959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                return Decimal(other)  # Can't both be infinity here
10707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exp = min(self._exp, other._exp)
10727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        negativezero = 0
10737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context.rounding == ROUND_FLOOR and self._sign != other._sign:
107459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If the answer is 0, the sign should be negative, in this case.
10757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            negativezero = 1
10767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self and not other:
10787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            sign = min(self._sign, other._sign)
10797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if negativezero:
10807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                sign = 1
108172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(sign, '0', exp)
1082e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            ans = ans._fix(context)
1083353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
10847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
108599b5548298ffc2ae5f03bd9ef873ce45a9844f0eFacundo Batista            exp = max(exp, other._exp - context.prec-1)
1086353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = other._rescale(exp, context.rounding)
1087e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            ans = ans._fix(context)
10887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
10897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not other:
109099b5548298ffc2ae5f03bd9ef873ce45a9844f0eFacundo Batista            exp = max(exp, self._exp - context.prec-1)
1091353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._rescale(exp, context.rounding)
1092e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            ans = ans._fix(context)
10937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
10947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        op1 = _WorkRep(self)
10967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        op2 = _WorkRep(other)
1097e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        op1, op2 = _normalize(op1, op2, context.prec)
10987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
10997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        result = _WorkRep()
11007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if op1.sign != op2.sign:
11017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            # Equal and opposite
110217931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            if op1.int == op2.int:
110372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(negativezero, '0', exp)
1104e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista                ans = ans._fix(context)
1105353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return ans
110617931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            if op1.int < op2.int:
11077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                op1, op2 = op2, op1
110859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                # OK, now abs(op1) > abs(op2)
110917931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            if op1.sign == 1:
111017931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger                result.sign = 1
11117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                op1.sign, op2.sign = op2.sign, op1.sign
11127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            else:
111317931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger                result.sign = 0
111459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                # So we know the sign, and op1 > 0.
111517931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        elif op1.sign == 1:
11167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            result.sign = 1
111717931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            op1.sign, op2.sign = (0, 0)
111817931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        else:
111917931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            result.sign = 0
112059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # Now, op1 > abs(op2) > 0
11217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
112217931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        if op2.sign == 0:
1123636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            result.int = op1.int + op2.int
11247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
1125636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            result.int = op1.int - op2.int
11267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        result.exp = op1.exp
11287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        ans = Decimal(result)
1129e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        ans = ans._fix(context)
11307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
11317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __radd__ = __add__
11337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __sub__(self, other, context=None):
1135353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return self - other"""
1136636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1137267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1138267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
11397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1140636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
1141636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context=context)
1142636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
1143636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
11447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1145353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self - other is computed as self + other.copy_negate()
1146353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self.__add__(other.copy_negate(), context=context)
11477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rsub__(self, other, context=None):
1149353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return other - self"""
1150636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1151267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1152267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
11537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1154353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return other.__sub__(self, context=context)
11557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __mul__(self, other, context=None):
11577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return self * other.
11587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        (+-) INF * 0 (or its reverse) raise InvalidOperation.
11607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1161636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1162267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1163267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
1164636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
11657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
11667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
11677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1168d87ac8f24da5dce860b559b69e6af59edd2c3eecRaymond Hettinger        resultsign = self._sign ^ other._sign
11697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1170636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
1171636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
1172636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
1173636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
1174636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1175636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity():
1176636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if not other:
1177636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    return context._raise_error(InvalidOperation, '(+-)INF * 0')
1178636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Infsign[resultsign]
1179636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1180636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if other._isinfinity():
1181636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if not self:
1182636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                    return context._raise_error(InvalidOperation, '0 * (+-)INF')
1183636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Infsign[resultsign]
11847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        resultexp = self._exp + other._exp
11867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Special case for multiplying by zero
11887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self or not other:
118972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(resultsign, '0', resultexp)
1190e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            # Fixing in case the exponent is out of bounds
1191e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            ans = ans._fix(context)
11927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
11937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
11947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Special case for multiplying by power of 10
119572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        if self._int == '1':
119672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(resultsign, other._int, resultexp)
1197e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            ans = ans._fix(context)
11987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
119972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        if other._int == '1':
120072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(resultsign, self._int, resultexp)
1201e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista            ans = ans._fix(context)
12027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
12037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1204636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        op1 = _WorkRep(self)
1205636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        op2 = _WorkRep(other)
1206636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
120772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
1208e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        ans = ans._fix(context)
12097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
12117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __rmul__ = __mul__
12127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __div__(self, other, context=None):
12147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return self / other."""
1215636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1216267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1217cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return NotImplemented
1218636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
12197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if context is None:
12207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context = getcontext()
12217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1222636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        sign = self._sign ^ other._sign
1223636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1224636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
1225636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(other, context)
1226636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
12277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return ans
12287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1229636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity() and other._isinfinity():
12307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
12317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
12327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if self._isinfinity():
1233636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Infsign[sign]
1234636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1235636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if other._isinfinity():
1236636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                context._raise_error(Clamped, 'Division by infinity')
123772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(sign, '0', context.Etiny())
1238636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1239636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        # Special cases for zeroes
1240636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if not other:
1241cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if not self:
1242cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(DivisionUndefined, '0 / 0')
1243636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            return context._raise_error(DivisionByZero, 'x / 0', sign)
12447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1245cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if not self:
1246cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            exp = self._exp - other._exp
1247cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            coeff = 0
1248cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        else:
1249cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            # OK, so neither = 0, INF or NaN
1250cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            shift = len(other._int) - len(self._int) + context.prec + 1
1251cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            exp = self._exp - other._exp - shift
1252cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            op1 = _WorkRep(self)
1253cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            op2 = _WorkRep(other)
1254cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if shift >= 0:
1255cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1256cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1257cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1258cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if remainder:
1259cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                # result is not exact; adjust to ensure correct rounding
1260cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                if coeff % 5 == 0:
1261cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                    coeff += 1
1262cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1263cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                # result is exact; get as close to ideal exponent as possible
1264cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                ideal_exp = self._exp - other._exp
1265cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                while exp < ideal_exp and coeff % 10 == 0:
1266cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                    coeff //= 10
1267cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                    exp += 1
12687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
126972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        ans = _dec_from_triple(sign, str(coeff), exp)
1270cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return ans._fix(context)
12717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1272cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista    __truediv__ = __div__
12737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1274cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista    def _divide(self, other, context):
1275cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        """Return (self // other, self % other), to context.prec precision.
12767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1277cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        Assumes that neither self nor other is a NaN, that self is not
1278cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        infinite and that other is nonzero.
1279cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        """
1280cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        sign = self._sign ^ other._sign
1281cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if other._isinfinity():
1282cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            ideal_exp = self._exp
1283cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        else:
1284cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            ideal_exp = min(self._exp, other._exp)
12857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1286cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        expdiff = self.adjusted() - other.adjusted()
1287cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if not self or other._isinfinity() or expdiff <= -2:
128872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return (_dec_from_triple(sign, '0', 0),
1289cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                    self._rescale(ideal_exp, context.rounding))
1290cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if expdiff <= context.prec:
1291cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            op1 = _WorkRep(self)
1292cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            op2 = _WorkRep(other)
1293cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if op1.exp >= op2.exp:
1294cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                op1.int *= 10**(op1.exp - op2.exp)
1295cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1296cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                op2.int *= 10**(op2.exp - op1.exp)
1297cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            q, r = divmod(op1.int, op2.int)
1298cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if q < 10**context.prec:
129972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return (_dec_from_triple(sign, str(q), 0),
130072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                        _dec_from_triple(self._sign, str(r), ideal_exp))
13017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1302cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        # Here the quotient is too large to be representable
1303cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        ans = context._raise_error(DivisionImpossible,
1304cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                                   'quotient too large in //, % or divmod')
1305cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return ans, ans
13067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rdiv__(self, other, context=None):
13087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Swaps self/other and returns __div__."""
1309636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1310267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1311267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
13127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return other.__div__(self, context=context)
13137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __rtruediv__ = __rdiv__
13147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __divmod__(self, other, context=None):
13167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1317cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        Return (self // other, self % other)
13187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1319cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        other = _convert_other(other)
1320cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if other is NotImplemented:
1321cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return other
1322cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1323cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if context is None:
1324cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            context = getcontext()
1325cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1326cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        ans = self._check_nans(other, context)
1327cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if ans:
1328cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return (ans, ans)
1329cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1330cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        sign = self._sign ^ other._sign
1331cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if self._isinfinity():
1332cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if other._isinfinity():
1333cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1334cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return ans, ans
1335cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1336cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return (Infsign[sign],
1337cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                        context._raise_error(InvalidOperation, 'INF % x'))
1338cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1339cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if not other:
1340cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if not self:
1341cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1342cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return ans, ans
1343cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1344cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return (context._raise_error(DivisionByZero, 'x // 0', sign),
1345cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                        context._raise_error(InvalidOperation, 'x % 0'))
1346cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1347cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        quotient, remainder = self._divide(other, context)
1348e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        remainder = remainder._fix(context)
1349cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return quotient, remainder
13507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rdivmod__(self, other, context=None):
13527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Swaps self/other and returns __divmod__."""
1353636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1354267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1355267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
13567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return other.__divmod__(self, context=context)
13577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __mod__(self, other, context=None):
13597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
13607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self % other
13617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1362636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1363267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1364267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
13657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1366cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if context is None:
1367cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            context = getcontext()
13687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1369cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        ans = self._check_nans(other, context)
1370cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if ans:
1371cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return ans
13727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1373cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if self._isinfinity():
1374cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return context._raise_error(InvalidOperation, 'INF % x')
1375cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        elif not other:
1376cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if self:
1377cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(InvalidOperation, 'x % 0')
1378cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1379cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(DivisionUndefined, '0 % 0')
1380cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1381cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        remainder = self._divide(other, context)[1]
1382e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        remainder = remainder._fix(context)
1383cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return remainder
13847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rmod__(self, other, context=None):
13867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Swaps self/other and returns __mod__."""
1387636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1388267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1389267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
13907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return other.__mod__(self, context=context)
13917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
13927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def remainder_near(self, other, context=None):
13937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
13947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Remainder nearest to 0-  abs(remainder-near) <= other/2
13957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1396636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
1397636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
13987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1399353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
14007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1401353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
1402353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
1403353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
14047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1405353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self == +/-infinity -> InvalidOperation
1406353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
1407353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1408353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'remainder_near(infinity, x)')
14097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1410353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # other == 0 -> either InvalidOperation or DivisionUndefined
1411353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other:
1412353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self:
1413353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation,
1414353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                            'remainder_near(x, 0)')
1415353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1416353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(DivisionUndefined,
1417353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                            'remainder_near(0, 0)')
14187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1419353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # other = +/-infinity -> remainder = self
1420353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._isinfinity():
1421353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal(self)
1422353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
14237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1424353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self = 0 -> remainder = self, with ideal exponent
1425353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ideal_exponent = min(self._exp, other._exp)
1426353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
142772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(self._sign, '0', ideal_exponent)
1428353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
14297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1430353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # catch most cases of large or small quotient
1431353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        expdiff = self.adjusted() - other.adjusted()
1432353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if expdiff >= context.prec + 1:
1433353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # expdiff >= prec+1 => abs(self/other) > 10**prec
1434cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return context._raise_error(DivisionImpossible)
1435353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if expdiff <= -2:
1436353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # expdiff <= -2 => abs(self/other) < 0.1
1437353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._rescale(ideal_exponent, context.rounding)
1438353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
14397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1440353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # adjust both arguments to have the same exponent, then divide
1441353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op1 = _WorkRep(self)
1442353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op2 = _WorkRep(other)
1443353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if op1.exp >= op2.exp:
1444353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            op1.int *= 10**(op1.exp - op2.exp)
14457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
1446353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            op2.int *= 10**(op2.exp - op1.exp)
1447353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        q, r = divmod(op1.int, op2.int)
1448353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # remainder is r*10**ideal_exponent; other is +/-op2.int *
1449353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 10**ideal_exponent.   Apply correction to ensure that
1450353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # abs(remainder) <= abs(other)/2
1451353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if 2*r + (q&1) > op2.int:
1452353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            r -= op2.int
1453353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            q += 1
1454353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1455353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if q >= 10**context.prec:
1456cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return context._raise_error(DivisionImpossible)
1457353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1458353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # result has same sign as self unless r is negative
1459353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        sign = self._sign
1460353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if r < 0:
1461353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sign = 1-sign
1462353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            r = -r
14637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
146472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        ans = _dec_from_triple(sign, str(r), ideal_exponent)
1465353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans._fix(context)
14667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __floordiv__(self, other, context=None):
14687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """self // other"""
1469cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        other = _convert_other(other)
1470cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if other is NotImplemented:
1471cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return other
1472cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1473cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if context is None:
1474cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            context = getcontext()
1475cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1476cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        ans = self._check_nans(other, context)
1477cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if ans:
1478cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return ans
1479cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1480cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if self._isinfinity():
1481cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if other._isinfinity():
1482cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(InvalidOperation, 'INF // INF')
1483cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1484cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return Infsign[self._sign ^ other._sign]
1485cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1486cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        if not other:
1487cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            if self:
1488cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(DivisionByZero, 'x // 0',
1489cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                                            self._sign ^ other._sign)
1490cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            else:
1491cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista                return context._raise_error(DivisionUndefined, '0 // 0')
1492cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista
1493cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista        return self._divide(other, context)[0]
14947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
14957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __rfloordiv__(self, other, context=None):
14967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Swaps self/other and returns __floordiv__."""
1497636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
1498267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
1499267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
15007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return other.__floordiv__(self, context=context)
15017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
15027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __float__(self):
15037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Float representation."""
15047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return float(str(self))
15057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
15067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __int__(self):
150746b0802ccd9a9c47b27a285526fbb2a8bee5b8cbBrett Cannon        """Converts self to an int, truncating if necessary."""
1508636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
1509636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isnan():
1510636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                context = getcontext()
1511636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return context._raise_error(InvalidContext)
1512636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            elif self._isinfinity():
151359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                raise OverflowError("Cannot convert infinity to long")
1514353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        s = (-1)**self._sign
15157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._exp >= 0:
151672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return s*int(self._int)*10**self._exp
1517605ed0248375bbf87bbd1d80afc7c6918fd3ce2bRaymond Hettinger        else:
151872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return s*int(self._int[:self._exp] or '0')
15197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
15205a05364049a7b0c3eeee94fb7b77e6b41036b3aeRaymond Hettinger    __trunc__ = __int__
15215a05364049a7b0c3eeee94fb7b77e6b41036b3aeRaymond Hettinger
1522116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger    @property
1523116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger    def real(self):
1524116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger        return self
1525116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger
1526116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger    @property
1527116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger    def imag(self):
1528116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger        return Decimal(0)
1529116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger
1530116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger    def conjugate(self):
1531116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger        return self
1532116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger
1533116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger    def __complex__(self):
1534116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger        return complex(float(self))
1535116f72fa5ceb864efcc47da2f8c437fd29c7e8b3Raymond Hettinger
15367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __long__(self):
15377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Converts to a long.
15387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
15397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Equivalent to long(int(self))
15407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
15417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return long(self.__int__())
15427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1543353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _fix_nan(self, context):
1544353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Decapitate the payload of a NaN to fit the context"""
1545353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        payload = self._int
1546353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1547353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # maximum length of payload is precision if _clamp=0,
1548353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # precision-1 if _clamp=1.
1549353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        max_payload_len = context.prec - context._clamp
1550353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if len(payload) > max_payload_len:
155172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            payload = payload[len(payload)-max_payload_len:].lstrip('0')
155272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(self._sign, payload, self._exp, True)
15536c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        return Decimal(self)
1554353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1555dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger    def _fix(self, context):
15567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Round if it is necessary to keep self within prec precision.
15577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
15587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Rounds and fixes the exponent.  Does not raise on a sNaN.
15597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
15607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Arguments:
15617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self - Decimal instance
15627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        context - context used.
15637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1564636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
1565353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
1566353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self._isnan():
1567353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # decapitate payload if necessary
1568353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self._fix_nan(context)
1569353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1570353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # self is +/-Infinity; return unaltered
15716c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                return Decimal(self)
15727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1573353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if self is zero then exponent should be between Etiny and
1574353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1575353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Etiny = context.Etiny()
1576353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Etop = context.Etop()
15777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
1578353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            exp_max = [context.Emax, Etop][context._clamp]
1579353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            new_exp = min(max(self._exp, Etiny), exp_max)
1580353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if new_exp != self._exp:
1581353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Clamped)
158272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(self._sign, '0', new_exp)
15837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            else:
15846c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                return Decimal(self)
15857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1586353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp_min is the smallest allowable exponent of the result,
1587353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # equal to max(self.adjusted()-context.prec+1, Etiny)
1588353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exp_min = len(self._int) + self._exp - context.prec
1589353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if exp_min > Etop:
1590353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # overflow: exp_min > Etop iff self.adjusted() > Emax
1591353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
1592353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Rounded)
1593353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(Overflow, 'above Emax', self._sign)
1594353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_is_subnormal = exp_min < Etiny
1595353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_is_subnormal:
1596353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Subnormal)
1597353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            exp_min = Etiny
15987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1599353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # round if self has too many digits
1600353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp < exp_min:
16017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            context._raise_error(Rounded)
16022ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            digits = len(self._int) + self._exp - exp_min
16032ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            if digits < 0:
16042ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista                self = _dec_from_triple(self._sign, '1', exp_min-1)
16052ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista                digits = 0
16062ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            this_function = getattr(self, self._pick_rounding_function[context.rounding])
16072ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            changed = this_function(digits)
16082ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            coeff = self._int[:digits] or '0'
16092ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            if changed == 1:
16102ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista                coeff = str(int(coeff)+1)
16112ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            ans = _dec_from_triple(self._sign, coeff, exp_min)
16122ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista
16132ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            if changed:
1614353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Inexact)
1615353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_is_subnormal:
1616353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    context._raise_error(Underflow)
1617353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if not ans:
1618353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        # raise Clamped on underflow to 0
1619353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        context._raise_error(Clamped)
1620353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                elif len(ans._int) == context.prec+1:
1621353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    # we get here only if rescaling rounds the
1622353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    # cofficient up to exactly 10**context.prec
1623353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if ans._exp < Etop:
162472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                        ans = _dec_from_triple(ans._sign,
162572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                                   ans._int[:-1], ans._exp+1)
1626353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    else:
1627353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        # Inexact and Rounded have already been raised
1628353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        ans = context._raise_error(Overflow, 'above Emax',
1629353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                                   self._sign)
16307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return ans
16317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1632353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # fold down if _clamp == 1 and self has too few digits
1633353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context._clamp == 1 and self._exp > Etop:
1634353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Clamped)
163572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self_padded = self._int + '0'*(self._exp - Etop)
163672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(self._sign, self_padded, Etop)
16377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1638353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # here self was representable to begin with; return unchanged
16396c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        return Decimal(self)
16407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
16417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    _pick_rounding_function = {}
16427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1643353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # for each of the rounding functions below:
1644353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #   self is a finite, nonzero Decimal
1645353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #   prec is an integer satisfying 0 <= prec < len(self._int)
16462ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    #
16472ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    # each function returns either -1, 0, or 1, as follows:
16482ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    #   1 indicates that self should be rounded up (away from zero)
16492ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    #   0 indicates that self should be truncated, and that all the
16502ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    #     digits to be truncated are zeros (so the value is unchanged)
16512ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista    #  -1 indicates that there are nonzero digits to be truncated
16527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1653353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_down(self, prec):
1654353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Also known as round-towards-0, truncate."""
16552ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        if _all_zeros(self._int, prec):
16562ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return 0
16572ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        else:
16582ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -1
16597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1660353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_up(self, prec):
1661353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds away from 0."""
16622ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        return -self._round_down(prec)
16637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1664353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_half_up(self, prec):
1665353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds 5 up (away from 0)"""
166672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        if self._int[prec] in '56789':
16672ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return 1
16682ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        elif _all_zeros(self._int, prec):
16692ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return 0
1670353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
16712ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -1
16727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1673353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_half_down(self, prec):
16747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Round 5 down"""
16752ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        if _exact_half(self._int, prec):
16762ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -1
16772ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        else:
16782ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return self._round_half_up(prec)
16797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1680353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_half_even(self, prec):
1681353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Round 5 to even, rest to nearest."""
16822ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        if _exact_half(self._int, prec) and \
16832ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista                (prec == 0 or self._int[prec-1] in '02468'):
16842ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -1
1685353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
16862ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return self._round_half_up(prec)
16877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1688353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_ceiling(self, prec):
16897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Rounds up (not away from 0 if negative.)"""
16907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign:
1691353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_down(prec)
16927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
16932ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -self._round_down(prec)
16947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1695353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_floor(self, prec):
16967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Rounds down (not towards 0 if negative)"""
16977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self._sign:
1698353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_down(prec)
16997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
17002ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -self._round_down(prec)
17017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1702353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _round_05up(self, prec):
1703353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Round down unless digit prec-1 is 0 or 5."""
17042ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        if prec and self._int[prec-1] not in '05':
1705353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._round_down(prec)
17062ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        else:
17072ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            return -self._round_down(prec)
1708353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1709353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def fma(self, other, third, context=None):
1710353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Fused multiply-add.
17117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1712353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Returns self*other+third with no rounding of the intermediate
1713353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        product self*other.
1714353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1715353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self and other are multiplied together, with no rounding of
1716353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        the result.  The third operand is then added to the result,
1717353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        and a single final rounding is performed.
17187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
1719353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1720353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
17217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
172258f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista        # compute product; raise InvalidOperation if either operand is
172358f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista        # a signaling NaN or if the product is zero times infinity.
172458f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista        if self._is_special or other._is_special:
172558f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            if context is None:
172658f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                context = getcontext()
172758f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            if self._exp == 'N':
17280f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista                return context._raise_error(InvalidOperation, 'sNaN', self)
172958f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            if other._exp == 'N':
17300f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista                return context._raise_error(InvalidOperation, 'sNaN', other)
173158f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            if self._exp == 'n':
173258f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                product = self
173358f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            elif other._exp == 'n':
173458f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                product = other
173558f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            elif self._exp == 'F':
173658f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                if not other:
173758f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                    return context._raise_error(InvalidOperation,
173858f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                                                'INF * 0 in fma')
173958f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                product = Infsign[self._sign ^ other._sign]
174058f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            elif other._exp == 'F':
174158f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                if not self:
174258f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                    return context._raise_error(InvalidOperation,
174358f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                                                '0 * INF in fma')
174458f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                product = Infsign[self._sign ^ other._sign]
174558f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista        else:
174658f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista            product = _dec_from_triple(self._sign ^ other._sign,
174758f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                                       str(int(self._int) * int(other._int)),
174858f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista                                       self._exp + other._exp)
17497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
175058f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista        third = _convert_other(third, raiseit=True)
175158f6f2e0c9fad1ef9ee921980888dc52da8100ceFacundo Batista        return product.__add__(third, context)
17527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1753353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _power_modulo(self, other, modulo, context=None):
1754353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Three argument version of __pow__"""
17557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1756353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if can't convert other and modulo to Decimal, raise
1757353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # TypeError; there's no point returning NotImplemented (no
1758353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # equivalent of __rpow__ for three argument pow)
1759353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
1760353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        modulo = _convert_other(modulo, raiseit=True)
17617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1762353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
1763353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
17647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1765353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # deal with NaNs: if there are any sNaNs then first one wins,
1766353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (i.e. behaviour for NaNs is identical to that of fma)
1767353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_is_nan = self._isnan()
1768353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other_is_nan = other._isnan()
1769353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        modulo_is_nan = modulo._isnan()
1770353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_is_nan or other_is_nan or modulo_is_nan:
1771353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self_is_nan == 2:
1772353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation, 'sNaN',
17730f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista                                        self)
1774353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other_is_nan == 2:
1775353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation, 'sNaN',
17760f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista                                        other)
1777353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if modulo_is_nan == 2:
1778353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation, 'sNaN',
17790f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista                                        modulo)
1780353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self_is_nan:
17816c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                return self._fix_nan(context)
1782353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other_is_nan:
17836c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                return other._fix_nan(context)
17846c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return modulo._fix_nan(context)
1785353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1786353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # check inputs: we apply same restrictions as Python's pow()
1787353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (self._isinteger() and
1788353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                other._isinteger() and
1789353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                modulo._isinteger()):
1790353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1791353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'pow() 3rd argument not allowed '
1792353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'unless all arguments are integers')
1793353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other < 0:
1794353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1795353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'pow() 2nd argument cannot be '
1796353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'negative when 3rd argument specified')
1797353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not modulo:
1798353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1799353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'pow() 3rd argument cannot be 0')
1800353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1801353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # additional restriction for decimal: the modulus must be less
1802353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # than 10**prec in absolute value
1803353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if modulo.adjusted() >= context.prec:
1804353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1805353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'insufficient precision: pow() 3rd '
1806353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'argument must not have more than '
1807353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'precision digits')
1808353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1809353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # define 0**0 == NaN, for consistency with two-argument pow
1810353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (even though it hurts!)
1811353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other and not self:
1812353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
1813353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'at least one of pow() 1st argument '
1814353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'and 2nd argument must be nonzero ;'
1815353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        '0**0 is not defined')
1816353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1817353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute sign of result
1818353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._iseven():
1819353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sign = 0
1820353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
1821353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sign = self._sign
1822353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1823353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # convert modulo to a Python integer, and self and other to
1824353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Decimal integers (i.e. force their exponents to be >= 0)
1825353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        modulo = abs(int(modulo))
1826353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        base = _WorkRep(self.to_integral_value())
1827353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exponent = _WorkRep(other.to_integral_value())
1828353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1829353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute result using integer pow()
1830353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1831353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        for i in xrange(exponent.exp):
1832353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            base = pow(base, 10, modulo)
1833353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        base = pow(base, exponent.int, modulo)
1834353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
183572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(sign, str(base), 0)
1836353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1837353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _power_exact(self, other, p):
1838353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Attempt to compute self**other exactly.
1839353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1840353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Given Decimals self and other and an integer p, attempt to
1841353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        compute an exact result for the power self**other, with p
1842353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        digits of precision.  Return None if self**other is not
1843353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exactly representable in p digits.
1844353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1845353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Assumes that elimination of special cases has already been
1846353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        performed: self and other must both be nonspecial; self must
1847353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        be positive and not numerically equal to 1; other must be
1848353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        nonzero.  For efficiency, other._exp should not be too large,
1849353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        so that 10**abs(other._exp) is a feasible calculation."""
1850353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1851353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # In the comments below, we write x for the value of self and
1852353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # y for the value of other.  Write x = xc*10**xe and y =
1853353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # yc*10**ye.
1854353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1855353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # The main purpose of this method is to identify the *failure*
1856353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # of x**y to be exactly representable with as little effort as
1857353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # possible.  So we look for cheap and easy tests that
1858353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # eliminate the possibility of x**y being exact.  Only if all
1859353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # these tests are passed do we go on to actually compute x**y.
1860353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1861353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Here's the main idea.  First normalize both x and y.  We
1862353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # express y as a rational m/n, with m and n relatively prime
1863353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # and n>0.  Then for x**y to be exactly representable (at
1864353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # *any* precision), xc must be the nth power of a positive
1865353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # integer and xe must be divisible by n.  If m is negative
1866353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # then additionally xc must be a power of either 2 or 5, hence
1867353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # a power of 2**n or 5**n.
1868353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1869353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # There's a limit to how small |y| can be: if y=m/n as above
1870353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # then:
1871353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1872353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #  (1) if xc != 1 then for the result to be representable we
1873353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      need xc**(1/n) >= 2, and hence also xc**|y| >= 2.  So
1874353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1875353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      2**(1/|y|), hence xc**|y| < 2 and the result is not
1876353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      representable.
1877353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1878353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #  (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1.  Hence if
1879353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #      |y| < 1/|xe| then the result is not representable.
1880353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1881353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Note that since x is not equal to 1, at least one of (1) and
1882353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (2) must apply.  Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1883353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1884353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
1885353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # There's also a limit to how large y can be, at least if it's
1886353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # positive: the normalized result will have coefficient xc**y,
1887353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # so if it's representable then xc**y < 10**p, and y <
1888353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # p/log10(xc).  Hence if y*log10(xc) >= p then the result is
1889353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # not exactly representable.
1890353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1891353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1892353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # so |y| < 1/xe and the result is not representable.
1893353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1894353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # < 1/nbits(xc).
1895353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1896353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        x = _WorkRep(self)
1897353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        xc, xe = x.int, x.exp
1898353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while xc % 10 == 0:
1899353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xc //= 10
1900353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xe += 1
1901353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1902353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        y = _WorkRep(other)
1903353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        yc, ye = y.int, y.exp
1904353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while yc % 10 == 0:
1905353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            yc //= 10
1906353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ye += 1
1907353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1908353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # case where xc == 1: result is 10**(xe*y), with xe*y
1909353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # required to be an integer
1910353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if xc == 1:
1911353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ye >= 0:
1912353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exponent = xe*yc*10**ye
1913353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1914353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exponent, remainder = divmod(xe*yc, 10**-ye)
1915353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if remainder:
1916353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1917353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if y.sign == 1:
1918353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exponent = -exponent
1919353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # if other is a nonnegative integer, use ideal exponent
1920353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._isinteger() and other._sign == 0:
1921353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                ideal_exponent = self._exp*int(other)
1922353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                zeros = min(exponent-ideal_exponent, p-1)
1923353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1924353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                zeros = 0
192572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
1926353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1927353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # case where y is negative: xc must be either a power
1928353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # of 2 or a power of 5.
1929353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if y.sign == 1:
1930353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            last_digit = xc % 10
1931353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if last_digit in (2,4,6,8):
1932353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # quick test for power of 2
1933353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if xc & -xc != xc:
1934353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1935353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # now xc is a power of 2; e is its exponent
1936353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                e = _nbits(xc)-1
1937353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # find e*y and xe*y; both must be integers
1938353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if ye >= 0:
1939353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    y_as_int = yc*10**ye
1940353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e = e*y_as_int
1941353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xe = xe*y_as_int
1942353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                else:
1943353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    ten_pow = 10**-ye
1944353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e, remainder = divmod(e*yc, ten_pow)
1945353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if remainder:
1946353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return None
1947353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xe, remainder = divmod(xe*yc, ten_pow)
1948353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if remainder:
1949353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return None
1950353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1951353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if e*65 >= p*93: # 93/65 > log(10)/log(5)
1952353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1953353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                xc = 5**e
1954353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
1955353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            elif last_digit == 5:
1956353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # e >= log_5(xc) if xc is a power of 5; we have
1957353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # equality all the way up to xc=5**2658
1958353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                e = _nbits(xc)*28//65
1959353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                xc, remainder = divmod(5**e, xc)
1960353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if remainder:
1961353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1962353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                while xc % 5 == 0:
1963353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xc //= 5
1964353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e -= 1
1965353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if ye >= 0:
1966353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    y_as_integer = yc*10**ye
1967353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e = e*y_as_integer
1968353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xe = xe*y_as_integer
1969353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                else:
1970353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    ten_pow = 10**-ye
1971353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    e, remainder = divmod(e*yc, ten_pow)
1972353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if remainder:
1973353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return None
1974353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    xe, remainder = divmod(xe*yc, ten_pow)
1975353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if remainder:
1976353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return None
1977353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if e*3 >= p*10: # 10/3 > log(10)/log(2)
1978353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return None
1979353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                xc = 2**e
1980353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
1981353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
19827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1983353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if xc >= 10**p:
1984353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1985353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xe = -e-xe
198672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(0, str(xc), xe)
19877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
1988353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # now y is positive; find m and n such that y = m/n
1989353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ye >= 0:
1990353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            m, n = yc*10**ye, 1
1991353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
1992353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1993353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1994353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xc_bits = _nbits(xc)
1995353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1996353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
1997353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            m, n = yc, 10**(-ye)
1998353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while m % 2 == n % 2 == 0:
1999353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                m //= 2
2000353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n //= 2
2001353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while m % 5 == n % 5 == 0:
2002353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                m //= 5
2003353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n //= 5
2004353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2005353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute nth root of xc*10**xe
2006353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if n > 1:
2007353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # if 1 < xc < 2**n then xc isn't an nth power
2008353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if xc != 1 and xc_bits <= n:
2009353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
2010353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2011353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xe, rem = divmod(xe, n)
2012353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if rem != 0:
2013353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
2014353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2015353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # compute nth root of xc using Newton's method
2016353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            a = 1L << -(-_nbits(xc)//n) # initial estimate
2017353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while True:
2018353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                q, r = divmod(xc, a**(n-1))
2019353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if a <= q:
2020353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
2021353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                else:
2022353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    a = (a*(n-1) + q)//n
2023353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if not (a == q and r == 0):
2024353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return None
2025353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xc = a
2026353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2027353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # now xc*10**xe is the nth root of the original xc*10**xe
2028353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute mth power of xc*10**xe
2029353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2030353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2031353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 10**p and the result is not representable.
2032353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if xc > 1 and m > p*100//_log10_lb(xc):
2033353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return None
2034353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        xc = xc**m
2035353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        xe *= m
2036353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if xc > 10**p:
2037353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return None
2038353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2039353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # by this point the result *is* exactly representable
2040353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # adjust the exponent to get as close as possible to the ideal
2041353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exponent, if necessary
2042353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        str_xc = str(xc)
2043353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._isinteger() and other._sign == 0:
2044353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ideal_exponent = self._exp*int(other)
2045353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            zeros = min(xe-ideal_exponent, p-len(str_xc))
2046353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2047353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            zeros = 0
204872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
2049cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
2050353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def __pow__(self, other, modulo=None, context=None):
2051353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return self ** other [ % modulo].
20527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2053353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        With two arguments, compute self**other.
20547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2055353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        With three arguments, compute (self**other) % modulo.  For the
2056353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        three argument form, the following restrictions on the
2057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        arguments hold:
20587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - all three arguments must be integral
2060353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - other must be nonnegative
2061353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - either self or other (or both) must be nonzero
2062353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - modulo must be nonzero and must have at most p digits,
2063353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista           where p is the context precision.
20647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2065353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        If any of these restrictions is violated the InvalidOperation
2066353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        flag is raised.
2067353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2068353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result of pow(self, other, modulo) is identical to the
2069353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        result that would be obtained by computing (self**other) %
2070353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        modulo with unbounded precision, but is computed more
2071353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        efficiently.  It is always exact.
2072353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2074353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if modulo is not None:
2075353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._power_modulo(other, modulo, context)
20767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2077636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        other = _convert_other(other)
2078267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger        if other is NotImplemented:
2079267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger            return other
20807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2081353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2082353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
20837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2084353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # either argument is a NaN => result is NaN
2085353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
2086353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
2087353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
20887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2089353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2090353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other:
2091353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if not self:
2092353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return context._raise_error(InvalidOperation, '0 ** 0')
2093353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2094353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_p1
20957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2096353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # result has sign 1 iff self._sign is 1 and other is an odd integer
2097353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        result_sign = 0
2098353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign == 1:
2099353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._isinteger():
2100353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if not other._iseven():
2101353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    result_sign = 1
2102353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2103353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # -ve**noninteger = NaN
2104353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # (-0)**noninteger = 0**noninteger
2105353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self:
2106353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return context._raise_error(InvalidOperation,
2107353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        'x ** y with x negative and y not an integer')
2108353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # negate self, without doing any unwanted rounding
210972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self = self.copy_negate()
2110353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2111353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2112353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2113353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._sign == 0:
211472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(result_sign, '0', 0)
2115353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2116353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Infsign[result_sign]
2117353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2118353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
2119353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
2120353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._sign == 0:
2121353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Infsign[result_sign]
2122353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
212372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(result_sign, '0', 0)
2124353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2125353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 1**other = 1, but the choice of exponent and the flags
2126353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # depend on the exponent of self, and on whether other is a
2127353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # positive integer, a negative integer, or neither
2128353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self == Dec_p1:
2129353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if other._isinteger():
2130353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # exp = max(self._exp*max(int(other), 0),
2131353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # 1-context.prec) but evaluating int(other) directly
2132353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # is dangerous until we know other is small (other
2133353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # could be 1e999999999)
2134353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other._sign == 1:
2135353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    multiplier = 0
2136353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                elif other > context.prec:
2137353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    multiplier = context.prec
2138353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                else:
2139353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    multiplier = int(other)
2140353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2141353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exp = self._exp * multiplier
2142353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if exp < 1-context.prec:
2143353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    exp = 1-context.prec
2144353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    context._raise_error(Rounded)
2145353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2146353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Inexact)
2147353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Rounded)
2148353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                exp = 1-context.prec
2149353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
215072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
2151353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2152353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # compute adjusted exponent of self
2153353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_adj = self.adjusted()
2154353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2155353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self ** infinity is infinity if self > 1, 0 if self < 1
2156353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self ** -infinity is infinity if self < 1, 0 if self > 1
2157353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._isinfinity():
2158353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if (other._sign == 0) == (self_adj < 0):
215972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                return _dec_from_triple(result_sign, '0', 0)
2160353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2161353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Infsign[result_sign]
2162353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2163353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # from here on, the result always goes through the call
2164353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # to _fix at the end of this function.
2165353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = None
2166353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2167353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # crude test to catch cases of extreme overflow/underflow.  If
2168353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2169353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2170353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # self**other >= 10**(Emax+1), so overflow occurs.  The test
2171353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # for underflow is similar.
2172353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        bound = self._log10_exp_bound() + other.adjusted()
2173353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if (self_adj >= 0) == (other._sign == 0):
2174353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # self > 1 and other +ve, or self < 1 and other -ve
2175353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # possibility of overflow
2176353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if bound >= len(str(context.Emax)):
217772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(result_sign, '1', context.Emax+1)
2178353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2179353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # self > 1 and other -ve, or self < 1 and other +ve
2180353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # possibility of underflow to 0
2181353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            Etiny = context.Etiny()
2182353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if bound >= len(str(-Etiny)):
218372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(result_sign, '1', Etiny-1)
2184353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2185353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # try for an exact result with precision +1
2186353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans is None:
2187353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._power_exact(other, context.prec + 1)
2188353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans is not None and result_sign == 1:
218972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(1, ans._int, ans._exp)
2190353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2191353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # usual case: inexact result, x**y computed directly as exp(y*log(x))
2192353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans is None:
2193353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            p = context.prec
2194353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            x = _WorkRep(self)
2195353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            xc, xe = x.int, x.exp
2196353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            y = _WorkRep(other)
2197353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            yc, ye = y.int, y.exp
2198353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if y.sign == 1:
2199353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                yc = -yc
2200353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2201353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # compute correctly rounded result:  start with precision +3,
2202353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # then increase precision until result is unambiguously roundable
2203353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            extra = 3
2204353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while True:
2205353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2206353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if coeff % (5*10**(len(str(coeff))-p-1)):
2207353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
2208353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                extra += 3
2209353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
221072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(result_sign, str(coeff), exp)
2211353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2212353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the specification says that for non-integer other we need to
2213353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # raise Inexact, even when the result is actually exact.  In
2214353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the same way, we need to raise Underflow here if the result
2215353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # is subnormal.  (The call to _fix will take care of raising
2216353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Rounded and Subnormal, as usual.)
2217353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not other._isinteger():
2218353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
2219353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # pad with zeros up to length context.prec+1 if necessary
2220353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if len(ans._int) <= context.prec:
2221353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                expdiff = context.prec+1 - len(ans._int)
222272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
222372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                       ans._exp-expdiff)
2224353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans.adjusted() < context.Emin:
2225353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Underflow)
2226353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2227353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # unlike exp, ln and log10, the power function respects the
2228353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # rounding mode; no need to use ROUND_HALF_EVEN here
2229353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2230353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
2231353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2232353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def __rpow__(self, other, context=None):
2233353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Swaps self/other and returns __pow__."""
2234353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other)
2235353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other is NotImplemented:
2236353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return other
2237353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return other.__pow__(self, context=context)
2238353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2239353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def normalize(self, context=None):
2240353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
2241353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2242353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2243353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2244353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2245353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
2246353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._check_nans(context=context)
2247353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans:
2248353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return ans
2249353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2250353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        dup = self._fix(context)
2251353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if dup._isinfinity():
2252353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return dup
2253353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2254353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not dup:
225572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(dup._sign, '0', 0)
2256353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exp_max = [context.Emax, context.Etop()][context._clamp]
2257353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        end = len(dup._int)
22587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exp = dup._exp
225972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        while dup._int[end-1] == '0' and exp < exp_max:
22607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            exp += 1
22617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            end -= 1
226272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(dup._sign, dup._int[:end], exp)
22637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2264bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista    def quantize(self, exp, rounding=None, context=None, watchexp=True):
22657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Quantize self so its exponent is the same as that of exp.
22667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
22677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Similar to self._rescale(exp._exp) but with error checking.
22687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2269bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista        exp = _convert_other(exp, raiseit=True)
2270bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista
2271353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2272353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2273353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if rounding is None:
2274353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rounding = context.rounding
2275353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2276636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or exp._is_special:
2277636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(exp, context)
2278636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
2279636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
22807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2281636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if exp._isinfinity() or self._isinfinity():
2282636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if exp._isinfinity() and self._isinfinity():
22836c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return Decimal(self)  # if both are inf, it is OK
2284636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return context._raise_error(InvalidOperation,
2285636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                                        'quantize with one INF')
2286353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2287bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista        # if we're not watching exponents, do a simple rescale
2288bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista        if not watchexp:
2289bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista            ans = self._rescale(exp._exp, rounding)
2290bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista            # raise Inexact and Rounded where appropriate
2291bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista            if ans._exp > self._exp:
2292bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista                context._raise_error(Rounded)
2293bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista                if ans != self:
2294bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista                    context._raise_error(Inexact)
2295bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista            return ans
2296bd2fe839db886de6ce9631acd8aa9796b413a565Facundo Batista
2297353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp._exp should be between Etiny and Emax
2298353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (context.Etiny() <= exp._exp <= context.Emax):
2299353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2300353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                   'target exponent out of bounds in quantize')
2301353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2302353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
230372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(self._sign, '0', exp._exp)
2304353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
2305353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2306353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_adjusted = self.adjusted()
2307353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_adjusted > context.Emax:
2308353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2309353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'exponent of quantize result too large for current context')
2310353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_adjusted - exp._exp + 1 > context.prec:
2311353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2312353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'quantize result has too many digits for current context')
2313353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2314353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._rescale(exp._exp, rounding)
2315353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans.adjusted() > context.Emax:
2316353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2317353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'exponent of quantize result too large for current context')
2318353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if len(ans._int) > context.prec:
2319353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2320353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'quantize result has too many digits for current context')
2321353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2322353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # raise appropriate flags
2323353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans._exp > self._exp:
2324353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Rounded)
2325353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans != self:
2326353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Inexact)
2327353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans and ans.adjusted() < context.Emin:
2328353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Subnormal)
2329353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2330353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # call to fix takes care of any necessary folddown
2331353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2332353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
23337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
23347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def same_quantum(self, other):
23351a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self and other have the same exponent; otherwise
23361a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return False.
23377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
23381a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        If either operand is a special value, the following rules are used:
23391a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista           * return True if both operands are infinities
23401a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista           * return True if both operands are NaNs
23411a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista           * otherwise, return False.
23427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
23431a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        other = _convert_other(other, raiseit=True)
2344636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
23451a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista            return (self.is_nan() and other.is_nan() or
23461a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista                    self.is_infinite() and other.is_infinite())
23477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return self._exp == other._exp
23487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2349353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _rescale(self, exp, rounding):
2350353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rescale self so that the exponent is exp, either by padding with zeros
2351353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        or by truncating digits, using the given rounding mode.
2352353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2353353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Specials are returned without change.  This operation is
2354353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        quiet: it raises no flags, and uses no information from the
2355353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.
23567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
23577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exp = exp to scale to (an integer)
2358353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = rounding mode
23597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2360636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
23616c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
23627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
236372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(self._sign, '0', exp)
23647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2365353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp >= exp:
2366353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # pad answer with zeros if necessary
236772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(self._sign,
236872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                        self._int + '0'*(self._exp - exp), exp)
23697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2370353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # too many digits; round and lose data.  If self.adjusted() <
2371353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp-1, replace self by 10**(exp-1) before rounding
2372353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        digits = len(self._int) + self._exp - exp
23737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if digits < 0:
237472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self = _dec_from_triple(self._sign, '1', exp-1)
2375353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            digits = 0
2376353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        this_function = getattr(self, self._pick_rounding_function[rounding])
23772ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        changed = this_function(digits)
23782ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        coeff = self._int[:digits] or '0'
23792ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        if changed == 1:
23802ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista            coeff = str(int(coeff)+1)
23812ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista        return _dec_from_triple(self._sign, coeff, exp)
23827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2383353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def to_integral_exact(self, rounding=None, context=None):
2384353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds to a nearby integer.
23857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2386353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        If no rounding mode is specified, take the rounding mode from
2387353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        the context.  This method raises the Rounded and Inexact flags
2388353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        when appropriate.
23897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2390353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        See also: to_integral_value, which does exactly the same as
2391353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        this method except that it doesn't raise Inexact or Rounded.
2392353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2393636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
2394636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
2395636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
2396636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
23976c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
23987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._exp >= 0:
23996c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
2400353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
240172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(self._sign, '0', 0)
2402636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
2403636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
2404353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if rounding is None:
2405353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rounding = context.rounding
2406353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._raise_error(Rounded)
2407353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._rescale(0, rounding)
2408353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans != self:
2409353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
24107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return ans
24117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2412353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def to_integral_value(self, rounding=None, context=None):
2413353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds to the nearest integer, without raising inexact, rounded."""
2414353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2415353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2416353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if rounding is None:
2417353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rounding = context.rounding
2418353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
2419353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self._check_nans(context=context)
2420353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if ans:
2421353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return ans
24226c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
2423353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp >= 0:
24246c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
2425353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2426353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._rescale(0, rounding)
24277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2428353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # the method name changed, but we provide also the old one, for compatibility
2429353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    to_integral = to_integral_value
2430353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2431353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def sqrt(self, context=None):
2432353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return the square root of self."""
2433636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special:
2434636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            ans = self._check_nans(context=context)
2435636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if ans:
2436636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return ans
24377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2438636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if self._isinfinity() and self._sign == 0:
2439636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return Decimal(self)
24407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
24417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if not self:
2442353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # exponent = self._exp // 2.  sqrt(-0) = -0
244372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(self._sign, '0', self._exp // 2)
2444353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans._fix(context)
24457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2446636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if context is None:
2447636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            context = getcontext()
2448636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
24497c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._sign == 1:
24507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
24517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2452353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # At this point self represents a positive number.  Let p be
2453353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the desired precision and express self in the form c*100**e
2454353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # with c a positive real number and e an integer, c and e
2455353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # being chosen so that 100**(p-1) <= c < 100**p.  Then the
2456353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2457353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # <= sqrt(c) < 10**p, so the closest representable Decimal at
2458353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # precision p is n*10**e where n = round_half_even(sqrt(c)),
2459353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the closest integer to sqrt(c) with the even integer chosen
2460353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # in the case of a tie.
2461353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        #
2462353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # To ensure correct rounding in all cases, we use the
2463353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # following trick: we compute the square root to an extra
2464353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # place (precision p+1 instead of precision p), rounding down.
2465353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Then, if the result is inexact and its last digit is 0 or 5,
2466353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # we increase the last digit to 1 or 6 respectively; if it's
2467353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exact we leave the last digit alone.  Now the final round to
2468353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # p places (or fewer in the case of underflow) will round
2469353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # correctly and raise the appropriate flags.
2470353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2471353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # use an extra digit of precision
2472353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        prec = context.prec+1
2473353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2474353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # write argument in the form c*100**e where e = self._exp//2
2475353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # is the 'ideal' exponent, to be used if the square root is
2476353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exactly representable.  l is the number of 'digits' of c in
2477353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # base 100, so that 100**(l-1) <= c < 100**l.
2478353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op = _WorkRep(self)
2479353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        e = op.exp >> 1
2480353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if op.exp & 1:
2481353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = op.int * 10
2482353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            l = (len(self._int) >> 1) + 1
24837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
2484353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = op.int
2485353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            l = len(self._int)+1 >> 1
2486353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2487353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # rescale so that c has exactly prec base 100 'digits'
2488353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        shift = prec-l
2489353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if shift >= 0:
2490353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c *= 100**shift
2491353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            exact = True
24927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
2493353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c, remainder = divmod(c, 100**-shift)
2494353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            exact = not remainder
2495353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        e -= shift
2496353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2497353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # find n = floor(sqrt(c)) using Newton's method
2498353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        n = 10**prec
2499353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while True:
2500353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            q = c//n
2501353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if n <= q:
25027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                break
2503353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2504353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n = n + q >> 1
2505353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exact = exact and n*n == c
2506353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2507353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if exact:
2508353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # result is exact; rescale to use ideal exponent e
2509353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if shift >= 0:
2510353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # assert n % 10**shift == 0
2511353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n //= 10**shift
2512353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2513353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n *= 10**-shift
2514353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            e += shift
25157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        else:
2516353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # result is not exact; fix last digit as described above
2517353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if n % 5 == 0:
2518353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                n += 1
25197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
252072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        ans = _dec_from_triple(0, str(n), e)
25217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2522353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # round, and fit to current context
2523353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context._shallow_copy()
2524353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = context._set_rounding(ROUND_HALF_EVEN)
2525dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger        ans = ans._fix(context)
2526353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.rounding = rounding
25277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2528353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
25297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
25307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def max(self, other, context=None):
25317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the larger value.
25327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2533353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Like max(self, other) except if one is not a number, returns
25347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        NaN (and signals if one is sNaN).  Also rounds.
25357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2536353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
2537636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
25386c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        if context is None:
25396c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            context = getcontext()
25406c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista
2541636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
254259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If one operand is a quiet NaN and the other is number, then the
2543636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            # number is always returned
2544636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            sn = self._isnan()
2545636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            on = other._isnan()
2546636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if sn or on:
2547636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if on == 1 and sn != 2:
25486c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return self._fix_nan(context)
2549636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if sn == 1 and on != 2:
25506c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return other._fix_nan(context)
2551636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return self._check_nans(other, context)
25527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
25532fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        c = self._cmp(other)
2554d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        if c == 0:
255559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If both operands are finite and equal in numerical value
2556d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger            # then an ordering is applied:
2557d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger            #
255859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If the signs differ then max returns the operand with the
2559d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger            # positive sign and min returns the operand with the negative sign
2560d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger            #
256159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If the signs are the same then the exponent is used to select
2562353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # the result.  This is exactly the ordering used in compare_total.
2563353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = self.compare_total(other)
2564353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2565353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == -1:
25667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = other
2567353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2568353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self
2569636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
2570e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        return ans._fix(context)
25717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
25727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def min(self, other, context=None):
25737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the smaller value.
25747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
257559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        Like min(self, other) except if one is not a number, returns
25767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        NaN (and signals if one is sNaN).  Also rounds.
25777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
2578353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
2579636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
25806c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        if context is None:
25816c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            context = getcontext()
25826c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista
2583636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        if self._is_special or other._is_special:
258459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # If one operand is a quiet NaN and the other is number, then the
2585636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            # number is always returned
2586636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            sn = self._isnan()
2587636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            on = other._isnan()
2588636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            if sn or on:
2589636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if on == 1 and sn != 2:
25906c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return self._fix_nan(context)
2591636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                if sn == 1 and on != 2:
25926c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return other._fix_nan(context)
2593636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger                return self._check_nans(other, context)
25947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
25952fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        c = self._cmp(other)
2596d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        if c == 0:
2597353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = self.compare_total(other)
2598353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2599353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == -1:
2600353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self
2601353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
26027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            ans = other
2603636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
2604e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        return ans._fix(context)
26057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
26067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _isinteger(self):
26077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns whether self is an integer"""
2608353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special:
2609353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return False
26107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if self._exp >= 0:
26117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return True
26127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rest = self._int[self._exp:]
261372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return rest == '0'*len(rest)
26147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
26157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _iseven(self):
2616353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns True if self is even.  Assumes self is an integer."""
2617353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self or self._exp > 0:
2618353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return True
261972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return self._int[-1+self._exp] in '02468'
26207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
26217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def adjusted(self):
26227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return the adjusted exponent of self"""
26237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        try:
26247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return self._exp + len(self._int) - 1
262559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # If NaN or Infinity, self._exp is string
26267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        except TypeError:
26277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return 0
26287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
2629353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def canonical(self, context=None):
2630353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the same Decimal object.
2631353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2632353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        As we do not have different encodings for the same number, the
2633353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        received object already is in its canonical form.
2634353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2635353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self
2636353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2637353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_signal(self, other, context=None):
2638353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares self to the other operand numerically.
2639353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2640353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        It's pretty much like compare(), but all NaNs signal, with signaling
2641353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        NaNs taking precedence over quiet NaNs.
2642353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
26432fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        other = _convert_other(other, raiseit = True)
26442fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        ans = self._compare_check_nans(other, context)
26452fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        if ans:
26462fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson            return ans
2647353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return self.compare(other, context=context)
2648353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2649353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_total(self, other):
2650353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares self to other using the abstract representations.
2651353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2652353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        This is not like the standard compare, which use their numerical
2653353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        value. Note that a total ordering is defined for all possible abstract
2654353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        representations.
2655353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2656353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # if one is negative and the other is positive, it's easy
2657353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign and not other._sign:
2658353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_n1
2659353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self._sign and other._sign:
2660353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_p1
2661353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        sign = self._sign
2662353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2663353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # let's handle both NaN types
2664353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        self_nan = self._isnan()
2665353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other_nan = other._isnan()
2666353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self_nan or other_nan:
2667353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self_nan == other_nan:
2668353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self._int < other._int:
2669353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if sign:
2670353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return Dec_p1
2671353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    else:
2672353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return Dec_n1
2673353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self._int > other._int:
2674353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    if sign:
2675353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return Dec_n1
2676353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    else:
2677353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                        return Dec_p1
2678353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_0
2679353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2680353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sign:
2681353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_nan == 1:
2682353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_n1
2683353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other_nan == 1:
2684353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_p1
2685353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_nan == 2:
2686353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_n1
2687353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other_nan == 2:
2688353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_p1
2689353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2690353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_nan == 1:
2691353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_p1
2692353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other_nan == 1:
2693353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_n1
2694353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if self_nan == 2:
2695353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_p1
2696353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if other_nan == 2:
2697353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    return Dec_n1
2698353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2699353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self < other:
2700353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_n1
2701353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self > other:
2702353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_p1
2703353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2704353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp < other._exp:
2705353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sign:
2706353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_p1
2707353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2708353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_n1
2709353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._exp > other._exp:
2710353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sign:
2711353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_n1
2712353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
2713353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return Dec_p1
2714353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Dec_0
2715353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2716353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2717353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_total_mag(self, other):
2718353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares self to other using abstract repr., ignoring sign.
2719353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2720353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Like compare_total, but with operand's sign ignored and assumed to be 0.
2721353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2722353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        s = self.copy_abs()
2723353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        o = other.copy_abs()
2724353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return s.compare_total(o)
2725353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2726353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_abs(self):
2727353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy with the sign set to 0. """
272872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(0, self._int, self._exp, self._is_special)
2729353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2730353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_negate(self):
2731353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy with the sign inverted."""
2732353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign:
273372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(0, self._int, self._exp, self._is_special)
2734353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
273572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(1, self._int, self._exp, self._is_special)
2736353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2737353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_sign(self, other):
2738353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns self with the sign of other."""
273972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(other._sign, self._int,
274072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                self._exp, self._is_special)
2741353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2742353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def exp(self, context=None):
2743353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns e ** self."""
2744353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2745353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2746353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2747353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2748353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp(NaN) = NaN
2749353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
2750353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
2751353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
2752353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2753353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp(-Infinity) = 0
2754353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == -1:
2755353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_0
2756353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2757353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp(0) = 1
2758353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2759353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_p1
2760353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2761353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exp(Infinity) = Infinity
2762353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
2763353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Decimal(self)
2764353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2765353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the result is now guaranteed to be inexact (the true
2766353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # mathematical result is transcendental). There's no need to
2767353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # raise Rounded and Inexact here---they'll always be raised as
2768353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # a result of the call to _fix.
2769353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        p = context.prec
2770353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        adj = self.adjusted()
2771353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2772353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # we only need to do any computation for quite a small range
2773353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # of adjusted exponents---for example, -29 <= adj <= 10 for
2774353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # the default context.  For smaller exponent the result is
2775353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # indistinguishable from 1 at the given precision, while for
2776353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # larger exponent the result either overflows or underflows.
2777353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2778353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # overflow
277972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(0, '1', context.Emax+1)
2780353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2781353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # underflow to 0
278272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(0, '1', context.Etiny()-1)
2783353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif self._sign == 0 and adj < -p:
2784353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # p+1 digits; final round will raise correct flags
278572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
2786353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif self._sign == 1 and adj < -p-1:
2787353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # p+1 digits; final round will raise correct flags
278872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(0, '9'*(p+1), -p-1)
2789353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # general case
2790353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
2791353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            op = _WorkRep(self)
2792353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c, e = op.int, op.exp
2793353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if op.sign == 1:
2794353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                c = -c
2795353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2796353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # compute correctly rounded result: increase precision by
2797353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # 3 digits at a time until we get an unambiguously
2798353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # roundable result
2799353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            extra = 3
2800353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while True:
2801353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                coeff, exp = _dexp(c, e, p+extra)
2802353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if coeff % (5*10**(len(str(coeff))-p-1)):
2803353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
2804353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                extra += 3
2805353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
280672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(0, str(coeff), exp)
2807353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2808353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # at this stage, ans should round correctly with *any*
2809353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # rounding mode, not just with ROUND_HALF_EVEN
2810353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context._shallow_copy()
2811353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = context._set_rounding(ROUND_HALF_EVEN)
2812353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2813353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.rounding = rounding
2814353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2815353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
2816353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2817353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_canonical(self):
28181a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is canonical; otherwise return False.
28191a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista
28201a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        Currently, the encoding of a Decimal instance is always
28211a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        canonical, so this method returns True for any Decimal.
28221a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """
28231a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return True
2824353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2825353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_finite(self):
28261a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is finite; otherwise return False.
2827353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
28281a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        A Decimal instance is considered finite if it is neither
28291a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        infinite nor a NaN.
2830353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
28311a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return not self._is_special
2832353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2833353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_infinite(self):
28341a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is infinite; otherwise return False."""
28351a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self._exp == 'F'
2836353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2837353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_nan(self):
28381a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is a qNaN or sNaN; otherwise return False."""
28391a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self._exp in ('n', 'N')
2840353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2841353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_normal(self, context=None):
28421a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is a normal number; otherwise return False."""
28431a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        if self._is_special or not self:
28441a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista            return False
2845353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2846353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
28471a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return context.Emin <= self.adjusted() <= context.Emax
2848353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2849353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_qnan(self):
28501a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is a quiet NaN; otherwise return False."""
28511a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self._exp == 'n'
2852353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2853353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_signed(self):
28541a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is negative; otherwise return False."""
28551a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self._sign == 1
2856353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2857353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_snan(self):
28581a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is a signaling NaN; otherwise return False."""
28591a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self._exp == 'N'
2860353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2861353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_subnormal(self, context=None):
28621a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is subnormal; otherwise return False."""
28631a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        if self._is_special or not self:
28641a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista            return False
2865353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2866353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
28671a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return self.adjusted() < context.Emin
2868353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2869353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_zero(self):
28701a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if self is a zero; otherwise return False."""
287172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return not self._is_special and self._int == '0'
2872353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2873353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _ln_exp_bound(self):
2874353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compute a lower bound for the adjusted exponent of self.ln().
2875353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        In other words, compute r such that self.ln() >= 10**r.  Assumes
2876353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        that self is finite and positive and that self != 1.
2877353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2878353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2879353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2880353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        adj = self._exp + len(self._int) - 1
2881353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj >= 1:
2882353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2883353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(str(adj*23//10)) - 1
2884353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj <= -2:
2885353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # argument <= 0.1
2886353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(str((-1-adj)*23//10)) - 1
2887353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op = _WorkRep(self)
2888353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c, e = op.int, op.exp
2889353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj == 0:
2890353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # 1 < self < 10
2891353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            num = str(c-10**-e)
2892353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            den = str(c)
2893353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(num) - len(den) - (num < den)
2894353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # adj == -1, 0.1 <= self < 1
2895353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return e + len(str(10**-e - c)) - 1
2896353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2897353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2898353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def ln(self, context=None):
2899353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the natural (base e) logarithm of self."""
2900353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2901353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2902353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2903353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2904353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(NaN) = NaN
2905353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
2906353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
2907353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
2908353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2909353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(0.0) == -Infinity
2910353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2911353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return negInf
2912353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2913353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(Infinity) = Infinity
2914353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
2915353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Inf
2916353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2917353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(1.0) == 0.0
2918353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self == Dec_p1:
2919353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Dec_0
2920353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2921353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # ln(negative) raises InvalidOperation
2922353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign == 1:
2923353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
2924353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'ln of a negative value')
2925353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2926353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # result is irrational, so necessarily inexact
2927353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op = _WorkRep(self)
2928353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c, e = op.int, op.exp
2929353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        p = context.prec
2930353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2931353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # correctly rounded result: repeatedly increase precision by 3
2932353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # until we get an unambiguously roundable result
2933353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        places = p - self._ln_exp_bound() + 2 # at least p+3 places
2934353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        while True:
2935353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            coeff = _dlog(c, e, places)
2936353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # assert len(str(abs(coeff)))-p >= 1
2937353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2938353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                break
2939353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            places += 3
294072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
2941353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2942353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context._shallow_copy()
2943353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = context._set_rounding(ROUND_HALF_EVEN)
2944353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
2945353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.rounding = rounding
2946353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
2947353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2948353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _log10_exp_bound(self):
2949353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compute a lower bound for the adjusted exponent of self.log10().
2950353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        In other words, find r such that self.log10() >= 10**r.
2951353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Assumes that self is finite and positive and that self != 1.
2952353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
2953353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2954353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # For x >= 10 or x < 0.1 we only need a bound on the integer
2955353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # part of log10(self), and this comes directly from the
2956353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # exponent of x.  For 0.1 <= x <= 10 we use the inequalities
2957353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2958353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # (1-1/x)/2.31 > 0.  If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2959353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2960353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        adj = self._exp + len(self._int) - 1
2961353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj >= 1:
2962353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # self >= 10
2963353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(str(adj))-1
2964353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj <= -2:
2965353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # self < 0.1
2966353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(str(-1-adj))-1
2967353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        op = _WorkRep(self)
2968353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        c, e = op.int, op.exp
2969353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if adj == 0:
2970353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # 1 < self < 10
2971353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            num = str(c-10**-e)
2972353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            den = str(231*c)
2973353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return len(num) - len(den) - (num < den) + 2
2974353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # adj == -1, 0.1 <= self < 1
2975353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        num = str(10**-e-c)
2976353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return len(num) + e - (num < "231") - 1
2977353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2978353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def log10(self, context=None):
2979353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the base 10 logarithm of self."""
2980353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2981353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
2982353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
2983353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2984353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(NaN) = NaN
2985353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
2986353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
2987353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
2988353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2989353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(0.0) == -Infinity
2990353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
2991353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return negInf
2992353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2993353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(Infinity) = Infinity
2994353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
2995353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Inf
2996353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
2997353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(negative or -Infinity) raises InvalidOperation
2998353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign == 1:
2999353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation,
3000353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                        'log10 of a negative value')
3001353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3002353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # log10(10**n) = n
300372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
3004353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # answer may need rounding
3005353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = Decimal(self._exp + len(self._int) - 1)
3006353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
3007353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # result is irrational, so necessarily inexact
3008353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            op = _WorkRep(self)
3009353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c, e = op.int, op.exp
3010353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            p = context.prec
3011353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3012353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # correctly rounded result: repeatedly increase precision
3013353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # until result is unambiguously roundable
3014353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            places = p-self._log10_exp_bound()+2
3015353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            while True:
3016353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                coeff = _dlog10(c, e, places)
3017353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                # assert len(str(abs(coeff)))-p >= 1
3018353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3019353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                    break
3020353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                places += 3
302172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
3022353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3023353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context._shallow_copy()
3024353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rounding = context._set_rounding(ROUND_HALF_EVEN)
3025353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = ans._fix(context)
3026353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.rounding = rounding
3027353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
3028353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3029353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logb(self, context=None):
3030353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """ Returns the exponent of the magnitude of self's MSD.
3031353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3032353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result is the integer which is the exponent of the magnitude
3033353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        of the most significant digit of self (as though it were truncated
3034353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        to a single digit while maintaining the value of that digit and
3035353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        without limiting the resulting exponent).
3036353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3037353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # logb(NaN) = NaN
3038353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
3039353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3040353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3041353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3042353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3043353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3044353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3045353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # logb(+/-Inf) = +Inf
3046353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
3047353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Inf
3048353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3049353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # logb(0) = -Inf, DivisionByZero
3050353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self:
3051cce8df2f678b1e1ec11c86cf2fabf12c2077577dFacundo Batista            return context._raise_error(DivisionByZero, 'logb(0)', 1)
3052353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3053353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # otherwise, simply return the adjusted exponent of self, as a
3054353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # Decimal.  Note that no attempt is made to fit the result
3055353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # into the current context.
3056353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal(self.adjusted())
3057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3058353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _islogical(self):
3059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Return True if self is a logical operand.
3060353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3061c8acc882a92c1fe5df95ae73b7b8004737ed9222Andrew M. Kuchling        For being logical, it must be a finite number with a sign of 0,
3062353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        an exponent of 0, and a coefficient whose digits must all be
3063353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        either 0 or 1.
3064353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3065353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign != 0 or self._exp != 0:
3066353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return False
3067353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        for dig in self._int:
306872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            if dig not in '01':
3069353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return False
3070353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return True
3071353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3072353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def _fill_logical(self, context, opa, opb):
3073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        dif = context.prec - len(opa)
3074353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if dif > 0:
307572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            opa = '0'*dif + opa
3076353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif dif < 0:
3077353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            opa = opa[-context.prec:]
3078353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        dif = context.prec - len(opb)
3079353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if dif > 0:
308072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            opb = '0'*dif + opb
3081353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif dif < 0:
3082353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            opb = opb[-context.prec:]
3083353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return opa, opb
3084353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3085353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_and(self, other, context=None):
3086353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies an 'and' operation between self and other's digits."""
3087353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3088353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3089353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self._islogical() or not other._islogical():
3090353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3091353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3092353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # fill to context.prec
3093353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        (opa, opb) = self._fill_logical(context, self._int, other._int)
3094353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3095353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # make the operation, and clean starting zeroes
309672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
309772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3098353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3099353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_invert(self, context=None):
3100353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Invert all its digits."""
3101353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3102353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
310372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
310472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                context)
3105353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3106353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_or(self, other, context=None):
3107353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies an 'or' operation between self and other's digits."""
3108353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3109353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3110353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self._islogical() or not other._islogical():
3111353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3112353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3113353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # fill to context.prec
3114353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        (opa, opb) = self._fill_logical(context, self._int, other._int)
3115353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3116353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # make the operation, and clean starting zeroes
311772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
311872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3119353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3120353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_xor(self, other, context=None):
3121353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies an 'xor' operation between self and other's digits."""
3122353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3123353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3124353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not self._islogical() or not other._islogical():
3125353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3126353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3127353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # fill to context.prec
3128353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        (opa, opb) = self._fill_logical(context, self._int, other._int)
3129353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3130353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # make the operation, and clean starting zeroes
313172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
313272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3133353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3134353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def max_mag(self, other, context=None):
3135353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values numerically with their sign ignored."""
3136353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
3137353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
31386c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        if context is None:
31396c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            context = getcontext()
31406c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista
3141353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special or other._is_special:
3142353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # If one operand is a quiet NaN and the other is number, then the
3143353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # number is always returned
3144353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sn = self._isnan()
3145353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            on = other._isnan()
3146353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sn or on:
3147353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if on == 1 and sn != 2:
31486c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return self._fix_nan(context)
3149353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if sn == 1 and on != 2:
31506c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return other._fix_nan(context)
3151353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self._check_nans(other, context)
3152353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
31532fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        c = self.copy_abs()._cmp(other.copy_abs())
3154353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == 0:
3155353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = self.compare_total(other)
3156353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3157353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == -1:
3158353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = other
3159353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
3160353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self
3161353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3162e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        return ans._fix(context)
3163353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3164353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def min_mag(self, other, context=None):
3165353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values numerically with their sign ignored."""
3166353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
3167353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
31686c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        if context is None:
31696c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            context = getcontext()
31706c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista
3171353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._is_special or other._is_special:
3172353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # If one operand is a quiet NaN and the other is number, then the
3173353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # number is always returned
3174353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            sn = self._isnan()
3175353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            on = other._isnan()
3176353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if sn or on:
3177353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if on == 1 and sn != 2:
31786c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return self._fix_nan(context)
3179353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                if sn == 1 and on != 2:
31806c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista                    return other._fix_nan(context)
3181353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return self._check_nans(other, context)
3182353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
31832fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        c = self.copy_abs()._cmp(other.copy_abs())
3184353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == 0:
3185353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = self.compare_total(other)
3186353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3187353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if c == -1:
3188353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self
3189353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
3190353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = other
3191353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3192e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        return ans._fix(context)
3193353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3194353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_minus(self, context=None):
3195353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the largest representable number smaller than itself."""
3196353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3197353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3198353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3199353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
3200353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3201353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3202353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3203353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == -1:
3204353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return negInf
3205353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
320672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(0, '9'*context.prec, context.Etop())
3207353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3208353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context.copy()
3209353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._set_rounding(ROUND_FLOOR)
3210353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._ignore_all_flags()
3211353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        new_self = self._fix(context)
3212353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if new_self != self:
3213353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return new_self
321472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
321572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                            context)
3216353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3217353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_plus(self, context=None):
3218353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the smallest representable number larger than itself."""
3219353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3220353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3221353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3222353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(context=context)
3223353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3224353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3225353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3226353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == 1:
3227353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return Inf
3228353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity() == -1:
322972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return _dec_from_triple(1, '9'*context.prec, context.Etop())
3230353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3231353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context = context.copy()
3232353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._set_rounding(ROUND_CEILING)
3233353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context._ignore_all_flags()
3234353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        new_self = self._fix(context)
3235353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if new_self != self:
3236353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return new_self
323772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
323872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                            context)
3239353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3240353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_toward(self, other, context=None):
3241353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the number closest to self, in the direction towards other.
3242353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3243353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result is the closest representable number to self
3244353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        (excluding self) that is in the direction towards other,
3245353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        unless both have the same value.  If the two operands are
3246353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        numerically equal, then the result is a copy of self with the
3247353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        sign set to be the same as the sign of other.
3248353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3249353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        other = _convert_other(other, raiseit=True)
3250353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3251353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3252353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3253353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3254353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
3255353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3256353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3257353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
32582fc9263df56d28a6c1def6c8a0517bbddfa899afMark Dickinson        comparison = self._cmp(other)
3259353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if comparison == 0:
326072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            return self.copy_sign(other)
3261353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3262353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if comparison == -1:
3263353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.next_plus(context)
3264353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else: # comparison == 1
3265353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            ans = self.next_minus(context)
3266353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3267353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # decide which flags to raise using value of ans
3268353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans._isinfinity():
3269353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Overflow,
3270353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                 'Infinite result from next_toward',
3271353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                 ans._sign)
3272353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Rounded)
3273353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
3274353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        elif ans.adjusted() < context.Emin:
3275353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Underflow)
3276353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Subnormal)
3277353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Rounded)
3278353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context._raise_error(Inexact)
3279353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # if precision == 1 then we don't raise Clamped for a
3280353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            # result 0E-Etiny.
3281353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if not ans:
3282353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                context._raise_error(Clamped)
3283353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3284353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return ans
3285353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3286353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def number_class(self, context=None):
3287353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns an indication of the class of self.
3288353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3289353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The class is one of the following strings:
32900f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista          sNaN
32910f5e7bf3049408d6f4c1855807204c9f13ae98f9Facundo Batista          NaN
3292353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Infinity
3293353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Normal
3294353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Subnormal
3295353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Zero
3296353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Zero
3297353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Subnormal
3298353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Normal
3299353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Infinity
3300353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3301353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self.is_snan():
3302353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "sNaN"
3303353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self.is_qnan():
3304353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "NaN"
3305353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        inf = self._isinfinity()
3306353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if inf == 1:
3307353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "+Infinity"
3308353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if inf == -1:
3309353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "-Infinity"
3310353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self.is_zero():
3311353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self._sign:
3312353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return "-Zero"
3313353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
3314353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return "+Zero"
3315353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3316353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3317353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self.is_subnormal(context=context):
3318353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            if self._sign:
3319353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return "-Subnormal"
3320353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            else:
3321353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                return "+Subnormal"
3322353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # just a normal, regular, boring number, :)
3323353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._sign:
3324353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "-Normal"
3325353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
3326353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return "+Normal"
3327353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3328353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def radix(self):
3329353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Just returns 10, as this is Decimal, :)"""
3330353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal(10)
3331353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3332353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def rotate(self, other, context=None):
3333353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a rotated copy of self, value-of-other times."""
3334353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3335353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3336353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3337353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
3338353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3339353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3340353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3341353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._exp != 0:
3342353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3343353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (-context.prec <= int(other) <= context.prec):
3344353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3345353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3346353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
33476c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
3348353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3349353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # get values, pad if necessary
3350353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        torot = int(other)
3351353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotdig = self._int
3352353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        topad = context.prec - len(rotdig)
3353353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if topad:
335472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            rotdig = '0'*topad + rotdig
3355353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3356353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # let's rotate!
3357353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotated = rotdig[torot:] + rotdig[:torot]
335872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(self._sign,
335972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                rotated.lstrip('0') or '0', self._exp)
3360353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3361353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def scaleb (self, other, context=None):
3362353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns self operand after adding the second value to its exp."""
3363353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3364353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3365353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3366353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
3367353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3368353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3369353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3370353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._exp != 0:
3371353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3372353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        liminf = -2 * (context.Emax + context.prec)
3373353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        limsup =  2 * (context.Emax + context.prec)
3374353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (liminf <= int(other) <= limsup):
3375353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3376353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3377353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
33786c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
3379353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
338072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
3381353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        d = d._fix(context)
3382353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return d
3383353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3384353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def shift(self, other, context=None):
3385353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a shifted copy of self, value-of-other times."""
3386353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if context is None:
3387353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            context = getcontext()
3388353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3389353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        ans = self._check_nans(other, context)
3390353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ans:
3391353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return ans
3392353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3393353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if other._exp != 0:
3394353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3395353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not (-context.prec <= int(other) <= context.prec):
3396353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return context._raise_error(InvalidOperation)
3397353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3398353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if self._isinfinity():
33996c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
3400353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3401353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # get values, pad if necessary
3402353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        torot = int(other)
3403353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if not torot:
34046c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista            return Decimal(self)
3405353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotdig = self._int
3406353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        topad = context.prec - len(rotdig)
3407353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if topad:
340872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            rotdig = '0'*topad + rotdig
3409353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3410353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # let's shift!
3411353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if torot < 0:
3412353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rotated = rotdig[:torot]
3413353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
341472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            rotated = rotdig + '0'*torot
3415353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            rotated = rotated[-context.prec:]
3416353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
341772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        return _dec_from_triple(self._sign,
341872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista                                    rotated.lstrip('0') or '0', self._exp)
3419353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
342059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # Support for pickling, copy, and deepcopy
34217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __reduce__(self):
34227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return (self.__class__, (str(self),))
34237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
34247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __copy__(self):
34257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if type(self) == Decimal:
3426cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis            return self     # I'm immutable; therefore I am my own clone
34277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return self.__class__(str(self))
34287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
34297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __deepcopy__(self, memo):
34307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if type(self) == Decimal:
3431cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis            return self     # My components are also immutable
34327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return self.__class__(str(self))
34337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
343472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batistadef _dec_from_triple(sign, coefficient, exponent, special=False):
343572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    """Create a decimal instance directly, without any validation,
343672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    normalization (e.g. removal of leading zeros) or argument
343772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    conversion.
343872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista
343972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    This function is for *internal use only*.
344072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    """
344172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista
344272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    self = object.__new__(Decimal)
344372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    self._sign = sign
344472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    self._int = coefficient
344572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    self._exp = exponent
344672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    self._is_special = special
344772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista
344872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    return self
344972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista
345059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Context class #######################################################
3451cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis
34527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3453cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis# get rounding method function:
345459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batistarounding_functions = [name for name in Decimal.__dict__.keys()
345559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                                    if name.startswith('_round_')]
34567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerfor name in rounding_functions:
345759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
34587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    globalname = name[1:].upper()
34597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    val = globals()[globalname]
34607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Decimal._pick_rounding_function[val] = name
34617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
34629ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettingerdel name, val, globalname, rounding_functions
34637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3464ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlanclass _ContextManager(object):
34658b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """Context manager class to support localcontext().
34661a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum
3467ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlan      Sets a copy of the supplied context in __enter__() and restores
34688b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan      the previous decimal context in __exit__()
34698b6999b4c5fab174090be263ba90f193bdede141Nick Coghlan    """
34701a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum    def __init__(self, new_context):
3471ced1218dd1b69ac848f8c79d1afaada5669af33cNick Coghlan        self.new_context = new_context.copy()
34721a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum    def __enter__(self):
34731a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum        self.saved_context = getcontext()
34741a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum        setcontext(self.new_context)
34751a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum        return self.new_context
34761a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum    def __exit__(self, t, v, tb):
34771a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum        setcontext(self.saved_context)
34781a5e21e0334a6d4e1c756575023c7157fc9ee306Guido van Rossum
34797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass Context(object):
34807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Contains the context for a Decimal instance.
34817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
34827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Contains:
34837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    prec - precision (for use in rounding, division, square roots..)
348459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    rounding - rounding type (how you round)
3485bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger    traps - If traps[exception] = 1, then the exception is
34867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    raised when it is caused.  Otherwise, a value is
34877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    substituted in.
34887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    flags  - When an exception is caused, flags[exception] is incremented.
34897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger             (Whether or not the trap_enabler is set)
34907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger             Should be reset by user of Decimal instance.
34910ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettinger    Emin -   Minimum exponent
34920ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettinger    Emax -   Maximum exponent
34937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    capitals -      If 1, 1*10^1 is printed as 1E+1.
34947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                    If 0, printed as 1e1
3495e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger    _clamp - If 1, change exponents if too high (Default 0)
34967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
34979ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger
34987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __init__(self, prec=None, rounding=None,
3499abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger                 traps=None, flags=None,
35000ea241e9e2d2accb625c4b1d3af6dd1f8df23a75Raymond Hettinger                 Emin=None, Emax=None,
3501e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger                 capitals=None, _clamp=0,
3502abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger                 _ignored_flags=None):
3503abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger        if flags is None:
3504abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger            flags = []
3505abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger        if _ignored_flags is None:
3506abf8a56e68a38f5bcff1fa1aa3742ff35854dd45Raymond Hettinger            _ignored_flags = []
3507bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        if not isinstance(flags, dict):
3508fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger            flags = dict([(s,s in flags) for s in _signals])
3509b91af521fddac47b14c57cd9ba736775334e6379Raymond Hettinger            del s
3510bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        if traps is not None and not isinstance(traps, dict):
3511fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger            traps = dict([(s,s in traps) for s in _signals])
3512b91af521fddac47b14c57cd9ba736775334e6379Raymond Hettinger            del s
35137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        for name, val in locals().items():
35147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            if val is None:
3515eb2608415ee4eb8aaea746f6a313937e264d0cdaRaymond Hettinger                setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
35167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            else:
35177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger                setattr(self, name, val)
35187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        del self.self
35197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3520b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger    def __repr__(self):
3521bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        """Show the current context."""
3522b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger        s = []
352359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
352459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
352559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista                 % vars(self))
352659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        names = [f.__name__ for f, v in self.flags.items() if v]
352759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        s.append('flags=[' + ', '.join(names) + ']')
352859c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        names = [t.__name__ for t, v in self.traps.items() if v]
352959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        s.append('traps=[' + ', '.join(names) + ']')
3530b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger        return ', '.join(s) + ')'
3531b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger
3532d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger    def clear_flags(self):
3533d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger        """Reset all flags to zero"""
3534d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger        for flag in self.flags:
3535b1b605ef546c45eac3c53db369ea6e881f05dc8bRaymond Hettinger            self.flags[flag] = 0
3536d9c0a7ae94ef81e69d927d834131bad760d4d99dRaymond Hettinger
35379fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger    def _shallow_copy(self):
35389fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        """Returns a shallow copy from self."""
3539e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        nc = Context(self.prec, self.rounding, self.traps,
3540e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista                     self.flags, self.Emin, self.Emax,
3541e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista                     self.capitals, self._clamp, self._ignored_flags)
35427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return nc
35439fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger
35449fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger    def copy(self):
35459fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        """Returns a deep copy from self."""
354659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        nc = Context(self.prec, self.rounding, self.traps.copy(),
3547e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista                     self.flags.copy(), self.Emin, self.Emax,
3548e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista                     self.capitals, self._clamp, self._ignored_flags)
35499fce44bc8cfb57d247e81ed18ac521db0fa015f5Raymond Hettinger        return nc
35509ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger    __copy__ = copy
35517c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35525aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger    def _raise_error(self, condition, explanation = None, *args):
35537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Handles an error
35547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the flag is in _ignored_flags, returns the default response.
35567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Otherwise, it increments the flag, then, if the corresponding
35577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        trap_enabler is set, it reaises the exception.  Otherwise, it returns
35587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        the default value after incrementing the flag.
35597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
35605aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger        error = _condition_map.get(condition, condition)
35617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if error in self._ignored_flags:
356259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # Don't touch the flag
35637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            return error().handle(self, *args)
35647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self.flags[error] += 1
3566bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        if not self.traps[error]:
356759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista            # The errors define how to handle themselves.
35685aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger            return condition().handle(self, *args)
35697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Errors should only be risked on copies of the context
357159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        # self._ignored_flags = []
35727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        raise error, explanation
35737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _ignore_all_flags(self):
35757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Ignore all flags, if they are raised"""
3576fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger        return self._ignore_flags(*_signals)
35777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _ignore_flags(self, *flags):
35797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Ignore the flags, if they are raised"""
35807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # Do not mutate-- This way, copies of a context leave the original
35817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # alone.
35827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self._ignored_flags = (self._ignored_flags + list(flags))
35837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return list(flags)
35847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _regard_flags(self, *flags):
35867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Stop ignoring the flags, if they are raised"""
35877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if flags and isinstance(flags[0], (tuple,list)):
35887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            flags = flags[0]
35897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        for flag in flags:
35907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self._ignored_flags.remove(flag)
35917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
35925aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger    def __hash__(self):
35935aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger        """A Context cannot be hashed."""
35945aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger        # We inherit object.__hash__, so we must deny this explicitly
359559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        raise TypeError("Cannot hash a Context.")
35965aa478badfabb005e6f17c98fcf007a0bc54eeccRaymond Hettinger
35977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def Etiny(self):
35987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns Etiny (= Emin - prec + 1)"""
35997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return int(self.Emin - self.prec + 1)
36007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def Etop(self):
3602e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger        """Returns maximum exponent (= Emax - prec + 1)"""
36037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return int(self.Emax - self.prec + 1)
36047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _set_rounding(self, type):
36067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Sets the rounding type.
36077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Sets the rounding type, and returns the current (previous)
36097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding type.  Often used like:
36107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        context = context.copy()
36127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # so you don't change the calling context
36137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        # if an error occurs in the middle.
36147c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding = context._set_rounding(ROUND_UP)
36157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        val = self.__sub__(other, context=context)
36167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        context._set_rounding(rounding)
36177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        This will make it round up for that operation.
36197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
36207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        rounding = self.rounding
36217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        self.rounding= type
36227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return rounding
36237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3624fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger    def create_decimal(self, num='0'):
362559bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson        """Creates a new Decimal instance but using self as context.
362659bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson
362759bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson        This method implements the to-number operation of the
362859bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson        IBM Decimal specification."""
362959bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson
363059bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson        if isinstance(num, basestring) and num != num.strip():
363159bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson            return self._raise_error(ConversionSyntax,
363259bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson                                     "no trailing or leading whitespace is "
363359bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson                                     "permitted.")
363459bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson
36357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        d = Decimal(num, context=self)
3636353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if d._isnan() and len(d._int) > self.prec - self._clamp:
3637353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            return self._raise_error(ConversionSyntax,
3638353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                                     "diagnostic info too long in NaN")
3639dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger        return d._fix(self)
36407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
364159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista    # Methods
36427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def abs(self, a):
36437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the absolute value of the operand.
36447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the operand is negative, the result is the same as using the minus
364659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operation on the operand.  Otherwise, the result is the same as using
36477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        the plus operation on the operand.
36487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36499ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.abs(Decimal('2.1'))
3650abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.1')
36519ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.abs(Decimal('-100'))
3652abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('100')
36539ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.abs(Decimal('101.5'))
3654abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('101.5')
36559ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.abs(Decimal('-101.5'))
3656abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('101.5')
36577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
36587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__abs__(context=self)
36597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def add(self, a, b):
36617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Return the sum of the two operands.
36627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36639ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
3664abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('19.00')
36659ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
3666abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.02E+4')
36677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
36687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__add__(b, context=self)
36697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def _apply(self, a):
3671dab988dd23e6328dadfe8408cd96abf4b017380dRaymond Hettinger        return str(a._fix(self))
36727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3673353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def canonical(self, a):
3674353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the same Decimal object.
3675353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3676353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        As we do not have different encodings for the same number, the
3677353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        received object already is in its canonical form.
3678353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3679353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.canonical(Decimal('2.50'))
3680abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.50')
3681353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3682353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.canonical(context=self)
3683353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
36847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def compare(self, a, b):
36857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Compares values numerically.
36867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the signs of the operands differ, a value representing each operand
36887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        ('-1' if the operand is less than zero, '0' if the operand is zero or
36897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        negative zero, or '1' if the operand is greater than zero) is used in
36907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        place of that operand for the comparison instead of the actual
36917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        operand.
36927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The comparison is then effected by subtracting the second operand from
36947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        the first and then returning a value according to the result of the
36957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        subtraction: '-1' if the result is less than zero, '0' if the result is
36967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        zero or negative zero, or '1' if the result is greater than zero.
36977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
36989ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
3699abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1')
37009ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
3701abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
37029ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
3703abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
37049ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
3705abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
37069ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
3707abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
37089ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
3709abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1')
37107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
37117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.compare(b, context=self)
37127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3713353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_signal(self, a, b):
3714353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values of the two operands numerically.
3715353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3716353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        It's pretty much like compare(), but all NaNs signal, with signaling
3717353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        NaNs taking precedence over quiet NaNs.
3718353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3719353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext
3720353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3721abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1')
3722353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3723abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
3724353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.flags[InvalidOperation] = 0
3725353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> print c.flags[InvalidOperation]
3726353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        0
3727353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3728abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('NaN')
3729353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> print c.flags[InvalidOperation]
3730353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        1
3731353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.flags[InvalidOperation] = 0
3732353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> print c.flags[InvalidOperation]
3733353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        0
3734353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3735abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('NaN')
3736353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> print c.flags[InvalidOperation]
3737353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        1
3738353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3739353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.compare_signal(b, context=self)
3740353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3741353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_total(self, a, b):
3742353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares two operands using their abstract representation.
3743353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3744353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        This is not like the standard compare, which use their numerical
3745353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        value. Note that a total ordering is defined for all possible abstract
3746353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        representations.
3747353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3748353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3749abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1')
3750353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('-127'),  Decimal('12'))
3751abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1')
3752353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3753abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1')
3754353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3755abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
3756353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('12.300'))
3757abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
3758353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('NaN'))
3759abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1')
3760353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3761353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.compare_total(b)
3762353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3763353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def compare_total_mag(self, a, b):
3764353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares two operands using their abstract representation ignoring sign.
3765353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3766353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Like compare_total, but with operand's sign ignored and assumed to be 0.
3767353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3768353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.compare_total_mag(b)
3769353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3770353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_abs(self, a):
3771353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy of the operand with the sign set to 0.
3772353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3773353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_abs(Decimal('2.1'))
3774abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.1')
3775353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_abs(Decimal('-100'))
3776abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('100')
3777353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3778353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.copy_abs()
3779353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3780353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_decimal(self, a):
3781353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy of the decimal objet.
3782353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3783353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3784abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.1')
3785353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3786abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1.00')
3787353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
37886c398da0e79cbd68ec4625f00f37a8f2a0a26e5cFacundo Batista        return Decimal(a)
3789353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3790353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_negate(self, a):
3791353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a copy of the operand with the sign inverted.
3792353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3793353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_negate(Decimal('101.5'))
3794abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-101.5')
3795353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3796abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('101.5')
3797353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3798353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.copy_negate()
3799353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3800353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def copy_sign(self, a, b):
3801353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Copies the second operand's sign to the first one.
3802353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3803353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        In detail, it returns a copy of the first operand with the sign
3804353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        equal to the sign of the second operand.
3805353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3806353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3807abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.50')
3808353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3809abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.50')
3810353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3811abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1.50')
3812353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3813abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1.50')
3814353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3815353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.copy_sign(b)
3816353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
38177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def divide(self, a, b):
38187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Decimal division in a specified context.
38197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
38209ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
3821abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.333333333')
38229ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
3823abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.666666667')
38249ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
3825abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.5')
38269ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
3827abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.1')
38289ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
3829abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
38309ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
3831abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('4.00')
38329ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
3833abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.20')
38349ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
3835abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('10')
38369ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
3837abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1000')
38389ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
3839abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.20E+6')
38407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
38417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__div__(b, context=self)
38427c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
38437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def divide_int(self, a, b):
38447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Divides two numbers and returns the integer part of the result.
38457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
38469ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
3847abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
38489ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
3849abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('3')
38509ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
3851abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('3')
38527c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
38537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__floordiv__(b, context=self)
38547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
38557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def divmod(self, a, b):
38567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__divmod__(b, context=self)
38577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
3858353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def exp(self, a):
3859353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns e ** a.
3860353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3861353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
3862353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
3863353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
3864353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('-Infinity'))
3865abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
3866353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('-1'))
3867abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.367879441')
3868353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('0'))
3869abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
3870353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('1'))
3871abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.71828183')
3872353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('0.693147181'))
3873abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.00000000')
3874353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.exp(Decimal('+Infinity'))
3875abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('Infinity')
3876353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3877353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.exp(context=self)
3878353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3879353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def fma(self, a, b, c):
3880353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a multiplied by b, plus c.
3881353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3882353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The first two operands are multiplied together, using multiply,
3883353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        the third operand is then added to the result of that
3884353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        multiplication, using add, all with only one final rounding.
3885353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3886353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3887abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('22')
3888353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3889abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-8')
3890353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3891abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.38435736E+12')
3892353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3893353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.fma(b, c, context=self)
3894353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3895353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_canonical(self, a):
38961a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is canonical; otherwise return False.
38971a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista
38981a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        Currently, the encoding of a Decimal instance is always
38991a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        canonical, so this method returns True for any Decimal.
3900353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3901353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_canonical(Decimal('2.50'))
39021a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3903353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
39041a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        return a.is_canonical()
3905353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3906353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_finite(self, a):
39071a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is finite; otherwise return False.
3908353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
39091a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        A Decimal instance is considered finite if it is neither
39101a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        infinite nor a NaN.
3911353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3912353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('2.50'))
39131a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3914353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('-0.3'))
39151a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3916353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('0'))
39171a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3918353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('Inf'))
39191a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3920353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_finite(Decimal('NaN'))
39211a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3922353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3923353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_finite()
3924353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3925353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_infinite(self, a):
39261a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is infinite; otherwise return False.
3927353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3928353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_infinite(Decimal('2.50'))
39291a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3930353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_infinite(Decimal('-Inf'))
39311a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3932353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_infinite(Decimal('NaN'))
39331a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3934353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3935353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_infinite()
3936353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3937353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_nan(self, a):
39381a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is a qNaN or sNaN;
39391a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        otherwise return False.
3940353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3941353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_nan(Decimal('2.50'))
39421a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3943353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_nan(Decimal('NaN'))
39441a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3945353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_nan(Decimal('-sNaN'))
39461a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3947353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3948353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_nan()
3949353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3950353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_normal(self, a):
39511a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is a normal number;
39521a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        otherwise return False.
3953353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3954353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
3955353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
3956353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
3957353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('2.50'))
39581a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3959353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('0.1E-999'))
39601a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3961353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('0.00'))
39621a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3963353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('-Inf'))
39641a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3965353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_normal(Decimal('NaN'))
39661a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3967353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3968353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_normal(context=self)
3969353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3970353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_qnan(self, a):
39711a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is a quiet NaN; otherwise return False.
3972353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3973353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_qnan(Decimal('2.50'))
39741a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3975353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_qnan(Decimal('NaN'))
39761a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3977353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_qnan(Decimal('sNaN'))
39781a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3979353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3980353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_qnan()
3981353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3982353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_signed(self, a):
39831a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is negative; otherwise return False.
3984353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3985353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_signed(Decimal('2.50'))
39861a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
3987353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_signed(Decimal('-12'))
39881a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3989353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_signed(Decimal('-0'))
39901a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
3991353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
3992353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_signed()
3993353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3994353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_snan(self, a):
39951a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is a signaling NaN;
39961a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        otherwise return False.
3997353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
3998353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_snan(Decimal('2.50'))
39991a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4000353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_snan(Decimal('NaN'))
40011a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4002353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_snan(Decimal('sNaN'))
40031a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
4004353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4005353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_snan()
4006353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4007353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_subnormal(self, a):
40081a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is subnormal; otherwise return False.
4009353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4010353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4011353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4012353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4013353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('2.50'))
40141a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4015353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('0.1E-999'))
40161a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
4017353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('0.00'))
40181a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4019353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('-Inf'))
40201a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4021353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.is_subnormal(Decimal('NaN'))
40221a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4023353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4024353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_subnormal(context=self)
4025353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4026353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def is_zero(self, a):
40271a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        """Return True if the operand is a zero; otherwise return False.
4028353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4029353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_zero(Decimal('0'))
40301a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
4031353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_zero(Decimal('2.50'))
40321a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        False
4033353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.is_zero(Decimal('-0E+2'))
40341a191df14dc2f37933ef32f553fcaa7a5ac77cf7Facundo Batista        True
4035353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4036353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.is_zero()
4037353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4038353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def ln(self, a):
4039353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the natural (base e) logarithm of the operand.
4040353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4041353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4042353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4043353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4044353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('0'))
4045abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-Infinity')
4046353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('1.000'))
4047abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4048353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('2.71828183'))
4049abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.00000000')
4050353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('10'))
4051abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.30258509')
4052353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.ln(Decimal('+Infinity'))
4053abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('Infinity')
4054353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4055353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.ln(context=self)
4056353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def log10(self, a):
4058353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the base 10 logarithm of the operand.
4059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4060353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4061353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4062353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4063353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('0'))
4064abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-Infinity')
4065353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('0.001'))
4066abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-3')
4067353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('1.000'))
4068abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4069353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('2'))
4070abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.301029996')
4071353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('10'))
4072abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('70'))
4074abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.84509804')
4075353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.log10(Decimal('+Infinity'))
4076abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('Infinity')
4077353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4078353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.log10(context=self)
4079353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4080353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logb(self, a):
4081353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """ Returns the exponent of the magnitude of the operand's MSD.
4082353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4083353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result is the integer which is the exponent of the magnitude
4084353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        of the most significant digit of the operand (as though the
4085353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        operand were truncated to a single digit while maintaining the
4086353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        value of that digit and without limiting the resulting exponent).
4087353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4088353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logb(Decimal('250'))
4089abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2')
4090353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logb(Decimal('2.50'))
4091abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4092353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logb(Decimal('0.03'))
4093abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-2')
4094353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logb(Decimal('0'))
4095abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-Infinity')
4096353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4097353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logb(context=self)
4098353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4099353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_and(self, a, b):
4100353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies the logical operation 'and' between each operand's digits.
4101353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4102353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The operands must be both logical numbers.
4103353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4104353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4105abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4106353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4107abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4108353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4109abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4110353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4111abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4112353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4113abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1000')
4114353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4115abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('10')
4116353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4117353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logical_and(b, context=self)
4118353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4119353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_invert(self, a):
4120353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Invert all the digits in the operand.
4121353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4122353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The operand must be a logical number.
4123353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4124353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_invert(Decimal('0'))
4125abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('111111111')
4126353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_invert(Decimal('1'))
4127abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('111111110')
4128353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_invert(Decimal('111111111'))
4129abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4130353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_invert(Decimal('101010101'))
4131abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('10101010')
4132353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4133353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logical_invert(context=self)
4134353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4135353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_or(self, a, b):
4136353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies the logical operation 'or' between each operand's digits.
4137353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4138353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The operands must be both logical numbers.
4139353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4140353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4141abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4142353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4143abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4144353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4145abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4146353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4147abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4148353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4149abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1110')
4150353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4151abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1110')
4152353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4153353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logical_or(b, context=self)
4154353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4155353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def logical_xor(self, a, b):
4156353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Applies the logical operation 'xor' between each operand's digits.
4157353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4158353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The operands must be both logical numbers.
4159353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4160353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4161abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4162353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4163abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4164353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4165abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4166353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4167abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4168353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4169abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('110')
4170353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4171abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1101')
4172353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4173353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.logical_xor(b, context=self)
4174353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
41757c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def max(self, a,b):
41767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """max compares two values numerically and returns the maximum.
41777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If either operand is a NaN then the general rules apply.
4179c8acc882a92c1fe5df95ae73b7b8004737ed9222Andrew M. Kuchling        Otherwise, the operands are compared as though by the compare
418059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operation.  If they are numerically equal then the left-hand operand
418159c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        is chosen as the result.  Otherwise the maximum (closer to positive
41827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        infinity) of the two operands is chosen as the result.
41837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
41849ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
4185abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('3')
41869ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
4187abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('3')
41889ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
4189abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4190d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4191abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('7')
41927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
41937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.max(b, context=self)
41947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4195353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def max_mag(self, a, b):
4196353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values numerically with their sign ignored."""
4197353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.max_mag(b, context=self)
4198353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
41997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def min(self, a,b):
42007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """min compares two values numerically and returns the minimum.
42017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
42027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If either operand is a NaN then the general rules apply.
4203c8acc882a92c1fe5df95ae73b7b8004737ed9222Andrew M. Kuchling        Otherwise, the operands are compared as though by the compare
420459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operation.  If they are numerically equal then the left-hand operand
420559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        is chosen as the result.  Otherwise the minimum (closer to negative
42067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        infinity) of the two operands is chosen as the result.
42077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
42089ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
4209abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2')
42109ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
4211abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-10')
42129ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
4213abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.0')
4214d6c700a320eacd6f04cbcc60996b84e765766890Raymond Hettinger        >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4215abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('7')
42167c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
42177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.min(b, context=self)
42187c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4219353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def min_mag(self, a, b):
4220353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Compares the values numerically with their sign ignored."""
4221353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.min_mag(b, context=self)
4222353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
42237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def minus(self, a):
42247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Minus corresponds to unary prefix minus in Python.
42257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
42267c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The operation is evaluated using the same rules as subtract; the
42277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        operation minus(a) is calculated as subtract('0', a) where the '0'
42287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        has the same exponent as the operand.
42297c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
42309ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.minus(Decimal('1.3'))
4231abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1.3')
42329ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.minus(Decimal('-1.3'))
4233abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.3')
42347c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
42357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__neg__(context=self)
42367c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
42377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def multiply(self, a, b):
42387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """multiply multiplies two operands.
42397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4240cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis        If either operand is a special value then the general rules apply.
4241cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis        Otherwise, the operands are multiplied together ('long multiplication'),
4242cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis        resulting in a number which may be as long as the sum of the lengths
4243cfe3128cd58c4a59d236527184b40352ae35e44aMartin v. Löwis        of the two operands.
42447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
42459ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
4246abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('3.60')
42479ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
4248abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('21')
42499ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
4250abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.72')
42519ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
4252abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0.0')
42539ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
4254abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('4.28135971E+11')
42557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
42567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__mul__(b, context=self)
42577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4258353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_minus(self, a):
4259353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the largest representable number smaller than a.
4260353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4261353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4262353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4263353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4264353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.next_minus(Decimal('1'))
4265abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.999999999')
4266353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_minus(Decimal('1E-1007'))
4267abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0E-1007')
4268353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4269abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1.00000004')
4270353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_minus(Decimal('Infinity'))
4271abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('9.99999999E+999')
4272353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4273353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.next_minus(context=self)
4274353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4275353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_plus(self, a):
4276353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the smallest representable number larger than a.
4277353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4278353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4279353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4280353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4281353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.next_plus(Decimal('1'))
4282abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.00000001')
4283353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_plus(Decimal('-1E-1007'))
4284abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0E-1007')
4285353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4286abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1.00000002')
4287353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_plus(Decimal('-Infinity'))
4288abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-9.99999999E+999')
4289353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4290353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.next_plus(context=self)
4291353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4292353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def next_toward(self, a, b):
4293353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the number closest to a, in direction towards b.
4294353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4295353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result is the closest representable number from the first
4296353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        operand (but not the first operand) that is in the direction
4297353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        towards the second operand, unless the operands have the same
4298353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        value.
4299353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4300353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4301353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4302353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4303353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('1'), Decimal('2'))
4304abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.00000001')
4305353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4306abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0E-1007')
4307353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4308abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1.00000002')
4309353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('1'), Decimal('0'))
4310abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.999999999')
4311353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4312abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0E-1007')
4313353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4314abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1.00000004')
4315353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4316abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0.00')
4317353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4318353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.next_toward(b, context=self)
4319353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
43207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def normalize(self, a):
4321e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger        """normalize reduces an operand to its simplest form.
43227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
43237c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Essentially a plus operation with all trailing zeros removed from the
43247c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        result.
43257c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
43269ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('2.1'))
4327abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.1')
43289ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('-2.0'))
4329abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-2')
43309ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('1.200'))
4331abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.2')
43329ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('-120'))
4333abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1.2E+2')
43349ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('120.00'))
4335abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.2E+2')
43369ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.normalize(Decimal('0.00'))
4337abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
43387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
43397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.normalize(context=self)
43407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4341353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def number_class(self, a):
4342353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns an indication of the class of the operand.
4343353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4344353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The class is one of the following strings:
4345353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -sNaN
4346353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -NaN
4347353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Infinity
4348353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Normal
4349353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Subnormal
4350353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          -Zero
4351353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Zero
4352353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Subnormal
4353353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Normal
4354353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista          +Infinity
4355353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4356353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = Context(ExtendedContext)
4357353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4358353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4359353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('Infinity'))
4360353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Infinity'
4361353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('1E-10'))
4362353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Normal'
4363353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('2.50'))
4364353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Normal'
4365353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('0.1E-999'))
4366353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Subnormal'
4367353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('0'))
4368353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '+Zero'
4369353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-0'))
4370353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Zero'
4371353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-0.1E-999'))
4372353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Subnormal'
4373353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-1E-10'))
4374353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Normal'
4375353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-2.50'))
4376353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Normal'
4377353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-Infinity'))
4378353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '-Infinity'
4379353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('NaN'))
4380353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        'NaN'
4381353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('-NaN'))
4382353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        'NaN'
4383353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.number_class(Decimal('sNaN'))
4384353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        'sNaN'
4385353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4386353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.number_class(context=self)
4387353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
43887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def plus(self, a):
43897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Plus corresponds to unary prefix plus in Python.
43907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
43917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The operation is evaluated using the same rules as add; the
43927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        operation plus(a) is calculated as add('0', a) where the '0'
43937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        has the same exponent as the operand.
43947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
43959ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.plus(Decimal('1.3'))
4396abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.3')
43979ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.plus(Decimal('-1.3'))
4398abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1.3')
43997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
44007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__pos__(context=self)
44017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def power(self, a, b, modulo=None):
44037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Raises a to the power of b, to modulo if given.
44047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4405353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        With two arguments, compute a**b.  If a is negative then b
4406353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        must be integral.  The result will be inexact unless b is
4407353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        integral and the result is finite and can be expressed exactly
4408353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        in 'precision' digits.
4409353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4410353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        With three arguments, compute (a**b) % modulo.  For the
4411353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        three argument form, the following restrictions on the
4412353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        arguments hold:
4413353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4414353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - all three arguments must be integral
4415353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - b must be nonnegative
4416353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - at least one of a or b must be nonzero
4417353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista         - modulo must be nonzero and have at most 'precision' digits
4418353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4419353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The result of pow(a, b, modulo) is identical to the result
4420353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        that would be obtained by computing (a**b) % modulo with
4421353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        unbounded precision, but is computed more efficiently.  It is
4422353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        always exact.
4423353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4424353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c = ExtendedContext.copy()
4425353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emin = -999
4426353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.Emax = 999
4427353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('2'), Decimal('3'))
4428abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('8')
4429353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-2'), Decimal('3'))
4430abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-8')
4431353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('2'), Decimal('-3'))
4432abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.125')
4433353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('1.7'), Decimal('8'))
4434abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('69.7575744')
4435353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('10'), Decimal('0.301029996'))
4436abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.00000000')
4437353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('Infinity'), Decimal('-1'))
4438abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4439353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('Infinity'), Decimal('0'))
4440abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4441353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('Infinity'), Decimal('1'))
4442abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('Infinity')
4443353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-Infinity'), Decimal('-1'))
4444abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0')
4445353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-Infinity'), Decimal('0'))
4446abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4447353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-Infinity'), Decimal('1'))
4448abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-Infinity')
4449353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-Infinity'), Decimal('2'))
4450abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('Infinity')
4451353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('0'), Decimal('0'))
4452abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('NaN')
4453353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4454353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4455abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('11')
4456353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4457abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-11')
4458353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4459abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
4460353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4461abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('11')
4462353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4463abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('11729830')
4464353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4465abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0')
4466353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4467abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
44687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
44697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__pow__(b, modulo, context=self)
44707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def quantize(self, a, b):
447259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
44737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The coefficient of the result is derived from that of the left-hand
447559c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operand.  It may be rounded using the current rounding setting (if the
44767c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        exponent is being increased), multiplied by a positive power of ten (if
44777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        the exponent is being decreased), or is unchanged (if the exponent is
44787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        already equal to that of the right-hand operand).
44797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Unlike other operations, if the length of the coefficient after the
44817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        quantize operation would be greater than precision then an Invalid
448259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        operation condition is raised.  This guarantees that, unless there is
448359c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        an error condition, the exponent of the result of a quantize is always
44847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        equal to that of the right-hand operand.
44857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        Also unlike other operations, quantize will never raise Underflow, even
44877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if the result is subnormal and inexact.
44887c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
44899ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
4490abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.170')
44919ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
4492abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.17')
44939ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
4494abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.2')
44959ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
4496abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2')
44979ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
4498abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0E+1')
44999ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
4500abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-Infinity')
45019ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
4502abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('NaN')
45039ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
4504abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0')
45059ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
4506abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0E+5')
45079ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
4508abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('NaN')
45099ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
4510abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('NaN')
45119ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
4512abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('217.0')
45139ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
4514abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('217')
45159ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
4516abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.2E+2')
45179ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
4518abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2E+2')
45197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
45207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.quantize(b, context=self)
45217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4522353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def radix(self):
4523353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Just returns 10, as this is Decimal, :)
4524353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4525353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.radix()
4526abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('10')
4527353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4528353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return Decimal(10)
4529353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
45307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def remainder(self, a, b):
45317c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns the remainder from integer division.
45327c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The result is the residue of the dividend after the operation of
453459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        calculating integer division as described for divide-integer, rounded
45350d4c06e06e5ee1f3bb1fa8068114bd700d74864aNeal Norwitz        to precision digits if necessary.  The sign of the result, if
453659c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        non-zero, is the same as that of the original dividend.
45377c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45387c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        This operation will fail under the same conditions as integer division
45397c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        (that is, if integer division on the same two operands would fail, the
45407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        remainder cannot be calculated).
45417c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45429ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
4543abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.1')
45449ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
4545abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
45469ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
4547abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1')
45489ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
4549abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.2')
45509ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
4551abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.1')
45529ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
4553abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.0')
45547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
45557c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__mod__(b, context=self)
45567c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def remainder_near(self, a, b):
45587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns to be "a - b * n", where n is the integer nearest the exact
45597c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        value of "x / b" (if two integers are equally near then the even one
456059c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        is chosen).  If the result is equal to 0 then its sign will be the
45617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        sign of a.
45627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        This operation will fail under the same conditions as integer division
45647c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        (that is, if integer division on the same two operands would fail, the
45657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        remainder cannot be calculated).
45667c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
45679ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
4568abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0.9')
45699ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
4570abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-2')
45719ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
4572abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
45739ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
4574abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-1')
45759ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
4576abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.2')
45779ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
4578abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.1')
45799ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
4580abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0.3')
45817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
45827c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.remainder_near(b, context=self)
45837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4584353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def rotate(self, a, b):
4585353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a rotated copy of a, b times.
4586353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4587353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The coefficient of the result is a rotated copy of the digits in
4588353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        the coefficient of the first operand.  The number of places of
4589353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        rotation is taken from the absolute value of the second operand,
4590353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        with the rotation being to the left if the second operand is
4591353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        positive or to the right otherwise.
4592353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4593353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4594abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('400000003')
4595353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4596abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('12')
4597353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4598abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('891234567')
4599353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4600abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('123456789')
4601353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4602abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('345678912')
4603353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4604353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.rotate(b, context=self)
4605353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
46067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def same_quantum(self, a, b):
46077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Returns True if the two operands have the same exponent.
46087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The result is never affected by either the sign or the coefficient of
46107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        either operand.
46117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46129ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
46137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        False
46149ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
46157c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        True
46169ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
46177c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        False
46189ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
46197c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        True
46207c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
46217c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.same_quantum(b)
46227c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4623353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def scaleb (self, a, b):
4624353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns the first operand after adding the second value its exp.
4625353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4626353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4627abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.0750')
4628353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4629abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('7.50')
4630353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4631abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('7.50E+3')
4632353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4633353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.scaleb (b, context=self)
4634353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4635353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def shift(self, a, b):
4636353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Returns a shifted copy of a, b times.
4637353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4638353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        The coefficient of the result is a shifted copy of the digits
4639353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        in the coefficient of the first operand.  The number of places
4640353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        to shift is taken from the absolute value of the second operand,
4641353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        with the shift being to the left if the second operand is
4642353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        positive or to the right otherwise.  Digits shifted into the
4643353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        coefficient are zeros.
4644353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4645353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4646abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('400000000')
4647353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4648abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
4649353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4650abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1234567')
4651353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4652abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('123456789')
4653353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4654abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('345678900')
4655353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4656353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.shift(b, context=self)
4657353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
46587c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def sqrt(self, a):
465959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        """Square root of a non-negative number to context precision.
46607c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46617c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        If the result must be inexact, it is rounded using the round-half-even
46627c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        algorithm.
46637c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46649ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('0'))
4665abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0')
46669ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('-0'))
4667abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0')
46689ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('0.39'))
4669abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.624499800')
46709ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('100'))
4671abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('10')
46729ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('1'))
4673abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1')
46749ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('1.0'))
4675abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.0')
46769ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('1.00'))
4677abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.0')
46789ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('7'))
4679abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2.64575131')
46809ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.sqrt(Decimal('10'))
4681abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('3.16227766')
46829ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.prec
46836ea484582238a65d44a76e3a831e3ba7c77a1a25Raymond Hettinger        9
46847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
46857c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.sqrt(context=self)
46867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def subtract(self, a, b):
4688f33d01d304c349a7f555779c7c99930f1203adb7Georg Brandl        """Return the difference between the two operands.
46897c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46909ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
4691abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.23')
46929ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
4693abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('0.00')
46949ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond Hettinger        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
4695abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-0.77')
46967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
46977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__sub__(b, context=self)
46987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
46997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def to_eng_string(self, a):
47007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Converts a number to a string, using scientific notation.
47017c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The operation is not affected by the context.
47037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
47047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.to_eng_string(context=self)
47057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def to_sci_string(self, a):
47077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Converts a number to a string, using scientific notation.
47087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        The operation is not affected by the context.
47107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
47117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return a.__str__(context=self)
47127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4713353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def to_integral_exact(self, a):
4714353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """Rounds to an integer.
4715353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4716353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        When the operand has a negative exponent, the result is the same
4717353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        as using the quantize() operation using the given operand as the
4718353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4719353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        of the operand as the precision setting; Inexact and Rounded flags
4720353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        are allowed in this operation.  The rounding mode is taken from the
4721353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        context.
4722353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4723353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4724abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2')
4725353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('100'))
4726abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('100')
4727353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4728abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('100')
4729353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4730abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('102')
4731353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4732abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-102')
4733353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4734abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.0E+6')
4735353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4736abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('7.89E+77')
4737353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4738abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-Infinity')
4739353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        """
4740353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.to_integral_exact(context=self)
4741353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4742353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    def to_integral_value(self, a):
47437c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """Rounds to an integer.
47447c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47457c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        When the operand has a negative exponent, the result is the same
47467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        as using the quantize() operation using the given operand as the
47477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        left-hand-operand, 1E+0 as the right-hand-operand, and the precision
47487c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        of the operand as the precision setting, except that no flags will
474959c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista        be set.  The rounding mode is taken from the context.
47507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4751353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('2.1'))
4752abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('2')
4753353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('100'))
4754abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('100')
4755353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('100.0'))
4756abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('100')
4757353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('101.5'))
4758abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('102')
4759353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
4760abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-102')
4761353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
4762abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('1.0E+6')
4763353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
4764abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('7.89E+77')
4765353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
4766abe32371878dcaea31c835e10144fdaa2eca6492Raymond Hettinger        Decimal('-Infinity')
47677c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        """
4768353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        return a.to_integral_value(context=self)
4769353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4770353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # the method name changed, but we provide also the old one, for compatibility
4771353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    to_integral = to_integral_value
47727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerclass _WorkRep(object):
47747c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __slots__ = ('sign','int','exp')
477517931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger    # sign: 0 or 1
4776636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    # int:  int or long
47777c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    # exp:  None, int, or string
47787c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47797c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __init__(self, value=None):
47807c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        if value is None:
47817c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.sign = None
4782636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger            self.int = 0
47837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.exp = None
478417931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        elif isinstance(value, Decimal):
478517931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            self.sign = value._sign
478672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista            self.int = int(value._int)
47877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.exp = value._exp
478817931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger        else:
478917931de110ac84e6b0eb88d77a95798f8670765aRaymond Hettinger            # assert isinstance(value, tuple)
47907c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.sign = value[0]
47917c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.int = value[1]
47927c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger            self.exp = value[2]
47937c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    def __repr__(self):
47957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
47967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    __str__ = __repr__
47987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
47997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
48007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4801e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batistadef _normalize(op1, op2, prec = 0):
48027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """Normalizes op1, op2 to have the same exp and length of coefficient.
48037c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
48047c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    Done during addition.
48057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    """
4806353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if op1.exp < op2.exp:
48077c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        tmp = op2
48087c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        other = op1
48097c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    else:
48107c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        tmp = op1
48117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        other = op2
48127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4813353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4814353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Then adding 10**exp to tmp has the same effect (after rounding)
4815353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # as adding any positive quantity smaller than 10**exp; similarly
4816353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # for subtraction.  So if other is smaller than 10**exp we replace
4817353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # it with 10**exp.  This avoids tmp.exp - other.exp getting too large.
4818e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista    tmp_len = len(str(tmp.int))
4819e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista    other_len = len(str(other.int))
4820e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista    exp = tmp.exp + min(-1, tmp_len - prec - 2)
4821e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista    if other_len + other.exp - 1 < exp:
4822e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        other.int = 1
4823e64acfad3dd13809943eecf50f11c40c510dedbeFacundo Batista        other.exp = exp
4824636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
4825353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    tmp.int *= 10 ** (tmp.exp - other.exp)
4826353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    tmp.exp = other.exp
48277c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    return op1, op2
48287c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
4829353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4830353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4831353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# This function from Tim Peters was taken from here:
4832353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4833353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# The correction being in the function definition is for speed, and
4834353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# the whole function is not resolved with math.log because of avoiding
4835353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista# the use of floats.
4836353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _nbits(n, correction = {
4837353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '0': 4, '1': 3, '2': 2, '3': 2,
4838353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '4': 1, '5': 1, '6': 1, '7': 1,
4839353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '8': 0, '9': 0, 'a': 0, 'b': 0,
4840353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4841353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Number of bits in binary representation of the positive integer n,
4842353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    or 0 if n == 0.
4843353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
4844353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if n < 0:
4845353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        raise ValueError("The argument to _nbits should be nonnegative.")
4846353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    hex_n = "%x" % n
4847353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return 4*len(hex_n) - correction[hex_n[0]]
4848353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4849353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _sqrt_nearest(n, a):
4850353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Closest integer to the square root of the positive integer n.  a is
4851353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    an initial approximation to the square root.  Any positive integer
4852353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    will do for a, but the closer a is to the square root of n the
4853353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    faster convergence will be.
4854353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4855353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
4856353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if n <= 0 or a <= 0:
4857353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4858353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4859353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    b=0
4860353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    while a != b:
4861353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        b, a = a, a--n//a>>1
4862353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return a
4863353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4864353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _rshift_nearest(x, shift):
4865353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given an integer x and a nonnegative integer shift, return closest
4866353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    integer to x / 2**shift; use round-to-even in case of a tie.
4867353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4868353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
4869353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    b, q = 1L << shift, x >> shift
4870353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return q + (2*(x & (b-1)) + (q&1) > b)
4871353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4872353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _div_nearest(a, b):
4873353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Closest integer to a/b, a and b positive integers; rounds to even
4874353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    in the case of a tie.
4875353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4876353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
4877353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    q, r = divmod(a, b)
4878353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return q + (2*r + (q&1) > b)
4879353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4880353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _ilog(x, M, L = 8):
4881353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Integer approximation to M*log(x/M), with absolute error boundable
4882353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    in terms only of x/M.
4883353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4884353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    Given positive integers x and M, return an integer approximation to
4885353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    M * log(x/M).  For L = 8 and 0.1 <= x/M <= 10 the difference
4886353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    between the approximation and the exact result is at most 22.  For
4887353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15.  In
4888353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    both cases these are upper bounds on the error; it will usually be
4889353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    much smaller."""
4890353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4891353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # The basic algorithm is the following: let log1p be the function
4892353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # log1p(x) = log(1+x).  Then log(x/M) = log1p((x-M)/M).  We use
4893353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # the reduction
4894353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4895353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #    log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4896353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4897353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # repeatedly until the argument to log1p is small (< 2**-L in
4898353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # absolute value).  For small y we can use the Taylor series
4899353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # expansion
4900353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4901353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #    log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4902353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
4903353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # truncating at T such that y**T is small enough.  The whole
4904353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # computation is carried out in a form of fixed-point arithmetic,
4905353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # with a real number z being represented by an integer
4906353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # approximation to z*M.  To avoid loss of precision, the y below
4907353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # is actually an integer approximation to 2**R*y*M, where R is the
4908353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # number of reductions performed so far.
4909353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4910353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    y = x-M
4911353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # argument reduction; R = number of reductions performed
4912353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    R = 0
4913353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    while (R <= L and long(abs(y)) << L-R >= M or
4914353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista           R > L and abs(y) >> R-L >= M):
4915353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        y = _div_nearest(long(M*y) << 1,
4916353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista                         M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4917353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        R += 1
4918353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4919353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Taylor series with T terms
4920353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    T = -int(-10*len(str(M))//(3*L))
4921353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    yshift = _rshift_nearest(y, R)
4922353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    w = _div_nearest(M, T)
4923353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    for k in xrange(T-1, 0, -1):
4924353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4925353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4926353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return _div_nearest(w*y, M)
4927353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4928353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _dlog10(c, e, p):
4929353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given integers c, e and p with c > 0, p >= 0, compute an integer
4930353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    approximation to 10**p * log10(c*10**e), with an absolute error of
4931353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    at most 1.  Assumes that c*10**e is not exactly 1."""
4932353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4933353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # increase precision by 2; compensate for this by dividing
4934353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # final result by 100
4935353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    p += 2
4936353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4937353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # write c*10**e as d*10**f with either:
4938353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #   f >= 0 and 1 <= d <= 10, or
4939353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #   f <= 0 and 0.1 <= d <= 1.
4940353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Thus for c*10**e close to 1, f = 0
4941353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    l = len(str(c))
4942353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    f = e+l - (e+l >= 1)
4943353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4944353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if p > 0:
4945353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        M = 10**p
4946353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        k = e+p-f
4947353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if k >= 0:
4948353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c *= 10**k
4949353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
4950353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = _div_nearest(c, 10**-k)
4951353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4952353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = _ilog(c, M) # error < 5 + 22 = 27
4953be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        log_10 = _log10_digits(p) # error < 1
4954353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = _div_nearest(log_d*M, log_10)
4955353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_tenpower = f*M # exact
4956353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
4957353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = 0  # error < 2.31
4958353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4959353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4960353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return _div_nearest(log_tenpower+log_d, 100)
4961353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4962353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _dlog(c, e, p):
4963353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given integers c, e and p with c > 0, compute an integer
4964353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    approximation to 10**p * log(c*10**e), with an absolute error of
4965353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    at most 1.  Assumes that c*10**e is not exactly 1."""
4966353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4967353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Increase precision by 2. The precision increase is compensated
4968353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # for at the end with a division by 100.
4969353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    p += 2
4970353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4971353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4972353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # or f <= 0 and 0.1 <= d <= 1.  Then we can compute 10**p * log(c*10**e)
4973353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # as 10**p * log(d) + 10**p*f * log(10).
4974353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    l = len(str(c))
4975353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    f = e+l - (e+l >= 1)
4976353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4977353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # compute approximation to 10**p*log(d), with error < 27
4978353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if p > 0:
4979353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        k = e+p-f
4980353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if k >= 0:
4981353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c *= 10**k
4982353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
4983353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            c = _div_nearest(c, 10**-k)  # error of <= 0.5 in c
4984353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4985353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # _ilog magnifies existing error in c by a factor of at most 10
4986353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4987353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
4988353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # p <= 0: just approximate the whole thing by 0; error < 2.31
4989353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        log_d = 0
4990353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
4991be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    # compute approximation to f*10**p*log(10), with error < 11.
4992353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if f:
4993be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        extra = len(str(abs(f)))-1
4994be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        if p + extra >= 0:
4995be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4996be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4997be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
4998353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
4999353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            f_log_ten = 0
5000353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
5001353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        f_log_ten = 0
5002353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5003be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
5004353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return _div_nearest(f_log_ten + log_d, 100)
5005353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5006be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batistaclass _Log10Memoize(object):
5007be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    """Class to compute, store, and allow retrieval of, digits of the
5008be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    constant log(10) = 2.302585....  This constant is needed by
5009be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5010be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    def __init__(self):
5011be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        self.digits = "23025850929940456840179914546843642076011014886"
5012be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista
5013be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    def getdigits(self, p):
5014be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        """Given an integer p >= 0, return floor(10**p)*log(10).
5015be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista
5016be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        For example, self.getdigits(3) returns 2302.
5017be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        """
5018be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        # digits are stored as a string, for quick conversion to
5019be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        # integer in the case that we've already computed enough
5020be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        # digits; the stored digits should always be correct
5021be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        # (truncated, not rounded to nearest).
5022be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        if p < 0:
5023be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            raise ValueError("p should be nonnegative")
5024be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista
5025be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        if p >= len(self.digits):
5026be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # compute p+3, p+6, p+9, ... digits; continue until at
5027be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # least one of the extra digits is nonzero
5028be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            extra = 3
5029be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            while True:
5030be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                # compute p+extra digits, correct to within 1ulp
5031be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                M = 10**(p+extra+2)
5032be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                digits = str(_div_nearest(_ilog(10*M, M), 100))
5033be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                if digits[-extra:] != '0'*extra:
5034be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                    break
5035be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista                extra += 3
5036be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # keep all reliable digits so far; remove trailing zeros
5037be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            # and next nonzero digit
5038be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista            self.digits = digits.rstrip('0')[:-1]
5039be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista        return int(self.digits[:p+1])
5040be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista
5041be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista_log10_digits = _Log10Memoize().getdigits
5042be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista
5043353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _iexp(x, M, L=8):
5044353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given integers x and M, M > 0, such that x/M is small in absolute
5045353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    value, compute an integer approximation to M*exp(x/M).  For 0 <=
5046353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5047353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    is usually much smaller)."""
5048353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5049353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Algorithm: to compute exp(z) for a real number z, first divide z
5050353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # by a suitable power R of 2 so that |z/2**R| < 2**-L.  Then
5051353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5052353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # series
5053353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
5054353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #     expm1(x) = x + x**2/2! + x**3/3! + ...
5055353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
5056353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Now use the identity
5057353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
5058353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #     expm1(2x) = expm1(x)*(expm1(x)+2)
5059353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    #
5060353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # R times to compute the sequence expm1(z/2**R),
5061353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5062353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5063353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Find R such that x/2**R/M <= 2**-L
5064353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    R = _nbits((long(x)<<L)//M)
5065353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5066353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Taylor series.  (2**L)**T > M
5067353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    T = -int(-10*len(str(M))//(3*L))
5068353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    y = _div_nearest(x, T)
5069353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    Mshift = long(M)<<R
5070353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    for i in xrange(T-1, 0, -1):
5071353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        y = _div_nearest(x*(Mshift + y), Mshift * i)
5072353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5073353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Expansion
5074353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    for k in xrange(R-1, -1, -1):
5075353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        Mshift = long(M)<<(k+2)
5076353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        y = _div_nearest(y*(y+Mshift), Mshift)
5077353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5078353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return M+y
5079353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5080353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _dexp(c, e, p):
5081353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Compute an approximation to exp(c*10**e), with p decimal places of
5082353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    precision.
5083353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5084be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    Returns integers d, f such that:
5085353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5086353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista      10**(p-1) <= d <= 10**p, and
5087353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista      (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5088353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5089353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    In other words, d*10**f is an approximation to exp(c*10**e) with p
5090353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    digits of precision, and with an error in d of at most 1.  This is
5091353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    almost, but not quite, the same as the error being < 1ulp: when d
5092353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    = 10**(p-1) the error could be up to 10 ulp."""
5093353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5094353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5095353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    p += 2
5096353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5097be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    # compute log(10) with extra precision = adjusted exponent of c*10**e
5098353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    extra = max(0, e + len(str(c)) - 1)
5099353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    q = p + extra
5100353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5101be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
5102353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # rounding down
5103353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    shift = e+q
5104353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if shift >= 0:
5105353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        cshift = c*10**shift
5106353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
5107353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        cshift = c//10**-shift
5108be6c7ba72ad2bc3087a7df20871387b11756e140Facundo Batista    quot, rem = divmod(cshift, _log10_digits(q))
5109353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5110353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # reduce remainder back to original precision
5111353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    rem = _div_nearest(rem, 10**extra)
5112353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5113353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # error in result of _iexp < 120;  error after division < 0.62
5114353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5115353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5116353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _dpower(xc, xe, yc, ye, p):
5117353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5118353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    y = yc*10**ye, compute x**y.  Returns a pair of integers (c, e) such that:
5119353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5120353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista      10**(p-1) <= c <= 10**p, and
5121353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista      (c-1)*10**e < x**y < (c+1)*10**e
5122353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5123353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    in other words, c*10**e is an approximation to x**y with p digits
5124353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    of precision, and with an error in c of at most 1.  (This is
5125353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    almost, but not quite, the same as the error being < 1ulp: when c
5126353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    == 10**(p-1) we can only guarantee error < 10ulp.)
5127353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5128353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    We assume that: x is positive and not equal to 1, and y is nonzero.
5129353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """
5130353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5131353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # Find b such that 10**(b-1) <= |y| <= 10**b
5132353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    b = len(str(abs(yc))) + ye
5133353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5134353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5135353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    lxc = _dlog(xc, xe, p+b+1)
5136353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5137353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5138353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    shift = ye-b
5139353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if shift >= 0:
5140353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        pc = lxc*yc*10**shift
5141353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
5142353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        pc = _div_nearest(lxc*yc, 10**-shift)
5143353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5144353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if pc == 0:
5145353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # we prefer a result that isn't exactly 1; this makes it
5146353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        # easier to compute a correctly rounded result in __pow__
5147353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5148353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            coeff, exp = 10**(p-1)+1, 1-p
5149353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        else:
5150353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista            coeff, exp = 10**p-1, -p
5151353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    else:
5152353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        coeff, exp = _dexp(pc, -(p+1), p+1)
5153353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        coeff = _div_nearest(coeff, 10)
5154353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        exp += 1
5155353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5156353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return coeff, exp
5157353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
5158353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _log10_lb(c, correction = {
5159353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5160353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        '6': 23, '7': 16, '8': 10, '9': 5}):
5161353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    """Compute a lower bound for 100*log10(c) for a positive integer c."""
5162353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if c <= 0:
5163353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        raise ValueError("The argument to _log10_lb should be nonnegative.")
5164353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    str_c = str(c)
5165353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    return 100*len(str_c) - correction[str_c[0]]
5166353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista
516759c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Helper Functions ####################################################
51687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
5169353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batistadef _convert_other(other, raiseit=False):
5170636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    """Convert other to Decimal.
5171636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
5172636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    Verifies that it's ok to use in an implicit construction.
5173636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    """
5174636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    if isinstance(other, Decimal):
5175636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        return other
5176636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger    if isinstance(other, (int, long)):
5177636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger        return Decimal(other)
5178353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista    if raiseit:
5179353750c405c9099d0be69c6af1d17037b38c4ddfFacundo Batista        raise TypeError("Unable to convert %s to Decimal" % other)
5180267b868f23a85c6a63a06452c85487355cf9ab8aRaymond Hettinger    return NotImplemented
5181636a6b100fe6083388bc5315758326078abe65b4Raymond Hettinger
518259c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### Setup Specific Contexts ############################################
51837c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51847c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# The default context prototype used by Context()
5185fed52963fcf97154e0b7d1d82514767d95eb27e5Raymond Hettinger# Is mutable, so that new contexts can have different default values
51867c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51877c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond HettingerDefaultContext = Context(
51886ea484582238a65d44a76e3a831e3ba7c77a1a25Raymond Hettinger        prec=28, rounding=ROUND_HALF_EVEN,
5189bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        traps=[DivisionByZero, Overflow, InvalidOperation],
5190bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        flags=[],
519199148e7eaad7741fbfb0822009b7c9b216ecc227Raymond Hettinger        Emax=999999999,
519299148e7eaad7741fbfb0822009b7c9b216ecc227Raymond Hettinger        Emin=-999999999,
5193e0f1581babe682552d7eadc4e54636b1c2775f0bRaymond Hettinger        capitals=1
51947c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger)
51957c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
51967c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# Pre-made alternate contexts offered by the specification
51977c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# Don't change these; the user should be able to select these
51987c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# contexts and be able to reproduce results from other implementations
51997c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger# of the spec.
52007c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52019ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond HettingerBasicContext = Context(
52027c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger        prec=9, rounding=ROUND_HALF_UP,
5203bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5204bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        flags=[],
52057c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger)
52067c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52079ec3e3b6eb4b36870bd28682e6c7a6c36911e5e0Raymond HettingerExtendedContext = Context(
52086ea484582238a65d44a76e3a831e3ba7c77a1a25Raymond Hettinger        prec=9, rounding=ROUND_HALF_EVEN,
5209bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        traps=[],
5210bf4406971ce34434ed914d17fab70370948d2aabRaymond Hettinger        flags=[],
52117c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger)
52127c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52137c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
521459c5884b4c37b6288911ff2aed218cfbb41f06abFacundo Batista##### crud for parsing strings #############################################
52156a123cb7827859748a0096570dfbb5ceba0e59dcMark Dickinson#
521672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# Regular expression used for parsing numeric strings.  Additional
521772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# comments:
521872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista#
521972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
522072bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# whitespace.  But note that the specification disallows whitespace in
522172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# a numeric string.
522272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista#
522372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# 2. For finite numbers (not infinities and NaNs) the body of the
522472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# number between the optional sign and the optional exponent must have
522572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# at least one decimal digit, possibly after the decimal point.  The
522672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# lookahead expression '(?=\d|\.\d)' checks this.
522772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista#
522872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# As the flag UNICODE is not enabled here, we're explicitly avoiding any
522972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# other meaning for \d than the numbers [0-9].
52307c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
523172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batistaimport re
523272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista_parser = re.compile(r"""     # A numeric string consists of:
52337c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger#    \s*
523472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    (?P<sign>[-+])?           # an optional sign, followed by either...
52357c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    (
523672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        (?=\d|\.\d)           # ...a number (with at least one digit)
523772bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        (?P<int>\d*)          # consisting of a (possibly empty) integer part
523872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        (\.(?P<frac>\d*))?    # followed by an optional fractional part
523972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
52407c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    |
524172bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        Inf(inity)?           # ...an infinity, or...
524272bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista    |
524372bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        (?P<signal>s)?        # ...an (optionally signaling)
524472bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        NaN                   # NaN
524572bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista        (?P<diag>\d*)         # with (possibly empty) diagnostic information.
52467c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    )
52477c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger#    \s*
524859bc20bb273055e2cd48a467524d21340c1771ccMark Dickinson    \Z
524972bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista""", re.VERBOSE | re.IGNORECASE).match
52507c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52512ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista_all_zeros = re.compile('0*$').match
52522ec7415db5ad63c4e4b27ee793214071454f6fe5Facundo Batista_exact_half = re.compile('50*$').match
52537c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerdel re
52547c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52550d4c06e06e5ee1f3bb1fa8068114bd700d74864aNeal Norwitz
525672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista##### Useful Constants (internal use only) ################################
52577c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
525872bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# Reusable defaults
525972bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaInf = Decimal('Inf')
526072bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistanegInf = Decimal('-Inf')
526172bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaNaN = Decimal('NaN')
526272bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaDec_0 = Decimal(0)
526372bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaDec_p1 = Decimal(1)
526472bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaDec_n1 = Decimal(-1)
52657c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
526672bc54faed8f12dc89ecc989fc7921002db3427fFacundo Batista# Infsign[sign] is infinity w/ that sign
526772bc54faed8f12dc89ecc989fc7921002db3427fFacundo BatistaInfsign = (Inf, negInf)
52687c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52697c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52707c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger
52717c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettingerif __name__ == '__main__':
52727c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    import doctest, sys
52737c85fa4a5203912aca564ce719a0fdd0fd5411e5Raymond Hettinger    doctest.testmod(sys.modules[__name__])
5274