blob: 6d0b34c000a1372e3590f39104f5ac3f8afcb647 [file] [log] [blame]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001# Copyright (c) 2004 Python Software Foundation.
2# All rights reserved.
3
4# Written by Eric Price <eprice at tjhsst.edu>
5# and Facundo Batista <facundo at taniquetil.com.ar>
6# and Raymond Hettinger <python at rcn.com>
Fred Drake1f34eb12004-07-01 14:28:36 +00007# and Aahz <aahz at pobox.com>
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00008# and Tim Peters
9
Facundo Batista6ab24792009-02-16 15:41:37 +000010# This module should be kept in sync with the latest updates of the
11# IBM specification as it evolves. Those updates will be treated
Raymond Hettinger27dbcf22004-08-19 22:39:55 +000012# as bug fixes (deviation from the spec is a compatibility, usability
13# bug) and will be backported. At this point the spec is stabilizing
14# and the updates are becoming fewer, smaller, and less significant.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000015
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000016"""
Facundo Batista6ab24792009-02-16 15:41:37 +000017This is an implementation of decimal floating point arithmetic based on
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000018the General Decimal Arithmetic Specification:
19
Raymond Hettinger960dc362009-04-21 03:43:15 +000020 http://speleotrove.com/decimal/decarith.html
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000021
Raymond Hettinger0ea241e2004-07-04 13:53:24 +000022and IEEE standard 854-1987:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000023
Senthil Kumaran4fec47e2013-09-07 23:19:29 -070024 http://en.wikipedia.org/wiki/IEEE_854-1987
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000025
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000026Decimal floating point has finite precision with arbitrarily large bounds.
27
Guido van Rossumd8faa362007-04-27 19:54:29 +000028The purpose of this module is to support arithmetic using familiar
29"schoolhouse" rules and to avoid some of the tricky representation
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000030issues associated with binary floating point. The package is especially
31useful for financial applications or for contexts where users have
32expectations that are at odds with binary floating point (for instance,
33in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
Mark Dickinsonaa63c4d2010-06-12 16:37:53 +000034of 0.0; Decimal('1.00') % Decimal('0.1') returns the expected
35Decimal('0.00')).
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000036
37Here are some examples of using the decimal module:
38
39>>> from decimal import *
Raymond Hettingerbd7f76d2004-07-08 00:49:18 +000040>>> setcontext(ExtendedContext)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000041>>> Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000042Decimal('0')
43>>> Decimal('1')
44Decimal('1')
45>>> Decimal('-.0123')
46Decimal('-0.0123')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000047>>> Decimal(123456)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000048Decimal('123456')
Stefan Krah1919b7e2012-03-21 18:25:23 +010049>>> Decimal('123.45e12345678')
50Decimal('1.2345E+12345680')
Christian Heimes68f5fbe2008-02-14 08:27:37 +000051>>> Decimal('1.33') + Decimal('1.27')
52Decimal('2.60')
53>>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
54Decimal('-2.20')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000055>>> dig = Decimal(1)
Guido van Rossum7131f842007-02-09 20:13:25 +000056>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000570.333333333
58>>> getcontext().prec = 18
Guido van Rossum7131f842007-02-09 20:13:25 +000059>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000600.333333333333333333
Guido van Rossum7131f842007-02-09 20:13:25 +000061>>> print(dig.sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000621
Guido van Rossum7131f842007-02-09 20:13:25 +000063>>> print(Decimal(3).sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000641.73205080756887729
Guido van Rossum7131f842007-02-09 20:13:25 +000065>>> print(Decimal(3) ** 123)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000664.85192780976896427E+58
67>>> inf = Decimal(1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000068>>> print(inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000069Infinity
70>>> neginf = Decimal(-1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000071>>> print(neginf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000072-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000073>>> print(neginf + inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000074NaN
Guido van Rossum7131f842007-02-09 20:13:25 +000075>>> print(neginf * inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000076-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000077>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000078Infinity
Raymond Hettingerbf440692004-07-10 14:14:37 +000079>>> getcontext().traps[DivisionByZero] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000080>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000081Traceback (most recent call last):
82 ...
83 ...
84 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +000085decimal.DivisionByZero: x / 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000086>>> c = Context()
Raymond Hettingerbf440692004-07-10 14:14:37 +000087>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000088>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000890
90>>> c.divide(Decimal(0), Decimal(0))
Christian Heimes68f5fbe2008-02-14 08:27:37 +000091Decimal('NaN')
Raymond Hettingerbf440692004-07-10 14:14:37 +000092>>> c.traps[InvalidOperation] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000093>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000941
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000095>>> c.flags[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000096>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000970
Guido van Rossum7131f842007-02-09 20:13:25 +000098>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000099Traceback (most recent call last):
100 ...
101 ...
102 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +0000103decimal.InvalidOperation: 0 / 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000104>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001051
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000106>>> c.flags[InvalidOperation] = 0
Raymond Hettingerbf440692004-07-10 14:14:37 +0000107>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000108>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000109NaN
Guido van Rossum7131f842007-02-09 20:13:25 +0000110>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001111
112>>>
113"""
114
115__all__ = [
116 # Two major classes
117 'Decimal', 'Context',
118
119 # Contexts
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +0000120 'DefaultContext', 'BasicContext', 'ExtendedContext',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000121
122 # Exceptions
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +0000123 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
124 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
Stefan Krah1919b7e2012-03-21 18:25:23 +0100125 'FloatOperation',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000126
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000127 # Constants for use in setting up contexts
128 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000129 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000130
131 # Functions for manipulating contexts
Stefan Krah1919b7e2012-03-21 18:25:23 +0100132 'setcontext', 'getcontext', 'localcontext',
133
134 # Limits for the C version for compatibility
135 'MAX_PREC', 'MAX_EMAX', 'MIN_EMIN', 'MIN_ETINY',
136
137 # C version: compile time choice that enables the thread local context
138 'HAVE_THREADS'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000139]
140
Raymond Hettinger960dc362009-04-21 03:43:15 +0000141__version__ = '1.70' # Highest version of the spec this complies with
Raymond Hettinger697ce952010-11-30 20:32:59 +0000142 # See http://speleotrove.com/decimal/
Stefan Krah45059eb2013-11-24 19:44:57 +0100143__libmpdec_version__ = "2.4.0" # compatible libmpdec version
Raymond Hettinger960dc362009-04-21 03:43:15 +0000144
Raymond Hettinger771ed762009-01-03 19:20:32 +0000145import math as _math
Raymond Hettinger82417ca2009-02-03 03:54:28 +0000146import numbers as _numbers
Stefan Krah1919b7e2012-03-21 18:25:23 +0100147import sys
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000148
Christian Heimes25bb7832008-01-11 16:17:00 +0000149try:
150 from collections import namedtuple as _namedtuple
151 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
Brett Cannoncd171c82013-07-04 17:43:24 -0400152except ImportError:
Christian Heimes25bb7832008-01-11 16:17:00 +0000153 DecimalTuple = lambda *args: args
154
Guido van Rossumd8faa362007-04-27 19:54:29 +0000155# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000156ROUND_DOWN = 'ROUND_DOWN'
157ROUND_HALF_UP = 'ROUND_HALF_UP'
158ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
159ROUND_CEILING = 'ROUND_CEILING'
160ROUND_FLOOR = 'ROUND_FLOOR'
161ROUND_UP = 'ROUND_UP'
162ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000163ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000164
Stefan Krah1919b7e2012-03-21 18:25:23 +0100165# Compatibility with the C version
166HAVE_THREADS = True
167if sys.maxsize == 2**63-1:
168 MAX_PREC = 999999999999999999
169 MAX_EMAX = 999999999999999999
170 MIN_EMIN = -999999999999999999
171else:
172 MAX_PREC = 425000000
173 MAX_EMAX = 425000000
174 MIN_EMIN = -425000000
175
176MIN_ETINY = MIN_EMIN - (MAX_PREC-1)
177
Guido van Rossumd8faa362007-04-27 19:54:29 +0000178# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000179
180class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000181 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000182
183 Used exceptions derive from this.
184 If an exception derives from another exception besides this (such as
185 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
186 called if the others are present. This isn't actually used for
187 anything, though.
188
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000189 handle -- Called when context._raise_error is called and the
Stefan Krah2eb4a072010-05-19 15:52:31 +0000190 trap_enabler is not set. First argument is self, second is the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000191 context. More arguments can be given, those being after
192 the explanation in _raise_error (For example,
193 context._raise_error(NewError, '(-x)!', self._sign) would
194 call NewError().handle(context, self._sign).)
195
196 To define a new exception, it should be sufficient to have it derive
197 from DecimalException.
198 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000199 def handle(self, context, *args):
200 pass
201
202
203class Clamped(DecimalException):
204 """Exponent of a 0 changed to fit bounds.
205
206 This occurs and signals clamped if the exponent of a result has been
207 altered in order to fit the constraints of a specific concrete
Guido van Rossumd8faa362007-04-27 19:54:29 +0000208 representation. This may occur when the exponent of a zero result would
209 be outside the bounds of a representation, or when a large normal
210 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000211 this latter case, the exponent is reduced to fit and the corresponding
212 number of zero digits are appended to the coefficient ("fold-down").
213 """
214
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000215class InvalidOperation(DecimalException):
216 """An invalid operation was performed.
217
218 Various bad things cause this:
219
220 Something creates a signaling NaN
221 -INF + INF
Guido van Rossumd8faa362007-04-27 19:54:29 +0000222 0 * (+-)INF
223 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000224 x % 0
225 (+-)INF % x
226 x._rescale( non-integer )
227 sqrt(-x) , x > 0
228 0 ** 0
229 x ** (non-integer)
230 x ** (+-)INF
231 An operand is invalid
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000232
233 The result of the operation after these is a quiet positive NaN,
234 except when the cause is a signaling NaN, in which case the result is
235 also a quiet NaN, but with the original sign, and an optional
236 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000237 """
238 def handle(self, context, *args):
239 if args:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000240 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
241 return ans._fix_nan(context)
Mark Dickinsonf9236412009-01-02 23:23:21 +0000242 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000243
244class ConversionSyntax(InvalidOperation):
245 """Trying to convert badly formed string.
246
247 This occurs and signals invalid-operation if an string is being
248 converted to a number and it does not conform to the numeric string
Guido van Rossumd8faa362007-04-27 19:54:29 +0000249 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000250 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000251 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000252 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000253
254class DivisionByZero(DecimalException, ZeroDivisionError):
255 """Division by 0.
256
257 This occurs and signals division-by-zero if division of a finite number
258 by zero was attempted (during a divide-integer or divide operation, or a
259 power operation with negative right-hand operand), and the dividend was
260 not zero.
261
262 The result of the operation is [sign,inf], where sign is the exclusive
263 or of the signs of the operands for divide, or is 1 for an odd power of
264 -0, for power.
265 """
266
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000267 def handle(self, context, sign, *args):
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000268 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000269
270class DivisionImpossible(InvalidOperation):
271 """Cannot perform the division adequately.
272
273 This occurs and signals invalid-operation if the integer result of a
274 divide-integer or remainder operation had too many digits (would be
Guido van Rossumd8faa362007-04-27 19:54:29 +0000275 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000276 """
277
278 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000279 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000280
281class DivisionUndefined(InvalidOperation, ZeroDivisionError):
282 """Undefined result of division.
283
284 This occurs and signals invalid-operation if division by zero was
285 attempted (during a divide-integer, divide, or remainder operation), and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000286 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000287 """
288
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000289 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000290 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000291
292class Inexact(DecimalException):
293 """Had to round, losing information.
294
295 This occurs and signals inexact whenever the result of an operation is
296 not exact (that is, it needed to be rounded and any discarded digits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000297 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000298 result in all cases is unchanged.
299
300 The inexact signal may be tested (or trapped) to determine if a given
301 operation (or sequence of operations) was inexact.
302 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000303
304class InvalidContext(InvalidOperation):
305 """Invalid context. Unknown rounding, for example.
306
307 This occurs and signals invalid-operation if an invalid context was
Guido van Rossumd8faa362007-04-27 19:54:29 +0000308 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000309 on creation and either the precision exceeds the capability of the
310 underlying concrete representation or an unknown or unsupported rounding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000311 was specified. These aspects of the context need only be checked when
312 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000313 """
314
315 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000316 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000317
318class Rounded(DecimalException):
319 """Number got rounded (not necessarily changed during rounding).
320
321 This occurs and signals rounded whenever the result of an operation is
322 rounded (that is, some zero or non-zero digits were discarded from the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000323 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000324 result in all cases is unchanged.
325
326 The rounded signal may be tested (or trapped) to determine if a given
327 operation (or sequence of operations) caused a loss of precision.
328 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000329
330class Subnormal(DecimalException):
331 """Exponent < Emin before rounding.
332
333 This occurs and signals subnormal whenever the result of a conversion or
334 operation is subnormal (that is, its adjusted exponent is less than
Guido van Rossumd8faa362007-04-27 19:54:29 +0000335 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000336
337 The subnormal signal may be tested (or trapped) to determine if a given
338 or operation (or sequence of operations) yielded a subnormal result.
339 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000340
341class Overflow(Inexact, Rounded):
342 """Numerical overflow.
343
344 This occurs and signals overflow if the adjusted exponent of a result
345 (from a conversion or from an operation that is not an attempt to divide
346 by zero), after rounding, would be greater than the largest value that
347 can be handled by the implementation (the value Emax).
348
349 The result depends on the rounding mode:
350
351 For round-half-up and round-half-even (and for round-half-down and
352 round-up, if implemented), the result of the operation is [sign,inf],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000353 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000354 result is the largest finite number that can be represented in the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000355 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000356 round-ceiling, the result is the same as for round-down if the sign of
Guido van Rossumd8faa362007-04-27 19:54:29 +0000357 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000358 the result is the same as for round-down if the sign of the intermediate
Guido van Rossumd8faa362007-04-27 19:54:29 +0000359 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000360 will also be raised.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000361 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000362
363 def handle(self, context, sign, *args):
364 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000365 ROUND_HALF_DOWN, ROUND_UP):
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000366 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000367 if sign == 0:
368 if context.rounding == ROUND_CEILING:
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000369 return _SignedInfinity[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000370 return _dec_from_triple(sign, '9'*context.prec,
371 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000372 if sign == 1:
373 if context.rounding == ROUND_FLOOR:
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000374 return _SignedInfinity[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000375 return _dec_from_triple(sign, '9'*context.prec,
376 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000377
378
379class Underflow(Inexact, Rounded, Subnormal):
380 """Numerical underflow with result rounded to 0.
381
382 This occurs and signals underflow if a result is inexact and the
383 adjusted exponent of the result would be smaller (more negative) than
384 the smallest value that can be handled by the implementation (the value
Guido van Rossumd8faa362007-04-27 19:54:29 +0000385 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000386
387 The result after an underflow will be a subnormal number rounded, if
Guido van Rossumd8faa362007-04-27 19:54:29 +0000388 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000389 in 0 with the sign of the intermediate result and an exponent of Etiny.
390
391 In all cases, Inexact, Rounded, and Subnormal will also be raised.
392 """
393
Stefan Krahb6405ef2012-03-23 14:46:48 +0100394class FloatOperation(DecimalException, TypeError):
Stefan Krah1919b7e2012-03-21 18:25:23 +0100395 """Enable stricter semantics for mixing floats and Decimals.
396
397 If the signal is not trapped (default), mixing floats and Decimals is
398 permitted in the Decimal() constructor, context.create_decimal() and
399 all comparison operators. Both conversion and comparisons are exact.
400 Any occurrence of a mixed operation is silently recorded by setting
401 FloatOperation in the context flags. Explicit conversions with
402 Decimal.from_float() or context.create_decimal_from_float() do not
403 set the flag.
404
405 Otherwise (the signal is trapped), only equality comparisons and explicit
406 conversions are silent. All other mixed operations raise FloatOperation.
407 """
408
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000409# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000410_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Stefan Krah1919b7e2012-03-21 18:25:23 +0100411 Underflow, InvalidOperation, Subnormal, FloatOperation]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000412
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000413# Map conditions (per the spec) to signals
414_condition_map = {ConversionSyntax:InvalidOperation,
415 DivisionImpossible:InvalidOperation,
416 DivisionUndefined:InvalidOperation,
417 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000418
Stefan Krah1919b7e2012-03-21 18:25:23 +0100419# Valid rounding modes
420_rounding_modes = (ROUND_DOWN, ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_CEILING,
421 ROUND_FLOOR, ROUND_UP, ROUND_HALF_DOWN, ROUND_05UP)
422
Guido van Rossumd8faa362007-04-27 19:54:29 +0000423##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000424
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000425# The getcontext() and setcontext() function manage access to a thread-local
426# current context. Py2.4 offers direct support for thread locals. If that
Georg Brandlf9926402008-06-13 06:32:25 +0000427# is not available, use threading.current_thread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000428# work for older Pythons. If threads are not part of the build, create a
429# mock threading object with threading.local() returning the module namespace.
430
431try:
432 import threading
Brett Cannoncd171c82013-07-04 17:43:24 -0400433except ImportError:
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000434 # Python was compiled without threads; create a mock object instead
Guido van Rossumd8faa362007-04-27 19:54:29 +0000435 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000436 def local(self, sys=sys):
437 return sys.modules[__name__]
438 threading = MockThreading()
Stefan Krah1919b7e2012-03-21 18:25:23 +0100439 del MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000440
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000441try:
442 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000443
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000444except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000445
Guido van Rossumd8faa362007-04-27 19:54:29 +0000446 # To fix reloading, force it to create a new context
447 # Old contexts have different exceptions in their dicts, making problems.
Georg Brandlf9926402008-06-13 06:32:25 +0000448 if hasattr(threading.current_thread(), '__decimal_context__'):
449 del threading.current_thread().__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000450
451 def setcontext(context):
452 """Set this thread's context to context."""
453 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000454 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000455 context.clear_flags()
Georg Brandlf9926402008-06-13 06:32:25 +0000456 threading.current_thread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000457
458 def getcontext():
459 """Returns this thread's context.
460
461 If this thread does not yet have a context, returns
462 a new context and sets this thread's context.
463 New contexts are copies of DefaultContext.
464 """
465 try:
Georg Brandlf9926402008-06-13 06:32:25 +0000466 return threading.current_thread().__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000467 except AttributeError:
468 context = Context()
Georg Brandlf9926402008-06-13 06:32:25 +0000469 threading.current_thread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000470 return context
471
472else:
473
474 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000475 if hasattr(local, '__decimal_context__'):
476 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000477
478 def getcontext(_local=local):
479 """Returns this thread's context.
480
481 If this thread does not yet have a context, returns
482 a new context and sets this thread's context.
483 New contexts are copies of DefaultContext.
484 """
485 try:
486 return _local.__decimal_context__
487 except AttributeError:
488 context = Context()
489 _local.__decimal_context__ = context
490 return context
491
492 def setcontext(context, _local=local):
493 """Set this thread's context to context."""
494 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000495 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000496 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000497 _local.__decimal_context__ = context
498
499 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000500
Thomas Wouters89f507f2006-12-13 04:49:30 +0000501def localcontext(ctx=None):
502 """Return a context manager for a copy of the supplied context
503
504 Uses a copy of the current context if no context is specified
505 The returned context manager creates a local decimal context
506 in a with statement:
507 def sin(x):
508 with localcontext() as ctx:
509 ctx.prec += 2
510 # Rest of sin calculation algorithm
511 # uses a precision 2 greater than normal
Guido van Rossumd8faa362007-04-27 19:54:29 +0000512 return +s # Convert result to normal precision
Thomas Wouters89f507f2006-12-13 04:49:30 +0000513
514 def sin(x):
515 with localcontext(ExtendedContext):
516 # Rest of sin calculation algorithm
517 # uses the Extended Context from the
518 # General Decimal Arithmetic Specification
Guido van Rossumd8faa362007-04-27 19:54:29 +0000519 return +s # Convert result to normal context
Thomas Wouters89f507f2006-12-13 04:49:30 +0000520
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000521 >>> setcontext(DefaultContext)
Guido van Rossum7131f842007-02-09 20:13:25 +0000522 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000523 28
524 >>> with localcontext():
525 ... ctx = getcontext()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000526 ... ctx.prec += 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000527 ... print(ctx.prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000528 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000529 30
530 >>> with localcontext(ExtendedContext):
Guido van Rossum7131f842007-02-09 20:13:25 +0000531 ... print(getcontext().prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000532 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000533 9
Guido van Rossum7131f842007-02-09 20:13:25 +0000534 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000535 28
536 """
537 if ctx is None: ctx = getcontext()
538 return _ContextManager(ctx)
539
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000540
Guido van Rossumd8faa362007-04-27 19:54:29 +0000541##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000542
Raymond Hettingera0fd8882009-01-20 07:24:44 +0000543# Do not subclass Decimal from numbers.Real and do not register it as such
544# (because Decimals are not interoperable with floats). See the notes in
545# numbers.py for more detail.
546
547class Decimal(object):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000548 """Floating point class for decimal arithmetic."""
549
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000550 __slots__ = ('_exp','_int','_sign', '_is_special')
551 # Generally, the value of the Decimal instance is given by
552 # (-1)**_sign * _int * 10**_exp
553 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000554
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000555 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000556 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000557 """Create a decimal point instance.
558
559 >>> Decimal('3.14') # string input
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000560 Decimal('3.14')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000561 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000562 Decimal('3.14')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000563 >>> Decimal(314) # int
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000564 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000565 >>> Decimal(Decimal(314)) # another decimal instance
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000566 Decimal('314')
Christian Heimesa62da1d2008-01-12 19:39:10 +0000567 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000568 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000569 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000570
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000571 # Note that the coefficient, self._int, is actually stored as
572 # a string rather than as a tuple of digits. This speeds up
573 # the "digits to integer" and "integer to digits" conversions
574 # that are used in almost every arithmetic operation on
575 # Decimals. This is an internal detail: the as_tuple function
576 # and the Decimal constructor still deal with tuples of
577 # digits.
578
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000579 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000580
Christian Heimesd59c64c2007-11-30 19:27:20 +0000581 # From a string
582 # REs insist on real strings, so we can too.
583 if isinstance(value, str):
Christian Heimesa62da1d2008-01-12 19:39:10 +0000584 m = _parser(value.strip())
Christian Heimesd59c64c2007-11-30 19:27:20 +0000585 if m is None:
586 if context is None:
587 context = getcontext()
588 return context._raise_error(ConversionSyntax,
589 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000590
Christian Heimesd59c64c2007-11-30 19:27:20 +0000591 if m.group('sign') == "-":
592 self._sign = 1
593 else:
594 self._sign = 0
595 intpart = m.group('int')
596 if intpart is not None:
597 # finite number
Mark Dickinson345adc42009-08-02 10:14:23 +0000598 fracpart = m.group('frac') or ''
Christian Heimesd59c64c2007-11-30 19:27:20 +0000599 exp = int(m.group('exp') or '0')
Mark Dickinson345adc42009-08-02 10:14:23 +0000600 self._int = str(int(intpart+fracpart))
601 self._exp = exp - len(fracpart)
Christian Heimesd59c64c2007-11-30 19:27:20 +0000602 self._is_special = False
603 else:
604 diag = m.group('diag')
605 if diag is not None:
606 # NaN
Mark Dickinson345adc42009-08-02 10:14:23 +0000607 self._int = str(int(diag or '0')).lstrip('0')
Christian Heimesd59c64c2007-11-30 19:27:20 +0000608 if m.group('signal'):
609 self._exp = 'N'
610 else:
611 self._exp = 'n'
612 else:
613 # infinity
614 self._int = '0'
615 self._exp = 'F'
616 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000617 return self
618
619 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000620 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000621 if value >= 0:
622 self._sign = 0
623 else:
624 self._sign = 1
625 self._exp = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000626 self._int = str(abs(value))
Christian Heimesd59c64c2007-11-30 19:27:20 +0000627 self._is_special = False
628 return self
629
630 # From another decimal
631 if isinstance(value, Decimal):
632 self._exp = value._exp
633 self._sign = value._sign
634 self._int = value._int
635 self._is_special = value._is_special
636 return self
637
638 # From an internal working value
639 if isinstance(value, _WorkRep):
640 self._sign = value.sign
641 self._int = str(value.int)
642 self._exp = int(value.exp)
643 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000644 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000645
646 # tuple/list conversion (possibly from as_tuple())
647 if isinstance(value, (list,tuple)):
648 if len(value) != 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000649 raise ValueError('Invalid tuple size in creation of Decimal '
650 'from list or tuple. The list or tuple '
651 'should have exactly three elements.')
652 # process sign. The isinstance test rejects floats
653 if not (isinstance(value[0], int) and value[0] in (0,1)):
654 raise ValueError("Invalid sign. The first value in the tuple "
655 "should be an integer; either 0 for a "
656 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000657 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000658 if value[2] == 'F':
659 # infinity: value[1] is ignored
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000660 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000661 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000662 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000663 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000664 # process and validate the digits in value[1]
665 digits = []
666 for digit in value[1]:
667 if isinstance(digit, int) and 0 <= digit <= 9:
668 # skip leading zeros
669 if digits or digit != 0:
670 digits.append(digit)
671 else:
672 raise ValueError("The second value in the tuple must "
673 "be composed of integers in the range "
674 "0 through 9.")
675 if value[2] in ('n', 'N'):
676 # NaN: digits form the diagnostic
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000677 self._int = ''.join(map(str, digits))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000678 self._exp = value[2]
679 self._is_special = True
680 elif isinstance(value[2], int):
681 # finite number: digits give the coefficient
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000682 self._int = ''.join(map(str, digits or [0]))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000683 self._exp = value[2]
684 self._is_special = False
685 else:
686 raise ValueError("The third value in the tuple must "
687 "be an integer, or one of the "
688 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000689 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000690
Raymond Hettingerbf440692004-07-10 14:14:37 +0000691 if isinstance(value, float):
Stefan Krah1919b7e2012-03-21 18:25:23 +0100692 if context is None:
693 context = getcontext()
694 context._raise_error(FloatOperation,
695 "strict semantics for mixing floats and Decimals are "
696 "enabled")
Raymond Hettinger96798592010-04-02 16:58:27 +0000697 value = Decimal.from_float(value)
698 self._exp = value._exp
699 self._sign = value._sign
700 self._int = value._int
701 self._is_special = value._is_special
702 return self
Raymond Hettingerbf440692004-07-10 14:14:37 +0000703
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000704 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000705
Mark Dickinson9c3f5032012-10-31 17:53:27 +0000706 @classmethod
Raymond Hettinger771ed762009-01-03 19:20:32 +0000707 def from_float(cls, f):
708 """Converts a float to a decimal number, exactly.
709
710 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
711 Since 0.1 is not exactly representable in binary floating point, the
712 value is stored as the nearest representable value which is
713 0x1.999999999999ap-4. The exact equivalent of the value in decimal
714 is 0.1000000000000000055511151231257827021181583404541015625.
715
716 >>> Decimal.from_float(0.1)
717 Decimal('0.1000000000000000055511151231257827021181583404541015625')
718 >>> Decimal.from_float(float('nan'))
719 Decimal('NaN')
720 >>> Decimal.from_float(float('inf'))
721 Decimal('Infinity')
722 >>> Decimal.from_float(-float('inf'))
723 Decimal('-Infinity')
724 >>> Decimal.from_float(-0.0)
725 Decimal('-0')
726
727 """
728 if isinstance(f, int): # handle integer inputs
729 return cls(f)
Stefan Krah1919b7e2012-03-21 18:25:23 +0100730 if not isinstance(f, float):
731 raise TypeError("argument must be int or float.")
732 if _math.isinf(f) or _math.isnan(f):
Raymond Hettinger771ed762009-01-03 19:20:32 +0000733 return cls(repr(f))
Mark Dickinsonba298e42009-01-04 21:17:43 +0000734 if _math.copysign(1.0, f) == 1.0:
735 sign = 0
736 else:
737 sign = 1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000738 n, d = abs(f).as_integer_ratio()
739 k = d.bit_length() - 1
740 result = _dec_from_triple(sign, str(n*5**k), -k)
Mark Dickinsonba298e42009-01-04 21:17:43 +0000741 if cls is Decimal:
742 return result
743 else:
744 return cls(result)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000745
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000746 def _isnan(self):
747 """Returns whether the number is not actually one.
748
749 0 if a number
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000750 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000751 2 if sNaN
752 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000753 if self._is_special:
754 exp = self._exp
755 if exp == 'n':
756 return 1
757 elif exp == 'N':
758 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000759 return 0
760
761 def _isinfinity(self):
762 """Returns whether the number is infinite
763
764 0 if finite or not a number
765 1 if +INF
766 -1 if -INF
767 """
768 if self._exp == 'F':
769 if self._sign:
770 return -1
771 return 1
772 return 0
773
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000774 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000775 """Returns whether the number is not actually one.
776
777 if self, other are sNaN, signal
778 if self, other are NaN return nan
779 return 0
780
781 Done before operations.
782 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000783
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000784 self_is_nan = self._isnan()
785 if other is None:
786 other_is_nan = False
787 else:
788 other_is_nan = other._isnan()
789
790 if self_is_nan or other_is_nan:
791 if context is None:
792 context = getcontext()
793
794 if self_is_nan == 2:
795 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000796 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000797 if other_is_nan == 2:
798 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000799 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000800 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000801 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000802
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000803 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000804 return 0
805
Christian Heimes77c02eb2008-02-09 02:18:51 +0000806 def _compare_check_nans(self, other, context):
807 """Version of _check_nans used for the signaling comparisons
808 compare_signal, __le__, __lt__, __ge__, __gt__.
809
810 Signal InvalidOperation if either self or other is a (quiet
811 or signaling) NaN. Signaling NaNs take precedence over quiet
812 NaNs.
813
814 Return 0 if neither operand is a NaN.
815
816 """
817 if context is None:
818 context = getcontext()
819
820 if self._is_special or other._is_special:
821 if self.is_snan():
822 return context._raise_error(InvalidOperation,
823 'comparison involving sNaN',
824 self)
825 elif other.is_snan():
826 return context._raise_error(InvalidOperation,
827 'comparison involving sNaN',
828 other)
829 elif self.is_qnan():
830 return context._raise_error(InvalidOperation,
831 'comparison involving NaN',
832 self)
833 elif other.is_qnan():
834 return context._raise_error(InvalidOperation,
835 'comparison involving NaN',
836 other)
837 return 0
838
Jack Diederich4dafcc42006-11-28 19:15:13 +0000839 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000840 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000841
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000842 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000843 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000844 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000845
Christian Heimes77c02eb2008-02-09 02:18:51 +0000846 def _cmp(self, other):
847 """Compare the two non-NaN decimal instances self and other.
848
849 Returns -1 if self < other, 0 if self == other and 1
850 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000851
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000852 if self._is_special or other._is_special:
Mark Dickinsone6aad752009-01-25 10:48:51 +0000853 self_inf = self._isinfinity()
854 other_inf = other._isinfinity()
855 if self_inf == other_inf:
856 return 0
857 elif self_inf < other_inf:
858 return -1
859 else:
860 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000861
Mark Dickinsone6aad752009-01-25 10:48:51 +0000862 # check for zeros; Decimal('0') == Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000863 if not self:
864 if not other:
865 return 0
866 else:
867 return -((-1)**other._sign)
868 if not other:
869 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000870
Guido van Rossumd8faa362007-04-27 19:54:29 +0000871 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000872 if other._sign < self._sign:
873 return -1
874 if self._sign < other._sign:
875 return 1
876
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000877 self_adjusted = self.adjusted()
878 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000879 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000880 self_padded = self._int + '0'*(self._exp - other._exp)
881 other_padded = other._int + '0'*(other._exp - self._exp)
Mark Dickinsone6aad752009-01-25 10:48:51 +0000882 if self_padded == other_padded:
883 return 0
884 elif self_padded < other_padded:
885 return -(-1)**self._sign
886 else:
887 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000888 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000889 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000891 return -((-1)**self._sign)
892
Christian Heimes77c02eb2008-02-09 02:18:51 +0000893 # Note: The Decimal standard doesn't cover rich comparisons for
894 # Decimals. In particular, the specification is silent on the
895 # subject of what should happen for a comparison involving a NaN.
896 # We take the following approach:
897 #
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000898 # == comparisons involving a quiet NaN always return False
899 # != comparisons involving a quiet NaN always return True
900 # == or != comparisons involving a signaling NaN signal
901 # InvalidOperation, and return False or True as above if the
902 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000903 # <, >, <= and >= comparisons involving a (quiet or signaling)
904 # NaN signal InvalidOperation, and return False if the
Christian Heimes3feef612008-02-11 06:19:17 +0000905 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000906 #
907 # This behavior is designed to conform as closely as possible to
908 # that specified by IEEE 754.
909
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000910 def __eq__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000911 self, other = _convert_for_comparison(self, other, equality_op=True)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000912 if other is NotImplemented:
913 return other
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000914 if self._check_nans(other, context):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000915 return False
916 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000917
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000918 def __ne__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000919 self, other = _convert_for_comparison(self, other, equality_op=True)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000920 if other is NotImplemented:
921 return other
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000922 if self._check_nans(other, context):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000923 return True
924 return self._cmp(other) != 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000925
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000926
Christian Heimes77c02eb2008-02-09 02:18:51 +0000927 def __lt__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000928 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000929 if other is NotImplemented:
930 return other
931 ans = self._compare_check_nans(other, context)
932 if ans:
933 return False
934 return self._cmp(other) < 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000935
Christian Heimes77c02eb2008-02-09 02:18:51 +0000936 def __le__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000937 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000938 if other is NotImplemented:
939 return other
940 ans = self._compare_check_nans(other, context)
941 if ans:
942 return False
943 return self._cmp(other) <= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000944
Christian Heimes77c02eb2008-02-09 02:18:51 +0000945 def __gt__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000946 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000947 if other is NotImplemented:
948 return other
949 ans = self._compare_check_nans(other, context)
950 if ans:
951 return False
952 return self._cmp(other) > 0
953
954 def __ge__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000955 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000956 if other is NotImplemented:
957 return other
958 ans = self._compare_check_nans(other, context)
959 if ans:
960 return False
961 return self._cmp(other) >= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000962
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000963 def compare(self, other, context=None):
964 """Compares one to another.
965
966 -1 => a < b
967 0 => a = b
968 1 => a > b
969 NaN => one is NaN
970 Like __cmp__, but returns Decimal instances.
971 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000972 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000973
Guido van Rossumd8faa362007-04-27 19:54:29 +0000974 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000975 if (self._is_special or other and other._is_special):
976 ans = self._check_nans(other, context)
977 if ans:
978 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000979
Christian Heimes77c02eb2008-02-09 02:18:51 +0000980 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000981
982 def __hash__(self):
983 """x.__hash__() <==> hash(x)"""
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000984
Mark Dickinsondc787d22010-05-23 13:33:13 +0000985 # In order to make sure that the hash of a Decimal instance
986 # agrees with the hash of a numerically equal integer, float
987 # or Fraction, we follow the rules for numeric hashes outlined
988 # in the documentation. (See library docs, 'Built-in Types').
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000989 if self._is_special:
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000990 if self.is_snan():
Raymond Hettingerd325c4b2010-11-21 04:08:28 +0000991 raise TypeError('Cannot hash a signaling NaN value.')
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000992 elif self.is_nan():
Mark Dickinsondc787d22010-05-23 13:33:13 +0000993 return _PyHASH_NAN
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000994 else:
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000995 if self._sign:
Mark Dickinsondc787d22010-05-23 13:33:13 +0000996 return -_PyHASH_INF
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000997 else:
Mark Dickinsondc787d22010-05-23 13:33:13 +0000998 return _PyHASH_INF
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000999
Mark Dickinsondc787d22010-05-23 13:33:13 +00001000 if self._exp >= 0:
1001 exp_hash = pow(10, self._exp, _PyHASH_MODULUS)
1002 else:
1003 exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS)
1004 hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS
Stefan Krahdc817b22010-11-17 11:16:34 +00001005 ans = hash_ if self >= 0 else -hash_
1006 return -2 if ans == -1 else ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001007
1008 def as_tuple(self):
1009 """Represents the number as a triple tuple.
1010
1011 To show the internals exactly as they are.
1012 """
Christian Heimes25bb7832008-01-11 16:17:00 +00001013 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001014
1015 def __repr__(self):
1016 """Represents the number as an instance of Decimal."""
1017 # Invariant: eval(repr(d)) == d
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001018 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001019
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001020 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001021 """Return string representation of the number in scientific notation.
1022
1023 Captures all of the information in the underlying representation.
1024 """
1025
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001026 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +00001027 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001028 if self._exp == 'F':
1029 return sign + 'Infinity'
1030 elif self._exp == 'n':
1031 return sign + 'NaN' + self._int
1032 else: # self._exp == 'N'
1033 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001034
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001035 # number of digits of self._int to left of decimal point
1036 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001037
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001038 # dotplace is number of digits of self._int to the left of the
1039 # decimal point in the mantissa of the output string (that is,
1040 # after adjusting the exponent)
1041 if self._exp <= 0 and leftdigits > -6:
1042 # no exponent required
1043 dotplace = leftdigits
1044 elif not eng:
1045 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001046 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001047 elif self._int == '0':
1048 # engineering notation, zero
1049 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001050 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001051 # engineering notation, nonzero
1052 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001053
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001054 if dotplace <= 0:
1055 intpart = '0'
1056 fracpart = '.' + '0'*(-dotplace) + self._int
1057 elif dotplace >= len(self._int):
1058 intpart = self._int+'0'*(dotplace-len(self._int))
1059 fracpart = ''
1060 else:
1061 intpart = self._int[:dotplace]
1062 fracpart = '.' + self._int[dotplace:]
1063 if leftdigits == dotplace:
1064 exp = ''
1065 else:
1066 if context is None:
1067 context = getcontext()
1068 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1069
1070 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001071
1072 def to_eng_string(self, context=None):
1073 """Convert to engineering-type string.
1074
1075 Engineering notation has an exponent which is a multiple of 3, so there
1076 are up to 3 digits left of the decimal place.
1077
1078 Same rules for when in exponential and when as a value as in __str__.
1079 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001080 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081
1082 def __neg__(self, context=None):
1083 """Returns a copy with the sign switched.
1084
1085 Rounds, if it has reason.
1086 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001087 if self._is_special:
1088 ans = self._check_nans(context=context)
1089 if ans:
1090 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001091
Mark Dickinson37a79fb2011-03-12 11:12:52 +00001092 if context is None:
1093 context = getcontext()
1094
1095 if not self and context.rounding != ROUND_FLOOR:
1096 # -Decimal('0') is Decimal('0'), not Decimal('-0'), except
1097 # in ROUND_FLOOR rounding mode.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001098 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001099 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001100 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001101
Christian Heimes2c181612007-12-17 20:04:13 +00001102 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001103
1104 def __pos__(self, context=None):
1105 """Returns a copy, unless it is a sNaN.
1106
1107 Rounds the number (if more then precision digits)
1108 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001109 if self._is_special:
1110 ans = self._check_nans(context=context)
1111 if ans:
1112 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001113
Mark Dickinson37a79fb2011-03-12 11:12:52 +00001114 if context is None:
1115 context = getcontext()
1116
1117 if not self and context.rounding != ROUND_FLOOR:
1118 # + (-0) = 0, except in ROUND_FLOOR rounding mode.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001119 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001120 else:
1121 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001122
Christian Heimes2c181612007-12-17 20:04:13 +00001123 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001124
Christian Heimes2c181612007-12-17 20:04:13 +00001125 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001126 """Returns the absolute value of self.
1127
Christian Heimes2c181612007-12-17 20:04:13 +00001128 If the keyword argument 'round' is false, do not round. The
1129 expression self.__abs__(round=False) is equivalent to
1130 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001131 """
Christian Heimes2c181612007-12-17 20:04:13 +00001132 if not round:
1133 return self.copy_abs()
1134
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001135 if self._is_special:
1136 ans = self._check_nans(context=context)
1137 if ans:
1138 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001139
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001140 if self._sign:
1141 ans = self.__neg__(context=context)
1142 else:
1143 ans = self.__pos__(context=context)
1144
1145 return ans
1146
1147 def __add__(self, other, context=None):
1148 """Returns self + other.
1149
1150 -INF + INF (or the reverse) cause InvalidOperation errors.
1151 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001152 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001153 if other is NotImplemented:
1154 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001155
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001156 if context is None:
1157 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001158
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001159 if self._is_special or other._is_special:
1160 ans = self._check_nans(other, context)
1161 if ans:
1162 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001163
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001164 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001165 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001166 if self._sign != other._sign and other._isinfinity():
1167 return context._raise_error(InvalidOperation, '-INF + INF')
1168 return Decimal(self)
1169 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001170 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001171
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001172 exp = min(self._exp, other._exp)
1173 negativezero = 0
1174 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001175 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001176 negativezero = 1
1177
1178 if not self and not other:
1179 sign = min(self._sign, other._sign)
1180 if negativezero:
1181 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001182 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001183 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001184 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001185 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001186 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001187 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001188 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001189 return ans
1190 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001191 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001192 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001193 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001194 return ans
1195
1196 op1 = _WorkRep(self)
1197 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001198 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001199
1200 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001201 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001202 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001203 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001204 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001205 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001206 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001207 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001208 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001209 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001210 if op1.sign == 1:
1211 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001212 op1.sign, op2.sign = op2.sign, op1.sign
1213 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001214 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001215 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001216 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001217 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001218 op1.sign, op2.sign = (0, 0)
1219 else:
1220 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001221 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001222
Raymond Hettinger17931de2004-10-27 06:21:46 +00001223 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001224 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001225 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001226 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001227
1228 result.exp = op1.exp
1229 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001230 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001231 return ans
1232
1233 __radd__ = __add__
1234
1235 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001236 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001237 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001238 if other is NotImplemented:
1239 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001240
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001241 if self._is_special or other._is_special:
1242 ans = self._check_nans(other, context=context)
1243 if ans:
1244 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001245
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001246 # self - other is computed as self + other.copy_negate()
1247 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001248
1249 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001250 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001251 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001252 if other is NotImplemented:
1253 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001254
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001255 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001256
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001257 def __mul__(self, other, context=None):
1258 """Return self * other.
1259
1260 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1261 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001262 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001263 if other is NotImplemented:
1264 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001265
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001266 if context is None:
1267 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001268
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001269 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001270
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001271 if self._is_special or other._is_special:
1272 ans = self._check_nans(other, context)
1273 if ans:
1274 return ans
1275
1276 if self._isinfinity():
1277 if not other:
1278 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001279 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001280
1281 if other._isinfinity():
1282 if not self:
1283 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001284 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001285
1286 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001287
1288 # Special case for multiplying by zero
1289 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001290 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001291 # Fixing in case the exponent is out of bounds
1292 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001293 return ans
1294
1295 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001296 if self._int == '1':
1297 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001298 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001299 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001300 if other._int == '1':
1301 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001302 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001303 return ans
1304
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001305 op1 = _WorkRep(self)
1306 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001307
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001308 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001309 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001310
1311 return ans
1312 __rmul__ = __mul__
1313
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001314 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001315 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001316 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001317 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001318 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001319
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001320 if context is None:
1321 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001322
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001323 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001324
1325 if self._is_special or other._is_special:
1326 ans = self._check_nans(other, context)
1327 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001328 return ans
1329
1330 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001331 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001332
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001333 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001334 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001335
1336 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001337 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001338 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001339
1340 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001341 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001342 if not self:
1343 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001344 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001345
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001346 if not self:
1347 exp = self._exp - other._exp
1348 coeff = 0
1349 else:
1350 # OK, so neither = 0, INF or NaN
1351 shift = len(other._int) - len(self._int) + context.prec + 1
1352 exp = self._exp - other._exp - shift
1353 op1 = _WorkRep(self)
1354 op2 = _WorkRep(other)
1355 if shift >= 0:
1356 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1357 else:
1358 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1359 if remainder:
1360 # result is not exact; adjust to ensure correct rounding
1361 if coeff % 5 == 0:
1362 coeff += 1
1363 else:
1364 # result is exact; get as close to ideal exponent as possible
1365 ideal_exp = self._exp - other._exp
1366 while exp < ideal_exp and coeff % 10 == 0:
1367 coeff //= 10
1368 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001369
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001370 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001371 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001372
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001373 def _divide(self, other, context):
1374 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001375
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001376 Assumes that neither self nor other is a NaN, that self is not
1377 infinite and that other is nonzero.
1378 """
1379 sign = self._sign ^ other._sign
1380 if other._isinfinity():
1381 ideal_exp = self._exp
1382 else:
1383 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001384
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001385 expdiff = self.adjusted() - other.adjusted()
1386 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001387 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001388 self._rescale(ideal_exp, context.rounding))
1389 if expdiff <= context.prec:
1390 op1 = _WorkRep(self)
1391 op2 = _WorkRep(other)
1392 if op1.exp >= op2.exp:
1393 op1.int *= 10**(op1.exp - op2.exp)
1394 else:
1395 op2.int *= 10**(op2.exp - op1.exp)
1396 q, r = divmod(op1.int, op2.int)
1397 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001398 return (_dec_from_triple(sign, str(q), 0),
1399 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001400
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001401 # Here the quotient is too large to be representable
1402 ans = context._raise_error(DivisionImpossible,
1403 'quotient too large in //, % or divmod')
1404 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001405
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001406 def __rtruediv__(self, other, context=None):
1407 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001408 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001409 if other is NotImplemented:
1410 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001411 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001412
1413 def __divmod__(self, other, context=None):
1414 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001415 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001416 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001417 other = _convert_other(other)
1418 if other is NotImplemented:
1419 return other
1420
1421 if context is None:
1422 context = getcontext()
1423
1424 ans = self._check_nans(other, context)
1425 if ans:
1426 return (ans, ans)
1427
1428 sign = self._sign ^ other._sign
1429 if self._isinfinity():
1430 if other._isinfinity():
1431 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1432 return ans, ans
1433 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001434 return (_SignedInfinity[sign],
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001435 context._raise_error(InvalidOperation, 'INF % x'))
1436
1437 if not other:
1438 if not self:
1439 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1440 return ans, ans
1441 else:
1442 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1443 context._raise_error(InvalidOperation, 'x % 0'))
1444
1445 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001446 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001447 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001448
1449 def __rdivmod__(self, other, context=None):
1450 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001451 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001452 if other is NotImplemented:
1453 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001454 return other.__divmod__(self, context=context)
1455
1456 def __mod__(self, other, context=None):
1457 """
1458 self % other
1459 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001460 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001461 if other is NotImplemented:
1462 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001463
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001464 if context is None:
1465 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001466
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001467 ans = self._check_nans(other, context)
1468 if ans:
1469 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001470
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001471 if self._isinfinity():
1472 return context._raise_error(InvalidOperation, 'INF % x')
1473 elif not other:
1474 if self:
1475 return context._raise_error(InvalidOperation, 'x % 0')
1476 else:
1477 return context._raise_error(DivisionUndefined, '0 % 0')
1478
1479 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001480 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001481 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001482
1483 def __rmod__(self, other, context=None):
1484 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001485 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001486 if other is NotImplemented:
1487 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001488 return other.__mod__(self, context=context)
1489
1490 def remainder_near(self, other, context=None):
1491 """
1492 Remainder nearest to 0- abs(remainder-near) <= other/2
1493 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001494 if context is None:
1495 context = getcontext()
1496
1497 other = _convert_other(other, raiseit=True)
1498
1499 ans = self._check_nans(other, context)
1500 if ans:
1501 return ans
1502
1503 # self == +/-infinity -> InvalidOperation
1504 if self._isinfinity():
1505 return context._raise_error(InvalidOperation,
1506 'remainder_near(infinity, x)')
1507
1508 # other == 0 -> either InvalidOperation or DivisionUndefined
1509 if not other:
1510 if self:
1511 return context._raise_error(InvalidOperation,
1512 'remainder_near(x, 0)')
1513 else:
1514 return context._raise_error(DivisionUndefined,
1515 'remainder_near(0, 0)')
1516
1517 # other = +/-infinity -> remainder = self
1518 if other._isinfinity():
1519 ans = Decimal(self)
1520 return ans._fix(context)
1521
1522 # self = 0 -> remainder = self, with ideal exponent
1523 ideal_exponent = min(self._exp, other._exp)
1524 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001525 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001526 return ans._fix(context)
1527
1528 # catch most cases of large or small quotient
1529 expdiff = self.adjusted() - other.adjusted()
1530 if expdiff >= context.prec + 1:
1531 # expdiff >= prec+1 => abs(self/other) > 10**prec
1532 return context._raise_error(DivisionImpossible)
1533 if expdiff <= -2:
1534 # expdiff <= -2 => abs(self/other) < 0.1
1535 ans = self._rescale(ideal_exponent, context.rounding)
1536 return ans._fix(context)
1537
1538 # adjust both arguments to have the same exponent, then divide
1539 op1 = _WorkRep(self)
1540 op2 = _WorkRep(other)
1541 if op1.exp >= op2.exp:
1542 op1.int *= 10**(op1.exp - op2.exp)
1543 else:
1544 op2.int *= 10**(op2.exp - op1.exp)
1545 q, r = divmod(op1.int, op2.int)
1546 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1547 # 10**ideal_exponent. Apply correction to ensure that
1548 # abs(remainder) <= abs(other)/2
1549 if 2*r + (q&1) > op2.int:
1550 r -= op2.int
1551 q += 1
1552
1553 if q >= 10**context.prec:
1554 return context._raise_error(DivisionImpossible)
1555
1556 # result has same sign as self unless r is negative
1557 sign = self._sign
1558 if r < 0:
1559 sign = 1-sign
1560 r = -r
1561
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001562 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001563 return ans._fix(context)
1564
1565 def __floordiv__(self, other, context=None):
1566 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001567 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001568 if other is NotImplemented:
1569 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001570
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001571 if context is None:
1572 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001573
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001574 ans = self._check_nans(other, context)
1575 if ans:
1576 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001577
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001578 if self._isinfinity():
1579 if other._isinfinity():
1580 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001581 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001582 return _SignedInfinity[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001583
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001584 if not other:
1585 if self:
1586 return context._raise_error(DivisionByZero, 'x // 0',
1587 self._sign ^ other._sign)
1588 else:
1589 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001590
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001591 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001592
1593 def __rfloordiv__(self, other, context=None):
1594 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001595 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001596 if other is NotImplemented:
1597 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001598 return other.__floordiv__(self, context=context)
1599
1600 def __float__(self):
1601 """Float representation."""
Mark Dickinsonfc33d4c2012-08-24 18:53:10 +01001602 if self._isnan():
1603 if self.is_snan():
1604 raise ValueError("Cannot convert signaling NaN to float")
1605 s = "-nan" if self._sign else "nan"
1606 else:
1607 s = str(self)
1608 return float(s)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001609
1610 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001611 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001612 if self._is_special:
1613 if self._isnan():
Mark Dickinson825fce32009-09-07 18:08:12 +00001614 raise ValueError("Cannot convert NaN to integer")
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001615 elif self._isinfinity():
Mark Dickinson825fce32009-09-07 18:08:12 +00001616 raise OverflowError("Cannot convert infinity to integer")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001617 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001618 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001619 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001620 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001621 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001622
Christian Heimes969fe572008-01-25 11:23:10 +00001623 __trunc__ = __int__
1624
Christian Heimes0bd4e112008-02-12 22:59:25 +00001625 def real(self):
1626 return self
Mark Dickinson315a20a2009-01-04 21:34:18 +00001627 real = property(real)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001628
Christian Heimes0bd4e112008-02-12 22:59:25 +00001629 def imag(self):
1630 return Decimal(0)
Mark Dickinson315a20a2009-01-04 21:34:18 +00001631 imag = property(imag)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001632
1633 def conjugate(self):
1634 return self
1635
1636 def __complex__(self):
1637 return complex(float(self))
1638
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001639 def _fix_nan(self, context):
1640 """Decapitate the payload of a NaN to fit the context"""
1641 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001642
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001643 # maximum length of payload is precision if clamp=0,
1644 # precision-1 if clamp=1.
1645 max_payload_len = context.prec - context.clamp
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001646 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001647 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1648 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001649 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001650
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001651 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001652 """Round if it is necessary to keep self within prec precision.
1653
1654 Rounds and fixes the exponent. Does not raise on a sNaN.
1655
1656 Arguments:
1657 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001658 context - context used.
1659 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001660
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001661 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001662 if self._isnan():
1663 # decapitate payload if necessary
1664 return self._fix_nan(context)
1665 else:
1666 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001667 return Decimal(self)
1668
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001669 # if self is zero then exponent should be between Etiny and
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001670 # Emax if clamp==0, and between Etiny and Etop if clamp==1.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001671 Etiny = context.Etiny()
1672 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001673 if not self:
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001674 exp_max = [context.Emax, Etop][context.clamp]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001675 new_exp = min(max(self._exp, Etiny), exp_max)
1676 if new_exp != self._exp:
1677 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001678 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001679 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001680 return Decimal(self)
1681
1682 # exp_min is the smallest allowable exponent of the result,
1683 # equal to max(self.adjusted()-context.prec+1, Etiny)
1684 exp_min = len(self._int) + self._exp - context.prec
1685 if exp_min > Etop:
1686 # overflow: exp_min > Etop iff self.adjusted() > Emax
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001687 ans = context._raise_error(Overflow, 'above Emax', self._sign)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001688 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001689 context._raise_error(Rounded)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001690 return ans
1691
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001692 self_is_subnormal = exp_min < Etiny
1693 if self_is_subnormal:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001694 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001695
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001696 # round if self has too many digits
1697 if self._exp < exp_min:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001698 digits = len(self._int) + self._exp - exp_min
1699 if digits < 0:
1700 self = _dec_from_triple(self._sign, '1', exp_min-1)
1701 digits = 0
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001702 rounding_method = self._pick_rounding_function[context.rounding]
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04001703 changed = rounding_method(self, digits)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001704 coeff = self._int[:digits] or '0'
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001705 if changed > 0:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001706 coeff = str(int(coeff)+1)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001707 if len(coeff) > context.prec:
1708 coeff = coeff[:-1]
1709 exp_min += 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001710
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001711 # check whether the rounding pushed the exponent out of range
1712 if exp_min > Etop:
1713 ans = context._raise_error(Overflow, 'above Emax', self._sign)
1714 else:
1715 ans = _dec_from_triple(self._sign, coeff, exp_min)
1716
1717 # raise the appropriate signals, taking care to respect
1718 # the precedence described in the specification
1719 if changed and self_is_subnormal:
1720 context._raise_error(Underflow)
1721 if self_is_subnormal:
1722 context._raise_error(Subnormal)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001723 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001724 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001725 context._raise_error(Rounded)
1726 if not ans:
1727 # raise Clamped on underflow to 0
1728 context._raise_error(Clamped)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001729 return ans
1730
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001731 if self_is_subnormal:
1732 context._raise_error(Subnormal)
1733
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001734 # fold down if clamp == 1 and self has too few digits
1735 if context.clamp == 1 and self._exp > Etop:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001736 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001737 self_padded = self._int + '0'*(self._exp - Etop)
1738 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001739
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001740 # here self was representable to begin with; return unchanged
1741 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001742
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001743 # for each of the rounding functions below:
1744 # self is a finite, nonzero Decimal
1745 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001746 #
1747 # each function returns either -1, 0, or 1, as follows:
1748 # 1 indicates that self should be rounded up (away from zero)
1749 # 0 indicates that self should be truncated, and that all the
1750 # digits to be truncated are zeros (so the value is unchanged)
1751 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001752
1753 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001754 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001755 if _all_zeros(self._int, prec):
1756 return 0
1757 else:
1758 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001759
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001760 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001761 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001762 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001763
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001764 def _round_half_up(self, prec):
1765 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001766 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001767 return 1
1768 elif _all_zeros(self._int, prec):
1769 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001770 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001771 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001772
1773 def _round_half_down(self, prec):
1774 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001775 if _exact_half(self._int, prec):
1776 return -1
1777 else:
1778 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001779
1780 def _round_half_even(self, prec):
1781 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001782 if _exact_half(self._int, prec) and \
1783 (prec == 0 or self._int[prec-1] in '02468'):
1784 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001785 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001786 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001787
1788 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001789 """Rounds up (not away from 0 if negative.)"""
1790 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001791 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001792 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001793 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001794
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001795 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001796 """Rounds down (not towards 0 if negative)"""
1797 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001798 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001799 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001800 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001801
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001802 def _round_05up(self, prec):
1803 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001804 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001805 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001806 else:
1807 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001808
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04001809 _pick_rounding_function = dict(
1810 ROUND_DOWN = _round_down,
1811 ROUND_UP = _round_up,
1812 ROUND_HALF_UP = _round_half_up,
1813 ROUND_HALF_DOWN = _round_half_down,
1814 ROUND_HALF_EVEN = _round_half_even,
1815 ROUND_CEILING = _round_ceiling,
1816 ROUND_FLOOR = _round_floor,
1817 ROUND_05UP = _round_05up,
1818 )
1819
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001820 def __round__(self, n=None):
1821 """Round self to the nearest integer, or to a given precision.
1822
1823 If only one argument is supplied, round a finite Decimal
1824 instance self to the nearest integer. If self is infinite or
1825 a NaN then a Python exception is raised. If self is finite
1826 and lies exactly halfway between two integers then it is
1827 rounded to the integer with even last digit.
1828
1829 >>> round(Decimal('123.456'))
1830 123
1831 >>> round(Decimal('-456.789'))
1832 -457
1833 >>> round(Decimal('-3.0'))
1834 -3
1835 >>> round(Decimal('2.5'))
1836 2
1837 >>> round(Decimal('3.5'))
1838 4
1839 >>> round(Decimal('Inf'))
1840 Traceback (most recent call last):
1841 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001842 OverflowError: cannot round an infinity
1843 >>> round(Decimal('NaN'))
1844 Traceback (most recent call last):
1845 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001846 ValueError: cannot round a NaN
1847
1848 If a second argument n is supplied, self is rounded to n
1849 decimal places using the rounding mode for the current
1850 context.
1851
1852 For an integer n, round(self, -n) is exactly equivalent to
1853 self.quantize(Decimal('1En')).
1854
1855 >>> round(Decimal('123.456'), 0)
1856 Decimal('123')
1857 >>> round(Decimal('123.456'), 2)
1858 Decimal('123.46')
1859 >>> round(Decimal('123.456'), -2)
1860 Decimal('1E+2')
1861 >>> round(Decimal('-Infinity'), 37)
1862 Decimal('NaN')
1863 >>> round(Decimal('sNaN123'), 0)
1864 Decimal('NaN123')
1865
1866 """
1867 if n is not None:
1868 # two-argument form: use the equivalent quantize call
1869 if not isinstance(n, int):
1870 raise TypeError('Second argument to round should be integral')
1871 exp = _dec_from_triple(0, '1', -n)
1872 return self.quantize(exp)
1873
1874 # one-argument form
1875 if self._is_special:
1876 if self.is_nan():
1877 raise ValueError("cannot round a NaN")
1878 else:
1879 raise OverflowError("cannot round an infinity")
1880 return int(self._rescale(0, ROUND_HALF_EVEN))
1881
1882 def __floor__(self):
1883 """Return the floor of self, as an integer.
1884
1885 For a finite Decimal instance self, return the greatest
1886 integer n such that n <= self. If self is infinite or a NaN
1887 then a Python exception is raised.
1888
1889 """
1890 if self._is_special:
1891 if self.is_nan():
1892 raise ValueError("cannot round a NaN")
1893 else:
1894 raise OverflowError("cannot round an infinity")
1895 return int(self._rescale(0, ROUND_FLOOR))
1896
1897 def __ceil__(self):
1898 """Return the ceiling of self, as an integer.
1899
1900 For a finite Decimal instance self, return the least integer n
1901 such that n >= self. If self is infinite or a NaN then a
1902 Python exception is raised.
1903
1904 """
1905 if self._is_special:
1906 if self.is_nan():
1907 raise ValueError("cannot round a NaN")
1908 else:
1909 raise OverflowError("cannot round an infinity")
1910 return int(self._rescale(0, ROUND_CEILING))
1911
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001912 def fma(self, other, third, context=None):
1913 """Fused multiply-add.
1914
1915 Returns self*other+third with no rounding of the intermediate
1916 product self*other.
1917
1918 self and other are multiplied together, with no rounding of
1919 the result. The third operand is then added to the result,
1920 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001921 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001922
1923 other = _convert_other(other, raiseit=True)
Mark Dickinsonb455e582011-05-22 12:53:18 +01001924 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001925
1926 # compute product; raise InvalidOperation if either operand is
1927 # a signaling NaN or if the product is zero times infinity.
1928 if self._is_special or other._is_special:
1929 if context is None:
1930 context = getcontext()
1931 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001932 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001933 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001934 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001935 if self._exp == 'n':
1936 product = self
1937 elif other._exp == 'n':
1938 product = other
1939 elif self._exp == 'F':
1940 if not other:
1941 return context._raise_error(InvalidOperation,
1942 'INF * 0 in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001943 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001944 elif other._exp == 'F':
1945 if not self:
1946 return context._raise_error(InvalidOperation,
1947 '0 * INF in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001948 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001949 else:
1950 product = _dec_from_triple(self._sign ^ other._sign,
1951 str(int(self._int) * int(other._int)),
1952 self._exp + other._exp)
1953
Christian Heimes8b0facf2007-12-04 19:30:01 +00001954 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001955
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001956 def _power_modulo(self, other, modulo, context=None):
1957 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001958
Stefan Krah1919b7e2012-03-21 18:25:23 +01001959 other = _convert_other(other)
1960 if other is NotImplemented:
1961 return other
1962 modulo = _convert_other(modulo)
1963 if modulo is NotImplemented:
1964 return modulo
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001965
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001966 if context is None:
1967 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001968
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001969 # deal with NaNs: if there are any sNaNs then first one wins,
1970 # (i.e. behaviour for NaNs is identical to that of fma)
1971 self_is_nan = self._isnan()
1972 other_is_nan = other._isnan()
1973 modulo_is_nan = modulo._isnan()
1974 if self_is_nan or other_is_nan or modulo_is_nan:
1975 if self_is_nan == 2:
1976 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001977 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001978 if other_is_nan == 2:
1979 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001980 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001981 if modulo_is_nan == 2:
1982 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001983 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001984 if self_is_nan:
1985 return self._fix_nan(context)
1986 if other_is_nan:
1987 return other._fix_nan(context)
1988 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001989
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001990 # check inputs: we apply same restrictions as Python's pow()
1991 if not (self._isinteger() and
1992 other._isinteger() and
1993 modulo._isinteger()):
1994 return context._raise_error(InvalidOperation,
1995 'pow() 3rd argument not allowed '
1996 'unless all arguments are integers')
1997 if other < 0:
1998 return context._raise_error(InvalidOperation,
1999 'pow() 2nd argument cannot be '
2000 'negative when 3rd argument specified')
2001 if not modulo:
2002 return context._raise_error(InvalidOperation,
2003 'pow() 3rd argument cannot be 0')
2004
2005 # additional restriction for decimal: the modulus must be less
2006 # than 10**prec in absolute value
2007 if modulo.adjusted() >= context.prec:
2008 return context._raise_error(InvalidOperation,
2009 'insufficient precision: pow() 3rd '
2010 'argument must not have more than '
2011 'precision digits')
2012
2013 # define 0**0 == NaN, for consistency with two-argument pow
2014 # (even though it hurts!)
2015 if not other and not self:
2016 return context._raise_error(InvalidOperation,
2017 'at least one of pow() 1st argument '
2018 'and 2nd argument must be nonzero ;'
2019 '0**0 is not defined')
2020
2021 # compute sign of result
2022 if other._iseven():
2023 sign = 0
2024 else:
2025 sign = self._sign
2026
2027 # convert modulo to a Python integer, and self and other to
2028 # Decimal integers (i.e. force their exponents to be >= 0)
2029 modulo = abs(int(modulo))
2030 base = _WorkRep(self.to_integral_value())
2031 exponent = _WorkRep(other.to_integral_value())
2032
2033 # compute result using integer pow()
2034 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
2035 for i in range(exponent.exp):
2036 base = pow(base, 10, modulo)
2037 base = pow(base, exponent.int, modulo)
2038
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002039 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002040
2041 def _power_exact(self, other, p):
2042 """Attempt to compute self**other exactly.
2043
2044 Given Decimals self and other and an integer p, attempt to
2045 compute an exact result for the power self**other, with p
2046 digits of precision. Return None if self**other is not
2047 exactly representable in p digits.
2048
2049 Assumes that elimination of special cases has already been
2050 performed: self and other must both be nonspecial; self must
2051 be positive and not numerically equal to 1; other must be
2052 nonzero. For efficiency, other._exp should not be too large,
2053 so that 10**abs(other._exp) is a feasible calculation."""
2054
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002055 # In the comments below, we write x for the value of self and y for the
2056 # value of other. Write x = xc*10**xe and abs(y) = yc*10**ye, with xc
2057 # and yc positive integers not divisible by 10.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002058
2059 # The main purpose of this method is to identify the *failure*
2060 # of x**y to be exactly representable with as little effort as
2061 # possible. So we look for cheap and easy tests that
2062 # eliminate the possibility of x**y being exact. Only if all
2063 # these tests are passed do we go on to actually compute x**y.
2064
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002065 # Here's the main idea. Express y as a rational number m/n, with m and
2066 # n relatively prime and n>0. Then for x**y to be exactly
2067 # representable (at *any* precision), xc must be the nth power of a
2068 # positive integer and xe must be divisible by n. If y is negative
2069 # then additionally xc must be a power of either 2 or 5, hence a power
2070 # of 2**n or 5**n.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002071 #
2072 # There's a limit to how small |y| can be: if y=m/n as above
2073 # then:
2074 #
2075 # (1) if xc != 1 then for the result to be representable we
2076 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
2077 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
2078 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
2079 # representable.
2080 #
2081 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
2082 # |y| < 1/|xe| then the result is not representable.
2083 #
2084 # Note that since x is not equal to 1, at least one of (1) and
2085 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
2086 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
2087 #
2088 # There's also a limit to how large y can be, at least if it's
2089 # positive: the normalized result will have coefficient xc**y,
2090 # so if it's representable then xc**y < 10**p, and y <
2091 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
2092 # not exactly representable.
2093
2094 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
2095 # so |y| < 1/xe and the result is not representable.
2096 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
2097 # < 1/nbits(xc).
2098
2099 x = _WorkRep(self)
2100 xc, xe = x.int, x.exp
2101 while xc % 10 == 0:
2102 xc //= 10
2103 xe += 1
2104
2105 y = _WorkRep(other)
2106 yc, ye = y.int, y.exp
2107 while yc % 10 == 0:
2108 yc //= 10
2109 ye += 1
2110
2111 # case where xc == 1: result is 10**(xe*y), with xe*y
2112 # required to be an integer
2113 if xc == 1:
Mark Dickinsona1236312010-07-08 19:03:34 +00002114 xe *= yc
2115 # result is now 10**(xe * 10**ye); xe * 10**ye must be integral
2116 while xe % 10 == 0:
2117 xe //= 10
2118 ye += 1
2119 if ye < 0:
2120 return None
2121 exponent = xe * 10**ye
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002122 if y.sign == 1:
2123 exponent = -exponent
2124 # if other is a nonnegative integer, use ideal exponent
2125 if other._isinteger() and other._sign == 0:
2126 ideal_exponent = self._exp*int(other)
2127 zeros = min(exponent-ideal_exponent, p-1)
2128 else:
2129 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002130 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002131
2132 # case where y is negative: xc must be either a power
2133 # of 2 or a power of 5.
2134 if y.sign == 1:
2135 last_digit = xc % 10
2136 if last_digit in (2,4,6,8):
2137 # quick test for power of 2
2138 if xc & -xc != xc:
2139 return None
2140 # now xc is a power of 2; e is its exponent
2141 e = _nbits(xc)-1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002142
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002143 # We now have:
2144 #
2145 # x = 2**e * 10**xe, e > 0, and y < 0.
2146 #
2147 # The exact result is:
2148 #
2149 # x**y = 5**(-e*y) * 10**(e*y + xe*y)
2150 #
2151 # provided that both e*y and xe*y are integers. Note that if
2152 # 5**(-e*y) >= 10**p, then the result can't be expressed
2153 # exactly with p digits of precision.
2154 #
2155 # Using the above, we can guard against large values of ye.
2156 # 93/65 is an upper bound for log(10)/log(5), so if
2157 #
2158 # ye >= len(str(93*p//65))
2159 #
2160 # then
2161 #
2162 # -e*y >= -y >= 10**ye > 93*p/65 > p*log(10)/log(5),
2163 #
2164 # so 5**(-e*y) >= 10**p, and the coefficient of the result
2165 # can't be expressed in p digits.
2166
2167 # emax >= largest e such that 5**e < 10**p.
2168 emax = p*93//65
2169 if ye >= len(str(emax)):
2170 return None
2171
2172 # Find -e*y and -xe*y; both must be integers
2173 e = _decimal_lshift_exact(e * yc, ye)
2174 xe = _decimal_lshift_exact(xe * yc, ye)
2175 if e is None or xe is None:
2176 return None
2177
2178 if e > emax:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002179 return None
2180 xc = 5**e
2181
2182 elif last_digit == 5:
2183 # e >= log_5(xc) if xc is a power of 5; we have
2184 # equality all the way up to xc=5**2658
2185 e = _nbits(xc)*28//65
2186 xc, remainder = divmod(5**e, xc)
2187 if remainder:
2188 return None
2189 while xc % 5 == 0:
2190 xc //= 5
2191 e -= 1
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002192
2193 # Guard against large values of ye, using the same logic as in
2194 # the 'xc is a power of 2' branch. 10/3 is an upper bound for
2195 # log(10)/log(2).
2196 emax = p*10//3
2197 if ye >= len(str(emax)):
2198 return None
2199
2200 e = _decimal_lshift_exact(e * yc, ye)
2201 xe = _decimal_lshift_exact(xe * yc, ye)
2202 if e is None or xe is None:
2203 return None
2204
2205 if e > emax:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002206 return None
2207 xc = 2**e
2208 else:
2209 return None
2210
2211 if xc >= 10**p:
2212 return None
2213 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002214 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002215
2216 # now y is positive; find m and n such that y = m/n
2217 if ye >= 0:
2218 m, n = yc*10**ye, 1
2219 else:
2220 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2221 return None
2222 xc_bits = _nbits(xc)
2223 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2224 return None
2225 m, n = yc, 10**(-ye)
2226 while m % 2 == n % 2 == 0:
2227 m //= 2
2228 n //= 2
2229 while m % 5 == n % 5 == 0:
2230 m //= 5
2231 n //= 5
2232
2233 # compute nth root of xc*10**xe
2234 if n > 1:
2235 # if 1 < xc < 2**n then xc isn't an nth power
2236 if xc != 1 and xc_bits <= n:
2237 return None
2238
2239 xe, rem = divmod(xe, n)
2240 if rem != 0:
2241 return None
2242
2243 # compute nth root of xc using Newton's method
2244 a = 1 << -(-_nbits(xc)//n) # initial estimate
2245 while True:
2246 q, r = divmod(xc, a**(n-1))
2247 if a <= q:
2248 break
2249 else:
2250 a = (a*(n-1) + q)//n
2251 if not (a == q and r == 0):
2252 return None
2253 xc = a
2254
2255 # now xc*10**xe is the nth root of the original xc*10**xe
2256 # compute mth power of xc*10**xe
2257
2258 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2259 # 10**p and the result is not representable.
2260 if xc > 1 and m > p*100//_log10_lb(xc):
2261 return None
2262 xc = xc**m
2263 xe *= m
2264 if xc > 10**p:
2265 return None
2266
2267 # by this point the result *is* exactly representable
2268 # adjust the exponent to get as close as possible to the ideal
2269 # exponent, if necessary
2270 str_xc = str(xc)
2271 if other._isinteger() and other._sign == 0:
2272 ideal_exponent = self._exp*int(other)
2273 zeros = min(xe-ideal_exponent, p-len(str_xc))
2274 else:
2275 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002276 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002277
2278 def __pow__(self, other, modulo=None, context=None):
2279 """Return self ** other [ % modulo].
2280
2281 With two arguments, compute self**other.
2282
2283 With three arguments, compute (self**other) % modulo. For the
2284 three argument form, the following restrictions on the
2285 arguments hold:
2286
2287 - all three arguments must be integral
2288 - other must be nonnegative
2289 - either self or other (or both) must be nonzero
2290 - modulo must be nonzero and must have at most p digits,
2291 where p is the context precision.
2292
2293 If any of these restrictions is violated the InvalidOperation
2294 flag is raised.
2295
2296 The result of pow(self, other, modulo) is identical to the
2297 result that would be obtained by computing (self**other) %
2298 modulo with unbounded precision, but is computed more
2299 efficiently. It is always exact.
2300 """
2301
2302 if modulo is not None:
2303 return self._power_modulo(other, modulo, context)
2304
2305 other = _convert_other(other)
2306 if other is NotImplemented:
2307 return other
2308
2309 if context is None:
2310 context = getcontext()
2311
2312 # either argument is a NaN => result is NaN
2313 ans = self._check_nans(other, context)
2314 if ans:
2315 return ans
2316
2317 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2318 if not other:
2319 if not self:
2320 return context._raise_error(InvalidOperation, '0 ** 0')
2321 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002322 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002323
2324 # result has sign 1 iff self._sign is 1 and other is an odd integer
2325 result_sign = 0
2326 if self._sign == 1:
2327 if other._isinteger():
2328 if not other._iseven():
2329 result_sign = 1
2330 else:
2331 # -ve**noninteger = NaN
2332 # (-0)**noninteger = 0**noninteger
2333 if self:
2334 return context._raise_error(InvalidOperation,
2335 'x ** y with x negative and y not an integer')
2336 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002337 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002338
2339 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2340 if not self:
2341 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002342 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002343 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002344 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002345
2346 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002347 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002348 if other._sign == 0:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002349 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002350 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002351 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002352
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002353 # 1**other = 1, but the choice of exponent and the flags
2354 # depend on the exponent of self, and on whether other is a
2355 # positive integer, a negative integer, or neither
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002356 if self == _One:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002357 if other._isinteger():
2358 # exp = max(self._exp*max(int(other), 0),
2359 # 1-context.prec) but evaluating int(other) directly
2360 # is dangerous until we know other is small (other
2361 # could be 1e999999999)
2362 if other._sign == 1:
2363 multiplier = 0
2364 elif other > context.prec:
2365 multiplier = context.prec
2366 else:
2367 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002368
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002369 exp = self._exp * multiplier
2370 if exp < 1-context.prec:
2371 exp = 1-context.prec
2372 context._raise_error(Rounded)
2373 else:
2374 context._raise_error(Inexact)
2375 context._raise_error(Rounded)
2376 exp = 1-context.prec
2377
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002378 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002379
2380 # compute adjusted exponent of self
2381 self_adj = self.adjusted()
2382
2383 # self ** infinity is infinity if self > 1, 0 if self < 1
2384 # self ** -infinity is infinity if self < 1, 0 if self > 1
2385 if other._isinfinity():
2386 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002387 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002388 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002389 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002390
2391 # from here on, the result always goes through the call
2392 # to _fix at the end of this function.
2393 ans = None
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002394 exact = False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002395
2396 # crude test to catch cases of extreme overflow/underflow. If
2397 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2398 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2399 # self**other >= 10**(Emax+1), so overflow occurs. The test
2400 # for underflow is similar.
2401 bound = self._log10_exp_bound() + other.adjusted()
2402 if (self_adj >= 0) == (other._sign == 0):
2403 # self > 1 and other +ve, or self < 1 and other -ve
2404 # possibility of overflow
2405 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002406 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002407 else:
2408 # self > 1 and other -ve, or self < 1 and other +ve
2409 # possibility of underflow to 0
2410 Etiny = context.Etiny()
2411 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002412 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002413
2414 # try for an exact result with precision +1
2415 if ans is None:
2416 ans = self._power_exact(other, context.prec + 1)
Mark Dickinsone42f1bb2010-07-08 19:09:16 +00002417 if ans is not None:
2418 if result_sign == 1:
2419 ans = _dec_from_triple(1, ans._int, ans._exp)
2420 exact = True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002421
2422 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2423 if ans is None:
2424 p = context.prec
2425 x = _WorkRep(self)
2426 xc, xe = x.int, x.exp
2427 y = _WorkRep(other)
2428 yc, ye = y.int, y.exp
2429 if y.sign == 1:
2430 yc = -yc
2431
2432 # compute correctly rounded result: start with precision +3,
2433 # then increase precision until result is unambiguously roundable
2434 extra = 3
2435 while True:
2436 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2437 if coeff % (5*10**(len(str(coeff))-p-1)):
2438 break
2439 extra += 3
2440
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002441 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002442
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002443 # unlike exp, ln and log10, the power function respects the
2444 # rounding mode; no need to switch to ROUND_HALF_EVEN here
2445
2446 # There's a difficulty here when 'other' is not an integer and
2447 # the result is exact. In this case, the specification
2448 # requires that the Inexact flag be raised (in spite of
2449 # exactness), but since the result is exact _fix won't do this
2450 # for us. (Correspondingly, the Underflow signal should also
2451 # be raised for subnormal results.) We can't directly raise
2452 # these signals either before or after calling _fix, since
2453 # that would violate the precedence for signals. So we wrap
2454 # the ._fix call in a temporary context, and reraise
2455 # afterwards.
2456 if exact and not other._isinteger():
2457 # pad with zeros up to length context.prec+1 if necessary; this
2458 # ensures that the Rounded signal will be raised.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002459 if len(ans._int) <= context.prec:
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002460 expdiff = context.prec + 1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002461 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2462 ans._exp-expdiff)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002463
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002464 # create a copy of the current context, with cleared flags/traps
2465 newcontext = context.copy()
2466 newcontext.clear_flags()
2467 for exception in _signals:
2468 newcontext.traps[exception] = 0
2469
2470 # round in the new context
2471 ans = ans._fix(newcontext)
2472
2473 # raise Inexact, and if necessary, Underflow
2474 newcontext._raise_error(Inexact)
2475 if newcontext.flags[Subnormal]:
2476 newcontext._raise_error(Underflow)
2477
2478 # propagate signals to the original context; _fix could
2479 # have raised any of Overflow, Underflow, Subnormal,
2480 # Inexact, Rounded, Clamped. Overflow needs the correct
2481 # arguments. Note that the order of the exceptions is
2482 # important here.
2483 if newcontext.flags[Overflow]:
2484 context._raise_error(Overflow, 'above Emax', ans._sign)
2485 for exception in Underflow, Subnormal, Inexact, Rounded, Clamped:
2486 if newcontext.flags[exception]:
2487 context._raise_error(exception)
2488
2489 else:
2490 ans = ans._fix(context)
2491
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002492 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002493
2494 def __rpow__(self, other, context=None):
2495 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002496 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002497 if other is NotImplemented:
2498 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002499 return other.__pow__(self, context=context)
2500
2501 def normalize(self, context=None):
2502 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002503
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002504 if context is None:
2505 context = getcontext()
2506
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002507 if self._is_special:
2508 ans = self._check_nans(context=context)
2509 if ans:
2510 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002511
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002512 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002513 if dup._isinfinity():
2514 return dup
2515
2516 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002517 return _dec_from_triple(dup._sign, '0', 0)
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00002518 exp_max = [context.Emax, context.Etop()][context.clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002519 end = len(dup._int)
2520 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002521 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002522 exp += 1
2523 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002524 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002525
Stefan Krahb151f8f2014-04-30 19:15:38 +02002526 def quantize(self, exp, rounding=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002527 """Quantize self so its exponent is the same as that of exp.
2528
2529 Similar to self._rescale(exp._exp) but with error checking.
2530 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002531 exp = _convert_other(exp, raiseit=True)
2532
2533 if context is None:
2534 context = getcontext()
2535 if rounding is None:
2536 rounding = context.rounding
2537
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002538 if self._is_special or exp._is_special:
2539 ans = self._check_nans(exp, context)
2540 if ans:
2541 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002542
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002543 if exp._isinfinity() or self._isinfinity():
2544 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002545 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002546 return context._raise_error(InvalidOperation,
2547 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002548
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002549 # exp._exp should be between Etiny and Emax
2550 if not (context.Etiny() <= exp._exp <= context.Emax):
2551 return context._raise_error(InvalidOperation,
2552 'target exponent out of bounds in quantize')
2553
2554 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002555 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002556 return ans._fix(context)
2557
2558 self_adjusted = self.adjusted()
2559 if self_adjusted > context.Emax:
2560 return context._raise_error(InvalidOperation,
2561 'exponent of quantize result too large for current context')
2562 if self_adjusted - exp._exp + 1 > context.prec:
2563 return context._raise_error(InvalidOperation,
2564 'quantize result has too many digits for current context')
2565
2566 ans = self._rescale(exp._exp, rounding)
2567 if ans.adjusted() > context.Emax:
2568 return context._raise_error(InvalidOperation,
2569 'exponent of quantize result too large for current context')
2570 if len(ans._int) > context.prec:
2571 return context._raise_error(InvalidOperation,
2572 'quantize result has too many digits for current context')
2573
2574 # raise appropriate flags
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002575 if ans and ans.adjusted() < context.Emin:
2576 context._raise_error(Subnormal)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002577 if ans._exp > self._exp:
2578 if ans != self:
2579 context._raise_error(Inexact)
2580 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002581
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002582 # call to fix takes care of any necessary folddown, and
2583 # signals Clamped if necessary
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002584 ans = ans._fix(context)
2585 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002586
Stefan Krah040e3112012-12-15 22:33:33 +01002587 def same_quantum(self, other, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002588 """Return True if self and other have the same exponent; otherwise
2589 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002590
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002591 If either operand is a special value, the following rules are used:
2592 * return True if both operands are infinities
2593 * return True if both operands are NaNs
2594 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002595 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002596 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002597 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002598 return (self.is_nan() and other.is_nan() or
2599 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002600 return self._exp == other._exp
2601
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002602 def _rescale(self, exp, rounding):
2603 """Rescale self so that the exponent is exp, either by padding with zeros
2604 or by truncating digits, using the given rounding mode.
2605
2606 Specials are returned without change. This operation is
2607 quiet: it raises no flags, and uses no information from the
2608 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002609
2610 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002611 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002612 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002613 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002614 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002615 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002616 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002617
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002618 if self._exp >= exp:
2619 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002620 return _dec_from_triple(self._sign,
2621 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002622
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002623 # too many digits; round and lose data. If self.adjusted() <
2624 # exp-1, replace self by 10**(exp-1) before rounding
2625 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002626 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002627 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002628 digits = 0
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04002629 this_function = self._pick_rounding_function[rounding]
2630 changed = this_function(self, digits)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002631 coeff = self._int[:digits] or '0'
2632 if changed == 1:
2633 coeff = str(int(coeff)+1)
2634 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002635
Christian Heimesf16baeb2008-02-29 14:57:44 +00002636 def _round(self, places, rounding):
2637 """Round a nonzero, nonspecial Decimal to a fixed number of
2638 significant figures, using the given rounding mode.
2639
2640 Infinities, NaNs and zeros are returned unaltered.
2641
2642 This operation is quiet: it raises no flags, and uses no
2643 information from the context.
2644
2645 """
2646 if places <= 0:
2647 raise ValueError("argument should be at least 1 in _round")
2648 if self._is_special or not self:
2649 return Decimal(self)
2650 ans = self._rescale(self.adjusted()+1-places, rounding)
2651 # it can happen that the rescale alters the adjusted exponent;
2652 # for example when rounding 99.97 to 3 significant figures.
2653 # When this happens we end up with an extra 0 at the end of
2654 # the number; a second rescale fixes this.
2655 if ans.adjusted() != self.adjusted():
2656 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2657 return ans
2658
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002659 def to_integral_exact(self, rounding=None, context=None):
2660 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002661
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002662 If no rounding mode is specified, take the rounding mode from
2663 the context. This method raises the Rounded and Inexact flags
2664 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002665
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002666 See also: to_integral_value, which does exactly the same as
2667 this method except that it doesn't raise Inexact or Rounded.
2668 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002669 if self._is_special:
2670 ans = self._check_nans(context=context)
2671 if ans:
2672 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002673 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002674 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002675 return Decimal(self)
2676 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002677 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002678 if context is None:
2679 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002680 if rounding is None:
2681 rounding = context.rounding
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002682 ans = self._rescale(0, rounding)
2683 if ans != self:
2684 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002685 context._raise_error(Rounded)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002686 return ans
2687
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002688 def to_integral_value(self, rounding=None, context=None):
2689 """Rounds to the nearest integer, without raising inexact, rounded."""
2690 if context is None:
2691 context = getcontext()
2692 if rounding is None:
2693 rounding = context.rounding
2694 if self._is_special:
2695 ans = self._check_nans(context=context)
2696 if ans:
2697 return ans
2698 return Decimal(self)
2699 if self._exp >= 0:
2700 return Decimal(self)
2701 else:
2702 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002703
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002704 # the method name changed, but we provide also the old one, for compatibility
2705 to_integral = to_integral_value
2706
2707 def sqrt(self, context=None):
2708 """Return the square root of self."""
Christian Heimes0348fb62008-03-26 12:55:56 +00002709 if context is None:
2710 context = getcontext()
2711
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002712 if self._is_special:
2713 ans = self._check_nans(context=context)
2714 if ans:
2715 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002716
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002717 if self._isinfinity() and self._sign == 0:
2718 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002719
2720 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002721 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002722 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002723 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002724
2725 if self._sign == 1:
2726 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2727
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002728 # At this point self represents a positive number. Let p be
2729 # the desired precision and express self in the form c*100**e
2730 # with c a positive real number and e an integer, c and e
2731 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2732 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2733 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2734 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2735 # the closest integer to sqrt(c) with the even integer chosen
2736 # in the case of a tie.
2737 #
2738 # To ensure correct rounding in all cases, we use the
2739 # following trick: we compute the square root to an extra
2740 # place (precision p+1 instead of precision p), rounding down.
2741 # Then, if the result is inexact and its last digit is 0 or 5,
2742 # we increase the last digit to 1 or 6 respectively; if it's
2743 # exact we leave the last digit alone. Now the final round to
2744 # p places (or fewer in the case of underflow) will round
2745 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002746
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002747 # use an extra digit of precision
2748 prec = context.prec+1
2749
2750 # write argument in the form c*100**e where e = self._exp//2
2751 # is the 'ideal' exponent, to be used if the square root is
2752 # exactly representable. l is the number of 'digits' of c in
2753 # base 100, so that 100**(l-1) <= c < 100**l.
2754 op = _WorkRep(self)
2755 e = op.exp >> 1
2756 if op.exp & 1:
2757 c = op.int * 10
2758 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002759 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002760 c = op.int
2761 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002762
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002763 # rescale so that c has exactly prec base 100 'digits'
2764 shift = prec-l
2765 if shift >= 0:
2766 c *= 100**shift
2767 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002768 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002769 c, remainder = divmod(c, 100**-shift)
2770 exact = not remainder
2771 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002772
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002773 # find n = floor(sqrt(c)) using Newton's method
2774 n = 10**prec
2775 while True:
2776 q = c//n
2777 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002778 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002779 else:
2780 n = n + q >> 1
2781 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002782
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002783 if exact:
2784 # result is exact; rescale to use ideal exponent e
2785 if shift >= 0:
2786 # assert n % 10**shift == 0
2787 n //= 10**shift
2788 else:
2789 n *= 10**-shift
2790 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002791 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002792 # result is not exact; fix last digit as described above
2793 if n % 5 == 0:
2794 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002795
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002796 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002797
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002798 # round, and fit to current context
2799 context = context._shallow_copy()
2800 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002801 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002802 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002803
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002804 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002805
2806 def max(self, other, context=None):
2807 """Returns the larger value.
2808
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002809 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002810 NaN (and signals if one is sNaN). Also rounds.
2811 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002812 other = _convert_other(other, raiseit=True)
2813
2814 if context is None:
2815 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002816
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002817 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002818 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002819 # number is always returned
2820 sn = self._isnan()
2821 on = other._isnan()
2822 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002823 if on == 1 and sn == 0:
2824 return self._fix(context)
2825 if sn == 1 and on == 0:
2826 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002827 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002828
Christian Heimes77c02eb2008-02-09 02:18:51 +00002829 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002830 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002831 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002832 # then an ordering is applied:
2833 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002834 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002835 # positive sign and min returns the operand with the negative sign
2836 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002837 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002838 # the result. This is exactly the ordering used in compare_total.
2839 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002840
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002841 if c == -1:
2842 ans = other
2843 else:
2844 ans = self
2845
Christian Heimes2c181612007-12-17 20:04:13 +00002846 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002847
2848 def min(self, other, context=None):
2849 """Returns the smaller value.
2850
Guido van Rossumd8faa362007-04-27 19:54:29 +00002851 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002852 NaN (and signals if one is sNaN). Also rounds.
2853 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002854 other = _convert_other(other, raiseit=True)
2855
2856 if context is None:
2857 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002858
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002859 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002860 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002861 # number is always returned
2862 sn = self._isnan()
2863 on = other._isnan()
2864 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002865 if on == 1 and sn == 0:
2866 return self._fix(context)
2867 if sn == 1 and on == 0:
2868 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002869 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002870
Christian Heimes77c02eb2008-02-09 02:18:51 +00002871 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002872 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002873 c = self.compare_total(other)
2874
2875 if c == -1:
2876 ans = self
2877 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002878 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002879
Christian Heimes2c181612007-12-17 20:04:13 +00002880 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002881
2882 def _isinteger(self):
2883 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002884 if self._is_special:
2885 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002886 if self._exp >= 0:
2887 return True
2888 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002889 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002890
2891 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002892 """Returns True if self is even. Assumes self is an integer."""
2893 if not self or self._exp > 0:
2894 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002895 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002896
2897 def adjusted(self):
2898 """Return the adjusted exponent of self"""
2899 try:
2900 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002901 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002902 except TypeError:
2903 return 0
2904
Stefan Krah040e3112012-12-15 22:33:33 +01002905 def canonical(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002906 """Returns the same Decimal object.
2907
2908 As we do not have different encodings for the same number, the
2909 received object already is in its canonical form.
2910 """
2911 return self
2912
2913 def compare_signal(self, other, context=None):
2914 """Compares self to the other operand numerically.
2915
2916 It's pretty much like compare(), but all NaNs signal, with signaling
2917 NaNs taking precedence over quiet NaNs.
2918 """
Christian Heimes77c02eb2008-02-09 02:18:51 +00002919 other = _convert_other(other, raiseit = True)
2920 ans = self._compare_check_nans(other, context)
2921 if ans:
2922 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002923 return self.compare(other, context=context)
2924
Stefan Krah040e3112012-12-15 22:33:33 +01002925 def compare_total(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002926 """Compares self to other using the abstract representations.
2927
2928 This is not like the standard compare, which use their numerical
2929 value. Note that a total ordering is defined for all possible abstract
2930 representations.
2931 """
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00002932 other = _convert_other(other, raiseit=True)
2933
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002934 # if one is negative and the other is positive, it's easy
2935 if self._sign and not other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002936 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002937 if not self._sign and other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002938 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002939 sign = self._sign
2940
2941 # let's handle both NaN types
2942 self_nan = self._isnan()
2943 other_nan = other._isnan()
2944 if self_nan or other_nan:
2945 if self_nan == other_nan:
Mark Dickinsond314e1b2009-08-28 13:39:53 +00002946 # compare payloads as though they're integers
2947 self_key = len(self._int), self._int
2948 other_key = len(other._int), other._int
2949 if self_key < other_key:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002950 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002951 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002952 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002953 return _NegativeOne
Mark Dickinsond314e1b2009-08-28 13:39:53 +00002954 if self_key > other_key:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002955 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002956 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002957 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002958 return _One
2959 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002960
2961 if sign:
2962 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002963 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002964 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002965 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002966 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002967 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002968 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002969 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002970 else:
2971 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002972 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002973 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002974 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002975 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002976 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002977 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002978 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002979
2980 if self < other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002981 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002982 if self > other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002983 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002984
2985 if self._exp < other._exp:
2986 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002987 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002988 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002989 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002990 if self._exp > other._exp:
2991 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002992 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002993 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002994 return _One
2995 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002996
2997
Stefan Krah040e3112012-12-15 22:33:33 +01002998 def compare_total_mag(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002999 """Compares self to other using abstract repr., ignoring sign.
3000
3001 Like compare_total, but with operand's sign ignored and assumed to be 0.
3002 """
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003003 other = _convert_other(other, raiseit=True)
3004
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003005 s = self.copy_abs()
3006 o = other.copy_abs()
3007 return s.compare_total(o)
3008
3009 def copy_abs(self):
3010 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003011 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003012
3013 def copy_negate(self):
3014 """Returns a copy with the sign inverted."""
3015 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003016 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003017 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003018 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003019
Stefan Krah040e3112012-12-15 22:33:33 +01003020 def copy_sign(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003021 """Returns self with the sign of other."""
Mark Dickinson84230a12010-02-18 14:49:50 +00003022 other = _convert_other(other, raiseit=True)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003023 return _dec_from_triple(other._sign, self._int,
3024 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003025
3026 def exp(self, context=None):
3027 """Returns e ** self."""
3028
3029 if context is None:
3030 context = getcontext()
3031
3032 # exp(NaN) = NaN
3033 ans = self._check_nans(context=context)
3034 if ans:
3035 return ans
3036
3037 # exp(-Infinity) = 0
3038 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003039 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003040
3041 # exp(0) = 1
3042 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003043 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003044
3045 # exp(Infinity) = Infinity
3046 if self._isinfinity() == 1:
3047 return Decimal(self)
3048
3049 # the result is now guaranteed to be inexact (the true
3050 # mathematical result is transcendental). There's no need to
3051 # raise Rounded and Inexact here---they'll always be raised as
3052 # a result of the call to _fix.
3053 p = context.prec
3054 adj = self.adjusted()
3055
3056 # we only need to do any computation for quite a small range
3057 # of adjusted exponents---for example, -29 <= adj <= 10 for
3058 # the default context. For smaller exponent the result is
3059 # indistinguishable from 1 at the given precision, while for
3060 # larger exponent the result either overflows or underflows.
3061 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
3062 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003063 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003064 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
3065 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003066 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003067 elif self._sign == 0 and adj < -p:
3068 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003069 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003070 elif self._sign == 1 and adj < -p-1:
3071 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003072 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003073 # general case
3074 else:
3075 op = _WorkRep(self)
3076 c, e = op.int, op.exp
3077 if op.sign == 1:
3078 c = -c
3079
3080 # compute correctly rounded result: increase precision by
3081 # 3 digits at a time until we get an unambiguously
3082 # roundable result
3083 extra = 3
3084 while True:
3085 coeff, exp = _dexp(c, e, p+extra)
3086 if coeff % (5*10**(len(str(coeff))-p-1)):
3087 break
3088 extra += 3
3089
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003090 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003091
3092 # at this stage, ans should round correctly with *any*
3093 # rounding mode, not just with ROUND_HALF_EVEN
3094 context = context._shallow_copy()
3095 rounding = context._set_rounding(ROUND_HALF_EVEN)
3096 ans = ans._fix(context)
3097 context.rounding = rounding
3098
3099 return ans
3100
3101 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003102 """Return True if self is canonical; otherwise return False.
3103
3104 Currently, the encoding of a Decimal instance is always
3105 canonical, so this method returns True for any Decimal.
3106 """
3107 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003108
3109 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003110 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003111
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003112 A Decimal instance is considered finite if it is neither
3113 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003114 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003115 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003116
3117 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003118 """Return True if self is infinite; otherwise return False."""
3119 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003120
3121 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003122 """Return True if self is a qNaN or sNaN; otherwise return False."""
3123 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003124
3125 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003126 """Return True if self is a normal number; otherwise return False."""
3127 if self._is_special or not self:
3128 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003129 if context is None:
3130 context = getcontext()
Mark Dickinson06bb6742009-10-20 13:38:04 +00003131 return context.Emin <= self.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003132
3133 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003134 """Return True if self is a quiet NaN; otherwise return False."""
3135 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003136
3137 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003138 """Return True if self is negative; otherwise return False."""
3139 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003140
3141 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003142 """Return True if self is a signaling NaN; otherwise return False."""
3143 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003144
3145 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003146 """Return True if self is subnormal; otherwise return False."""
3147 if self._is_special or not self:
3148 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003149 if context is None:
3150 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003151 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003152
3153 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003154 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003155 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003156
3157 def _ln_exp_bound(self):
3158 """Compute a lower bound for the adjusted exponent of self.ln().
3159 In other words, compute r such that self.ln() >= 10**r. Assumes
3160 that self is finite and positive and that self != 1.
3161 """
3162
3163 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
3164 adj = self._exp + len(self._int) - 1
3165 if adj >= 1:
3166 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
3167 return len(str(adj*23//10)) - 1
3168 if adj <= -2:
3169 # argument <= 0.1
3170 return len(str((-1-adj)*23//10)) - 1
3171 op = _WorkRep(self)
3172 c, e = op.int, op.exp
3173 if adj == 0:
3174 # 1 < self < 10
3175 num = str(c-10**-e)
3176 den = str(c)
3177 return len(num) - len(den) - (num < den)
3178 # adj == -1, 0.1 <= self < 1
3179 return e + len(str(10**-e - c)) - 1
3180
3181
3182 def ln(self, context=None):
3183 """Returns the natural (base e) logarithm of self."""
3184
3185 if context is None:
3186 context = getcontext()
3187
3188 # ln(NaN) = NaN
3189 ans = self._check_nans(context=context)
3190 if ans:
3191 return ans
3192
3193 # ln(0.0) == -Infinity
3194 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003195 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003196
3197 # ln(Infinity) = Infinity
3198 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003199 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003200
3201 # ln(1.0) == 0.0
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003202 if self == _One:
3203 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003204
3205 # ln(negative) raises InvalidOperation
3206 if self._sign == 1:
3207 return context._raise_error(InvalidOperation,
3208 'ln of a negative value')
3209
3210 # result is irrational, so necessarily inexact
3211 op = _WorkRep(self)
3212 c, e = op.int, op.exp
3213 p = context.prec
3214
3215 # correctly rounded result: repeatedly increase precision by 3
3216 # until we get an unambiguously roundable result
3217 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3218 while True:
3219 coeff = _dlog(c, e, places)
3220 # assert len(str(abs(coeff)))-p >= 1
3221 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3222 break
3223 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003224 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003225
3226 context = context._shallow_copy()
3227 rounding = context._set_rounding(ROUND_HALF_EVEN)
3228 ans = ans._fix(context)
3229 context.rounding = rounding
3230 return ans
3231
3232 def _log10_exp_bound(self):
3233 """Compute a lower bound for the adjusted exponent of self.log10().
3234 In other words, find r such that self.log10() >= 10**r.
3235 Assumes that self is finite and positive and that self != 1.
3236 """
3237
3238 # For x >= 10 or x < 0.1 we only need a bound on the integer
3239 # part of log10(self), and this comes directly from the
3240 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3241 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3242 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3243
3244 adj = self._exp + len(self._int) - 1
3245 if adj >= 1:
3246 # self >= 10
3247 return len(str(adj))-1
3248 if adj <= -2:
3249 # self < 0.1
3250 return len(str(-1-adj))-1
3251 op = _WorkRep(self)
3252 c, e = op.int, op.exp
3253 if adj == 0:
3254 # 1 < self < 10
3255 num = str(c-10**-e)
3256 den = str(231*c)
3257 return len(num) - len(den) - (num < den) + 2
3258 # adj == -1, 0.1 <= self < 1
3259 num = str(10**-e-c)
3260 return len(num) + e - (num < "231") - 1
3261
3262 def log10(self, context=None):
3263 """Returns the base 10 logarithm of self."""
3264
3265 if context is None:
3266 context = getcontext()
3267
3268 # log10(NaN) = NaN
3269 ans = self._check_nans(context=context)
3270 if ans:
3271 return ans
3272
3273 # log10(0.0) == -Infinity
3274 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003275 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003276
3277 # log10(Infinity) = Infinity
3278 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003279 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003280
3281 # log10(negative or -Infinity) raises InvalidOperation
3282 if self._sign == 1:
3283 return context._raise_error(InvalidOperation,
3284 'log10 of a negative value')
3285
3286 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003287 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003288 # answer may need rounding
3289 ans = Decimal(self._exp + len(self._int) - 1)
3290 else:
3291 # result is irrational, so necessarily inexact
3292 op = _WorkRep(self)
3293 c, e = op.int, op.exp
3294 p = context.prec
3295
3296 # correctly rounded result: repeatedly increase precision
3297 # until result is unambiguously roundable
3298 places = p-self._log10_exp_bound()+2
3299 while True:
3300 coeff = _dlog10(c, e, places)
3301 # assert len(str(abs(coeff)))-p >= 1
3302 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3303 break
3304 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003305 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003306
3307 context = context._shallow_copy()
3308 rounding = context._set_rounding(ROUND_HALF_EVEN)
3309 ans = ans._fix(context)
3310 context.rounding = rounding
3311 return ans
3312
3313 def logb(self, context=None):
3314 """ Returns the exponent of the magnitude of self's MSD.
3315
3316 The result is the integer which is the exponent of the magnitude
3317 of the most significant digit of self (as though it were truncated
3318 to a single digit while maintaining the value of that digit and
3319 without limiting the resulting exponent).
3320 """
3321 # logb(NaN) = NaN
3322 ans = self._check_nans(context=context)
3323 if ans:
3324 return ans
3325
3326 if context is None:
3327 context = getcontext()
3328
3329 # logb(+/-Inf) = +Inf
3330 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003331 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003332
3333 # logb(0) = -Inf, DivisionByZero
3334 if not self:
3335 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3336
3337 # otherwise, simply return the adjusted exponent of self, as a
3338 # Decimal. Note that no attempt is made to fit the result
3339 # into the current context.
Mark Dickinson56df8872009-10-07 19:23:50 +00003340 ans = Decimal(self.adjusted())
3341 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003342
3343 def _islogical(self):
3344 """Return True if self is a logical operand.
3345
Christian Heimes679db4a2008-01-18 09:56:22 +00003346 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003347 an exponent of 0, and a coefficient whose digits must all be
3348 either 0 or 1.
3349 """
3350 if self._sign != 0 or self._exp != 0:
3351 return False
3352 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003353 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003354 return False
3355 return True
3356
3357 def _fill_logical(self, context, opa, opb):
3358 dif = context.prec - len(opa)
3359 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003360 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003361 elif dif < 0:
3362 opa = opa[-context.prec:]
3363 dif = context.prec - len(opb)
3364 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003365 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003366 elif dif < 0:
3367 opb = opb[-context.prec:]
3368 return opa, opb
3369
3370 def logical_and(self, other, context=None):
3371 """Applies an 'and' operation between self and other's digits."""
3372 if context is None:
3373 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003374
3375 other = _convert_other(other, raiseit=True)
3376
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003377 if not self._islogical() or not other._islogical():
3378 return context._raise_error(InvalidOperation)
3379
3380 # fill to context.prec
3381 (opa, opb) = self._fill_logical(context, self._int, other._int)
3382
3383 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003384 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3385 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003386
3387 def logical_invert(self, context=None):
3388 """Invert all its digits."""
3389 if context is None:
3390 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003391 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3392 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003393
3394 def logical_or(self, other, context=None):
3395 """Applies an 'or' operation between self and other's digits."""
3396 if context is None:
3397 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003398
3399 other = _convert_other(other, raiseit=True)
3400
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003401 if not self._islogical() or not other._islogical():
3402 return context._raise_error(InvalidOperation)
3403
3404 # fill to context.prec
3405 (opa, opb) = self._fill_logical(context, self._int, other._int)
3406
3407 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003408 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003409 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003410
3411 def logical_xor(self, other, context=None):
3412 """Applies an 'xor' operation between self and other's digits."""
3413 if context is None:
3414 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003415
3416 other = _convert_other(other, raiseit=True)
3417
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003418 if not self._islogical() or not other._islogical():
3419 return context._raise_error(InvalidOperation)
3420
3421 # fill to context.prec
3422 (opa, opb) = self._fill_logical(context, self._int, other._int)
3423
3424 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003425 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003426 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003427
3428 def max_mag(self, other, context=None):
3429 """Compares the values numerically with their sign ignored."""
3430 other = _convert_other(other, raiseit=True)
3431
3432 if context is None:
3433 context = getcontext()
3434
3435 if self._is_special or other._is_special:
3436 # If one operand is a quiet NaN and the other is number, then the
3437 # number is always returned
3438 sn = self._isnan()
3439 on = other._isnan()
3440 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003441 if on == 1 and sn == 0:
3442 return self._fix(context)
3443 if sn == 1 and on == 0:
3444 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003445 return self._check_nans(other, context)
3446
Christian Heimes77c02eb2008-02-09 02:18:51 +00003447 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003448 if c == 0:
3449 c = self.compare_total(other)
3450
3451 if c == -1:
3452 ans = other
3453 else:
3454 ans = self
3455
Christian Heimes2c181612007-12-17 20:04:13 +00003456 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003457
3458 def min_mag(self, other, context=None):
3459 """Compares the values numerically with their sign ignored."""
3460 other = _convert_other(other, raiseit=True)
3461
3462 if context is None:
3463 context = getcontext()
3464
3465 if self._is_special or other._is_special:
3466 # If one operand is a quiet NaN and the other is number, then the
3467 # number is always returned
3468 sn = self._isnan()
3469 on = other._isnan()
3470 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003471 if on == 1 and sn == 0:
3472 return self._fix(context)
3473 if sn == 1 and on == 0:
3474 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003475 return self._check_nans(other, context)
3476
Christian Heimes77c02eb2008-02-09 02:18:51 +00003477 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003478 if c == 0:
3479 c = self.compare_total(other)
3480
3481 if c == -1:
3482 ans = self
3483 else:
3484 ans = other
3485
Christian Heimes2c181612007-12-17 20:04:13 +00003486 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003487
3488 def next_minus(self, context=None):
3489 """Returns the largest representable number smaller than itself."""
3490 if context is None:
3491 context = getcontext()
3492
3493 ans = self._check_nans(context=context)
3494 if ans:
3495 return ans
3496
3497 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003498 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003499 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003500 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003501
3502 context = context.copy()
3503 context._set_rounding(ROUND_FLOOR)
3504 context._ignore_all_flags()
3505 new_self = self._fix(context)
3506 if new_self != self:
3507 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003508 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3509 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003510
3511 def next_plus(self, context=None):
3512 """Returns the smallest representable number larger than itself."""
3513 if context is None:
3514 context = getcontext()
3515
3516 ans = self._check_nans(context=context)
3517 if ans:
3518 return ans
3519
3520 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003521 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003522 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003523 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003524
3525 context = context.copy()
3526 context._set_rounding(ROUND_CEILING)
3527 context._ignore_all_flags()
3528 new_self = self._fix(context)
3529 if new_self != self:
3530 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003531 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3532 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003533
3534 def next_toward(self, other, context=None):
3535 """Returns the number closest to self, in the direction towards other.
3536
3537 The result is the closest representable number to self
3538 (excluding self) that is in the direction towards other,
3539 unless both have the same value. If the two operands are
3540 numerically equal, then the result is a copy of self with the
3541 sign set to be the same as the sign of other.
3542 """
3543 other = _convert_other(other, raiseit=True)
3544
3545 if context is None:
3546 context = getcontext()
3547
3548 ans = self._check_nans(other, context)
3549 if ans:
3550 return ans
3551
Christian Heimes77c02eb2008-02-09 02:18:51 +00003552 comparison = self._cmp(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003553 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003554 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003555
3556 if comparison == -1:
3557 ans = self.next_plus(context)
3558 else: # comparison == 1
3559 ans = self.next_minus(context)
3560
3561 # decide which flags to raise using value of ans
3562 if ans._isinfinity():
3563 context._raise_error(Overflow,
3564 'Infinite result from next_toward',
3565 ans._sign)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003566 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00003567 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003568 elif ans.adjusted() < context.Emin:
3569 context._raise_error(Underflow)
3570 context._raise_error(Subnormal)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003571 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00003572 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003573 # if precision == 1 then we don't raise Clamped for a
3574 # result 0E-Etiny.
3575 if not ans:
3576 context._raise_error(Clamped)
3577
3578 return ans
3579
3580 def number_class(self, context=None):
3581 """Returns an indication of the class of self.
3582
3583 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003584 sNaN
3585 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003586 -Infinity
3587 -Normal
3588 -Subnormal
3589 -Zero
3590 +Zero
3591 +Subnormal
3592 +Normal
3593 +Infinity
3594 """
3595 if self.is_snan():
3596 return "sNaN"
3597 if self.is_qnan():
3598 return "NaN"
3599 inf = self._isinfinity()
3600 if inf == 1:
3601 return "+Infinity"
3602 if inf == -1:
3603 return "-Infinity"
3604 if self.is_zero():
3605 if self._sign:
3606 return "-Zero"
3607 else:
3608 return "+Zero"
3609 if context is None:
3610 context = getcontext()
3611 if self.is_subnormal(context=context):
3612 if self._sign:
3613 return "-Subnormal"
3614 else:
3615 return "+Subnormal"
3616 # just a normal, regular, boring number, :)
3617 if self._sign:
3618 return "-Normal"
3619 else:
3620 return "+Normal"
3621
3622 def radix(self):
3623 """Just returns 10, as this is Decimal, :)"""
3624 return Decimal(10)
3625
3626 def rotate(self, other, context=None):
3627 """Returns a rotated copy of self, value-of-other times."""
3628 if context is None:
3629 context = getcontext()
3630
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003631 other = _convert_other(other, raiseit=True)
3632
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003633 ans = self._check_nans(other, context)
3634 if ans:
3635 return ans
3636
3637 if other._exp != 0:
3638 return context._raise_error(InvalidOperation)
3639 if not (-context.prec <= int(other) <= context.prec):
3640 return context._raise_error(InvalidOperation)
3641
3642 if self._isinfinity():
3643 return Decimal(self)
3644
3645 # get values, pad if necessary
3646 torot = int(other)
3647 rotdig = self._int
3648 topad = context.prec - len(rotdig)
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003649 if topad > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003650 rotdig = '0'*topad + rotdig
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003651 elif topad < 0:
3652 rotdig = rotdig[-topad:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003653
3654 # let's rotate!
3655 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003656 return _dec_from_triple(self._sign,
3657 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003658
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003659 def scaleb(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003660 """Returns self operand after adding the second value to its exp."""
3661 if context is None:
3662 context = getcontext()
3663
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003664 other = _convert_other(other, raiseit=True)
3665
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003666 ans = self._check_nans(other, context)
3667 if ans:
3668 return ans
3669
3670 if other._exp != 0:
3671 return context._raise_error(InvalidOperation)
3672 liminf = -2 * (context.Emax + context.prec)
3673 limsup = 2 * (context.Emax + context.prec)
3674 if not (liminf <= int(other) <= limsup):
3675 return context._raise_error(InvalidOperation)
3676
3677 if self._isinfinity():
3678 return Decimal(self)
3679
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003680 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003681 d = d._fix(context)
3682 return d
3683
3684 def shift(self, other, context=None):
3685 """Returns a shifted copy of self, value-of-other times."""
3686 if context is None:
3687 context = getcontext()
3688
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003689 other = _convert_other(other, raiseit=True)
3690
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003691 ans = self._check_nans(other, context)
3692 if ans:
3693 return ans
3694
3695 if other._exp != 0:
3696 return context._raise_error(InvalidOperation)
3697 if not (-context.prec <= int(other) <= context.prec):
3698 return context._raise_error(InvalidOperation)
3699
3700 if self._isinfinity():
3701 return Decimal(self)
3702
3703 # get values, pad if necessary
3704 torot = int(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003705 rotdig = self._int
3706 topad = context.prec - len(rotdig)
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003707 if topad > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003708 rotdig = '0'*topad + rotdig
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003709 elif topad < 0:
3710 rotdig = rotdig[-topad:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003711
3712 # let's shift!
3713 if torot < 0:
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003714 shifted = rotdig[:torot]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003715 else:
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003716 shifted = rotdig + '0'*torot
3717 shifted = shifted[-context.prec:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003718
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003719 return _dec_from_triple(self._sign,
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003720 shifted.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003721
Guido van Rossumd8faa362007-04-27 19:54:29 +00003722 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003723 def __reduce__(self):
3724 return (self.__class__, (str(self),))
3725
3726 def __copy__(self):
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00003727 if type(self) is Decimal:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003728 return self # I'm immutable; therefore I am my own clone
3729 return self.__class__(str(self))
3730
3731 def __deepcopy__(self, memo):
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00003732 if type(self) is Decimal:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003733 return self # My components are also immutable
3734 return self.__class__(str(self))
3735
Mark Dickinson79f52032009-03-17 23:12:51 +00003736 # PEP 3101 support. the _localeconv keyword argument should be
3737 # considered private: it's provided for ease of testing only.
3738 def __format__(self, specifier, context=None, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00003739 """Format a Decimal instance according to the given specifier.
3740
3741 The specifier should be a standard format specifier, with the
3742 form described in PEP 3101. Formatting types 'e', 'E', 'f',
Mark Dickinson79f52032009-03-17 23:12:51 +00003743 'F', 'g', 'G', 'n' and '%' are supported. If the formatting
3744 type is omitted it defaults to 'g' or 'G', depending on the
3745 value of context.capitals.
Christian Heimesf16baeb2008-02-29 14:57:44 +00003746 """
3747
3748 # Note: PEP 3101 says that if the type is not present then
3749 # there should be at least one digit after the decimal point.
3750 # We take the liberty of ignoring this requirement for
3751 # Decimal---it's presumably there to make sure that
3752 # format(float, '') behaves similarly to str(float).
3753 if context is None:
3754 context = getcontext()
3755
Mark Dickinson79f52032009-03-17 23:12:51 +00003756 spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003757
Mark Dickinson79f52032009-03-17 23:12:51 +00003758 # special values don't care about the type or precision
Christian Heimesf16baeb2008-02-29 14:57:44 +00003759 if self._is_special:
Mark Dickinson79f52032009-03-17 23:12:51 +00003760 sign = _format_sign(self._sign, spec)
3761 body = str(self.copy_abs())
3762 return _format_align(sign, body, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003763
3764 # a type of None defaults to 'g' or 'G', depending on context
Christian Heimesf16baeb2008-02-29 14:57:44 +00003765 if spec['type'] is None:
3766 spec['type'] = ['g', 'G'][context.capitals]
Mark Dickinson79f52032009-03-17 23:12:51 +00003767
3768 # if type is '%', adjust exponent of self accordingly
3769 if spec['type'] == '%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003770 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3771
3772 # round if necessary, taking rounding mode from the context
3773 rounding = context.rounding
3774 precision = spec['precision']
3775 if precision is not None:
3776 if spec['type'] in 'eE':
3777 self = self._round(precision+1, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003778 elif spec['type'] in 'fF%':
3779 self = self._rescale(-precision, rounding)
Mark Dickinson79f52032009-03-17 23:12:51 +00003780 elif spec['type'] in 'gG' and len(self._int) > precision:
3781 self = self._round(precision, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003782 # special case: zeros with a positive exponent can't be
3783 # represented in fixed point; rescale them to 0e0.
Mark Dickinson79f52032009-03-17 23:12:51 +00003784 if not self and self._exp > 0 and spec['type'] in 'fF%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003785 self = self._rescale(0, rounding)
3786
3787 # figure out placement of the decimal point
3788 leftdigits = self._exp + len(self._int)
Mark Dickinson79f52032009-03-17 23:12:51 +00003789 if spec['type'] in 'eE':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003790 if not self and precision is not None:
3791 dotplace = 1 - precision
3792 else:
3793 dotplace = 1
Mark Dickinson79f52032009-03-17 23:12:51 +00003794 elif spec['type'] in 'fF%':
3795 dotplace = leftdigits
Christian Heimesf16baeb2008-02-29 14:57:44 +00003796 elif spec['type'] in 'gG':
3797 if self._exp <= 0 and leftdigits > -6:
3798 dotplace = leftdigits
3799 else:
3800 dotplace = 1
3801
Mark Dickinson79f52032009-03-17 23:12:51 +00003802 # find digits before and after decimal point, and get exponent
3803 if dotplace < 0:
3804 intpart = '0'
3805 fracpart = '0'*(-dotplace) + self._int
3806 elif dotplace > len(self._int):
3807 intpart = self._int + '0'*(dotplace-len(self._int))
3808 fracpart = ''
Christian Heimesf16baeb2008-02-29 14:57:44 +00003809 else:
Mark Dickinson79f52032009-03-17 23:12:51 +00003810 intpart = self._int[:dotplace] or '0'
3811 fracpart = self._int[dotplace:]
3812 exp = leftdigits-dotplace
Christian Heimesf16baeb2008-02-29 14:57:44 +00003813
Mark Dickinson79f52032009-03-17 23:12:51 +00003814 # done with the decimal-specific stuff; hand over the rest
3815 # of the formatting to the _format_number function
3816 return _format_number(self._sign, intpart, fracpart, exp, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003817
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003818def _dec_from_triple(sign, coefficient, exponent, special=False):
3819 """Create a decimal instance directly, without any validation,
3820 normalization (e.g. removal of leading zeros) or argument
3821 conversion.
3822
3823 This function is for *internal use only*.
3824 """
3825
3826 self = object.__new__(Decimal)
3827 self._sign = sign
3828 self._int = coefficient
3829 self._exp = exponent
3830 self._is_special = special
3831
3832 return self
3833
Raymond Hettinger82417ca2009-02-03 03:54:28 +00003834# Register Decimal as a kind of Number (an abstract base class).
3835# However, do not register it as Real (because Decimals are not
3836# interoperable with floats).
3837_numbers.Number.register(Decimal)
3838
3839
Guido van Rossumd8faa362007-04-27 19:54:29 +00003840##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003841
Thomas Wouters89f507f2006-12-13 04:49:30 +00003842class _ContextManager(object):
3843 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003844
Thomas Wouters89f507f2006-12-13 04:49:30 +00003845 Sets a copy of the supplied context in __enter__() and restores
3846 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003847 """
3848 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003849 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003850 def __enter__(self):
3851 self.saved_context = getcontext()
3852 setcontext(self.new_context)
3853 return self.new_context
3854 def __exit__(self, t, v, tb):
3855 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003856
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003857class Context(object):
3858 """Contains the context for a Decimal instance.
3859
3860 Contains:
3861 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003862 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003863 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003864 raised when it is caused. Otherwise, a value is
3865 substituted in.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003866 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003867 (Whether or not the trap_enabler is set)
3868 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003869 Emin - Minimum exponent
3870 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003871 capitals - If 1, 1*10^1 is printed as 1E+1.
3872 If 0, printed as 1e1
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00003873 clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003874 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003875
Stefan Krah1919b7e2012-03-21 18:25:23 +01003876 def __init__(self, prec=None, rounding=None, Emin=None, Emax=None,
3877 capitals=None, clamp=None, flags=None, traps=None,
3878 _ignored_flags=None):
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003879 # Set defaults; for everything except flags and _ignored_flags,
3880 # inherit from DefaultContext.
3881 try:
3882 dc = DefaultContext
3883 except NameError:
3884 pass
3885
3886 self.prec = prec if prec is not None else dc.prec
3887 self.rounding = rounding if rounding is not None else dc.rounding
3888 self.Emin = Emin if Emin is not None else dc.Emin
3889 self.Emax = Emax if Emax is not None else dc.Emax
3890 self.capitals = capitals if capitals is not None else dc.capitals
3891 self.clamp = clamp if clamp is not None else dc.clamp
3892
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003893 if _ignored_flags is None:
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003894 self._ignored_flags = []
3895 else:
3896 self._ignored_flags = _ignored_flags
3897
3898 if traps is None:
3899 self.traps = dc.traps.copy()
3900 elif not isinstance(traps, dict):
Stefan Krah1919b7e2012-03-21 18:25:23 +01003901 self.traps = dict((s, int(s in traps)) for s in _signals + traps)
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003902 else:
3903 self.traps = traps
3904
3905 if flags is None:
3906 self.flags = dict.fromkeys(_signals, 0)
3907 elif not isinstance(flags, dict):
Stefan Krah1919b7e2012-03-21 18:25:23 +01003908 self.flags = dict((s, int(s in flags)) for s in _signals + flags)
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003909 else:
3910 self.flags = flags
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003911
Stefan Krah1919b7e2012-03-21 18:25:23 +01003912 def _set_integer_check(self, name, value, vmin, vmax):
3913 if not isinstance(value, int):
3914 raise TypeError("%s must be an integer" % name)
3915 if vmin == '-inf':
3916 if value > vmax:
3917 raise ValueError("%s must be in [%s, %d]. got: %s" % (name, vmin, vmax, value))
3918 elif vmax == 'inf':
3919 if value < vmin:
3920 raise ValueError("%s must be in [%d, %s]. got: %s" % (name, vmin, vmax, value))
3921 else:
3922 if value < vmin or value > vmax:
3923 raise ValueError("%s must be in [%d, %d]. got %s" % (name, vmin, vmax, value))
3924 return object.__setattr__(self, name, value)
3925
3926 def _set_signal_dict(self, name, d):
3927 if not isinstance(d, dict):
3928 raise TypeError("%s must be a signal dict" % d)
3929 for key in d:
3930 if not key in _signals:
3931 raise KeyError("%s is not a valid signal dict" % d)
3932 for key in _signals:
3933 if not key in d:
3934 raise KeyError("%s is not a valid signal dict" % d)
3935 return object.__setattr__(self, name, d)
3936
3937 def __setattr__(self, name, value):
3938 if name == 'prec':
3939 return self._set_integer_check(name, value, 1, 'inf')
3940 elif name == 'Emin':
3941 return self._set_integer_check(name, value, '-inf', 0)
3942 elif name == 'Emax':
3943 return self._set_integer_check(name, value, 0, 'inf')
3944 elif name == 'capitals':
3945 return self._set_integer_check(name, value, 0, 1)
3946 elif name == 'clamp':
3947 return self._set_integer_check(name, value, 0, 1)
3948 elif name == 'rounding':
3949 if not value in _rounding_modes:
3950 # raise TypeError even for strings to have consistency
3951 # among various implementations.
3952 raise TypeError("%s: invalid rounding mode" % value)
3953 return object.__setattr__(self, name, value)
3954 elif name == 'flags' or name == 'traps':
3955 return self._set_signal_dict(name, value)
3956 elif name == '_ignored_flags':
3957 return object.__setattr__(self, name, value)
3958 else:
3959 raise AttributeError(
3960 "'decimal.Context' object has no attribute '%s'" % name)
3961
3962 def __delattr__(self, name):
3963 raise AttributeError("%s cannot be deleted" % name)
3964
3965 # Support for pickling, copy, and deepcopy
3966 def __reduce__(self):
3967 flags = [sig for sig, v in self.flags.items() if v]
3968 traps = [sig for sig, v in self.traps.items() if v]
3969 return (self.__class__,
3970 (self.prec, self.rounding, self.Emin, self.Emax,
3971 self.capitals, self.clamp, flags, traps))
3972
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003973 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003974 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003975 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003976 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00003977 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d, '
3978 'clamp=%(clamp)d'
Guido van Rossumd8faa362007-04-27 19:54:29 +00003979 % vars(self))
3980 names = [f.__name__ for f, v in self.flags.items() if v]
3981 s.append('flags=[' + ', '.join(names) + ']')
3982 names = [t.__name__ for t, v in self.traps.items() if v]
3983 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003984 return ', '.join(s) + ')'
3985
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003986 def clear_flags(self):
3987 """Reset all flags to zero"""
3988 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003989 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003990
Stefan Krah1919b7e2012-03-21 18:25:23 +01003991 def clear_traps(self):
3992 """Reset all traps to zero"""
3993 for flag in self.traps:
3994 self.traps[flag] = 0
3995
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003996 def _shallow_copy(self):
3997 """Returns a shallow copy from self."""
Stefan Krah1919b7e2012-03-21 18:25:23 +01003998 nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
3999 self.capitals, self.clamp, self.flags, self.traps,
4000 self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004001 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004002
4003 def copy(self):
4004 """Returns a deep copy from self."""
Stefan Krah1919b7e2012-03-21 18:25:23 +01004005 nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
4006 self.capitals, self.clamp,
4007 self.flags.copy(), self.traps.copy(),
4008 self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004009 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004010 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004011
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004012 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004013 """Handles an error
4014
4015 If the flag is in _ignored_flags, returns the default response.
Raymond Hettinger86173da2008-02-01 20:38:12 +00004016 Otherwise, it sets the flag, then, if the corresponding
Stefan Krah2eb4a072010-05-19 15:52:31 +00004017 trap_enabler is set, it reraises the exception. Otherwise, it returns
Raymond Hettinger86173da2008-02-01 20:38:12 +00004018 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004019 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004020 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004021 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00004022 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004023 return error().handle(self, *args)
4024
Raymond Hettinger86173da2008-02-01 20:38:12 +00004025 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00004026 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00004027 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004028 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004029
4030 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00004031 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00004032 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004033
4034 def _ignore_all_flags(self):
4035 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00004036 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004037
4038 def _ignore_flags(self, *flags):
4039 """Ignore the flags, if they are raised"""
4040 # Do not mutate-- This way, copies of a context leave the original
4041 # alone.
4042 self._ignored_flags = (self._ignored_flags + list(flags))
4043 return list(flags)
4044
4045 def _regard_flags(self, *flags):
4046 """Stop ignoring the flags, if they are raised"""
4047 if flags and isinstance(flags[0], (tuple,list)):
4048 flags = flags[0]
4049 for flag in flags:
4050 self._ignored_flags.remove(flag)
4051
Nick Coghland1abd252008-07-15 15:46:38 +00004052 # We inherit object.__hash__, so we must deny this explicitly
4053 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004054
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004055 def Etiny(self):
4056 """Returns Etiny (= Emin - prec + 1)"""
4057 return int(self.Emin - self.prec + 1)
4058
4059 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004060 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004061 return int(self.Emax - self.prec + 1)
4062
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004063 def _set_rounding(self, type):
4064 """Sets the rounding type.
4065
4066 Sets the rounding type, and returns the current (previous)
4067 rounding type. Often used like:
4068
4069 context = context.copy()
4070 # so you don't change the calling context
4071 # if an error occurs in the middle.
4072 rounding = context._set_rounding(ROUND_UP)
4073 val = self.__sub__(other, context=context)
4074 context._set_rounding(rounding)
4075
4076 This will make it round up for that operation.
4077 """
4078 rounding = self.rounding
4079 self.rounding= type
4080 return rounding
4081
Raymond Hettingerfed52962004-07-14 15:41:57 +00004082 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00004083 """Creates a new Decimal instance but using self as context.
4084
4085 This method implements the to-number operation of the
4086 IBM Decimal specification."""
4087
4088 if isinstance(num, str) and num != num.strip():
4089 return self._raise_error(ConversionSyntax,
4090 "no trailing or leading whitespace is "
4091 "permitted.")
4092
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004093 d = Decimal(num, context=self)
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00004094 if d._isnan() and len(d._int) > self.prec - self.clamp:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004095 return self._raise_error(ConversionSyntax,
4096 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00004097 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004098
Raymond Hettinger771ed762009-01-03 19:20:32 +00004099 def create_decimal_from_float(self, f):
4100 """Creates a new Decimal instance from a float but rounding using self
4101 as the context.
4102
4103 >>> context = Context(prec=5, rounding=ROUND_DOWN)
4104 >>> context.create_decimal_from_float(3.1415926535897932)
4105 Decimal('3.1415')
4106 >>> context = Context(prec=5, traps=[Inexact])
4107 >>> context.create_decimal_from_float(3.1415926535897932)
4108 Traceback (most recent call last):
4109 ...
4110 decimal.Inexact: None
4111
4112 """
4113 d = Decimal.from_float(f) # An exact conversion
4114 return d._fix(self) # Apply the context rounding
4115
Guido van Rossumd8faa362007-04-27 19:54:29 +00004116 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004117 def abs(self, a):
4118 """Returns the absolute value of the operand.
4119
4120 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00004121 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004122 the plus operation on the operand.
4123
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004124 >>> ExtendedContext.abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004125 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004126 >>> ExtendedContext.abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004127 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004128 >>> ExtendedContext.abs(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004129 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004130 >>> ExtendedContext.abs(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004131 Decimal('101.5')
Mark Dickinson84230a12010-02-18 14:49:50 +00004132 >>> ExtendedContext.abs(-1)
4133 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004134 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004135 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004136 return a.__abs__(context=self)
4137
4138 def add(self, a, b):
4139 """Return the sum of the two operands.
4140
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004141 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004142 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004143 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004144 Decimal('1.02E+4')
Mark Dickinson84230a12010-02-18 14:49:50 +00004145 >>> ExtendedContext.add(1, Decimal(2))
4146 Decimal('3')
4147 >>> ExtendedContext.add(Decimal(8), 5)
4148 Decimal('13')
4149 >>> ExtendedContext.add(5, 5)
4150 Decimal('10')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004151 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004152 a = _convert_other(a, raiseit=True)
4153 r = a.__add__(b, context=self)
4154 if r is NotImplemented:
4155 raise TypeError("Unable to convert %s to Decimal" % b)
4156 else:
4157 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004158
4159 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00004160 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004161
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004162 def canonical(self, a):
4163 """Returns the same Decimal object.
4164
4165 As we do not have different encodings for the same number, the
4166 received object already is in its canonical form.
4167
4168 >>> ExtendedContext.canonical(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004169 Decimal('2.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004170 """
Stefan Krah1919b7e2012-03-21 18:25:23 +01004171 if not isinstance(a, Decimal):
4172 raise TypeError("canonical requires a Decimal as an argument.")
Stefan Krah040e3112012-12-15 22:33:33 +01004173 return a.canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004174
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004175 def compare(self, a, b):
4176 """Compares values numerically.
4177
4178 If the signs of the operands differ, a value representing each operand
4179 ('-1' if the operand is less than zero, '0' if the operand is zero or
4180 negative zero, or '1' if the operand is greater than zero) is used in
4181 place of that operand for the comparison instead of the actual
4182 operand.
4183
4184 The comparison is then effected by subtracting the second operand from
4185 the first and then returning a value according to the result of the
4186 subtraction: '-1' if the result is less than zero, '0' if the result is
4187 zero or negative zero, or '1' if the result is greater than zero.
4188
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004189 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004190 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004191 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004192 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004193 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004194 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004195 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004196 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004197 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004198 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004199 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004200 Decimal('-1')
Mark Dickinson84230a12010-02-18 14:49:50 +00004201 >>> ExtendedContext.compare(1, 2)
4202 Decimal('-1')
4203 >>> ExtendedContext.compare(Decimal(1), 2)
4204 Decimal('-1')
4205 >>> ExtendedContext.compare(1, Decimal(2))
4206 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004207 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004208 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004209 return a.compare(b, context=self)
4210
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004211 def compare_signal(self, a, b):
4212 """Compares the values of the two operands numerically.
4213
4214 It's pretty much like compare(), but all NaNs signal, with signaling
4215 NaNs taking precedence over quiet NaNs.
4216
4217 >>> c = ExtendedContext
4218 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004219 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004220 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004221 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004222 >>> c.flags[InvalidOperation] = 0
4223 >>> print(c.flags[InvalidOperation])
4224 0
4225 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004226 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004227 >>> print(c.flags[InvalidOperation])
4228 1
4229 >>> c.flags[InvalidOperation] = 0
4230 >>> print(c.flags[InvalidOperation])
4231 0
4232 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004233 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004234 >>> print(c.flags[InvalidOperation])
4235 1
Mark Dickinson84230a12010-02-18 14:49:50 +00004236 >>> c.compare_signal(-1, 2)
4237 Decimal('-1')
4238 >>> c.compare_signal(Decimal(-1), 2)
4239 Decimal('-1')
4240 >>> c.compare_signal(-1, Decimal(2))
4241 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004242 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004243 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004244 return a.compare_signal(b, context=self)
4245
4246 def compare_total(self, a, b):
4247 """Compares two operands using their abstract representation.
4248
4249 This is not like the standard compare, which use their numerical
4250 value. Note that a total ordering is defined for all possible abstract
4251 representations.
4252
4253 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004254 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004255 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004256 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004257 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004258 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004259 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004260 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004261 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004262 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004263 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004264 Decimal('-1')
Mark Dickinson84230a12010-02-18 14:49:50 +00004265 >>> ExtendedContext.compare_total(1, 2)
4266 Decimal('-1')
4267 >>> ExtendedContext.compare_total(Decimal(1), 2)
4268 Decimal('-1')
4269 >>> ExtendedContext.compare_total(1, Decimal(2))
4270 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004271 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004272 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004273 return a.compare_total(b)
4274
4275 def compare_total_mag(self, a, b):
4276 """Compares two operands using their abstract representation ignoring sign.
4277
4278 Like compare_total, but with operand's sign ignored and assumed to be 0.
4279 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004280 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004281 return a.compare_total_mag(b)
4282
4283 def copy_abs(self, a):
4284 """Returns a copy of the operand with the sign set to 0.
4285
4286 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004287 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004288 >>> ExtendedContext.copy_abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004289 Decimal('100')
Mark Dickinson84230a12010-02-18 14:49:50 +00004290 >>> ExtendedContext.copy_abs(-1)
4291 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004292 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004293 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004294 return a.copy_abs()
4295
4296 def copy_decimal(self, a):
Mark Dickinson84230a12010-02-18 14:49:50 +00004297 """Returns a copy of the decimal object.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004298
4299 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004300 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004301 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004302 Decimal('-1.00')
Mark Dickinson84230a12010-02-18 14:49:50 +00004303 >>> ExtendedContext.copy_decimal(1)
4304 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004305 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004306 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004307 return Decimal(a)
4308
4309 def copy_negate(self, a):
4310 """Returns a copy of the operand with the sign inverted.
4311
4312 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004313 Decimal('-101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004314 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004315 Decimal('101.5')
Mark Dickinson84230a12010-02-18 14:49:50 +00004316 >>> ExtendedContext.copy_negate(1)
4317 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004318 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004319 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004320 return a.copy_negate()
4321
4322 def copy_sign(self, a, b):
4323 """Copies the second operand's sign to the first one.
4324
4325 In detail, it returns a copy of the first operand with the sign
4326 equal to the sign of the second operand.
4327
4328 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004329 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004330 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004331 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004332 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004333 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004334 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004335 Decimal('-1.50')
Mark Dickinson84230a12010-02-18 14:49:50 +00004336 >>> ExtendedContext.copy_sign(1, -2)
4337 Decimal('-1')
4338 >>> ExtendedContext.copy_sign(Decimal(1), -2)
4339 Decimal('-1')
4340 >>> ExtendedContext.copy_sign(1, Decimal(-2))
4341 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004342 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004343 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004344 return a.copy_sign(b)
4345
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004346 def divide(self, a, b):
4347 """Decimal division in a specified context.
4348
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004349 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004350 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004351 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004352 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004353 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004354 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004355 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004356 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004357 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004358 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004359 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004360 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004361 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004362 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004363 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004364 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004365 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004366 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004367 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004368 Decimal('1.20E+6')
Mark Dickinson84230a12010-02-18 14:49:50 +00004369 >>> ExtendedContext.divide(5, 5)
4370 Decimal('1')
4371 >>> ExtendedContext.divide(Decimal(5), 5)
4372 Decimal('1')
4373 >>> ExtendedContext.divide(5, Decimal(5))
4374 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004375 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004376 a = _convert_other(a, raiseit=True)
4377 r = a.__truediv__(b, context=self)
4378 if r is NotImplemented:
4379 raise TypeError("Unable to convert %s to Decimal" % b)
4380 else:
4381 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004382
4383 def divide_int(self, a, b):
4384 """Divides two numbers and returns the integer part of the result.
4385
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004386 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004387 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004388 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004389 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004390 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004391 Decimal('3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004392 >>> ExtendedContext.divide_int(10, 3)
4393 Decimal('3')
4394 >>> ExtendedContext.divide_int(Decimal(10), 3)
4395 Decimal('3')
4396 >>> ExtendedContext.divide_int(10, Decimal(3))
4397 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004398 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004399 a = _convert_other(a, raiseit=True)
4400 r = a.__floordiv__(b, context=self)
4401 if r is NotImplemented:
4402 raise TypeError("Unable to convert %s to Decimal" % b)
4403 else:
4404 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004405
4406 def divmod(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004407 """Return (a // b, a % b).
Mark Dickinsonc53796e2010-01-06 16:22:15 +00004408
4409 >>> ExtendedContext.divmod(Decimal(8), Decimal(3))
4410 (Decimal('2'), Decimal('2'))
4411 >>> ExtendedContext.divmod(Decimal(8), Decimal(4))
4412 (Decimal('2'), Decimal('0'))
Mark Dickinson84230a12010-02-18 14:49:50 +00004413 >>> ExtendedContext.divmod(8, 4)
4414 (Decimal('2'), Decimal('0'))
4415 >>> ExtendedContext.divmod(Decimal(8), 4)
4416 (Decimal('2'), Decimal('0'))
4417 >>> ExtendedContext.divmod(8, Decimal(4))
4418 (Decimal('2'), Decimal('0'))
Mark Dickinsonc53796e2010-01-06 16:22:15 +00004419 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004420 a = _convert_other(a, raiseit=True)
4421 r = a.__divmod__(b, context=self)
4422 if r is NotImplemented:
4423 raise TypeError("Unable to convert %s to Decimal" % b)
4424 else:
4425 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004426
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004427 def exp(self, a):
4428 """Returns e ** a.
4429
4430 >>> c = ExtendedContext.copy()
4431 >>> c.Emin = -999
4432 >>> c.Emax = 999
4433 >>> c.exp(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004434 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004435 >>> c.exp(Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004436 Decimal('0.367879441')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004437 >>> c.exp(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004438 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004439 >>> c.exp(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004440 Decimal('2.71828183')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004441 >>> c.exp(Decimal('0.693147181'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004442 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004443 >>> c.exp(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004444 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004445 >>> c.exp(10)
4446 Decimal('22026.4658')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004447 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004448 a =_convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004449 return a.exp(context=self)
4450
4451 def fma(self, a, b, c):
4452 """Returns a multiplied by b, plus c.
4453
4454 The first two operands are multiplied together, using multiply,
4455 the third operand is then added to the result of that
4456 multiplication, using add, all with only one final rounding.
4457
4458 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004459 Decimal('22')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004460 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004461 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004462 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004463 Decimal('1.38435736E+12')
Mark Dickinson84230a12010-02-18 14:49:50 +00004464 >>> ExtendedContext.fma(1, 3, 4)
4465 Decimal('7')
4466 >>> ExtendedContext.fma(1, Decimal(3), 4)
4467 Decimal('7')
4468 >>> ExtendedContext.fma(1, 3, Decimal(4))
4469 Decimal('7')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004470 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004471 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004472 return a.fma(b, c, context=self)
4473
4474 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004475 """Return True if the operand is canonical; otherwise return False.
4476
4477 Currently, the encoding of a Decimal instance is always
4478 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004479
4480 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004481 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004482 """
Stefan Krah1919b7e2012-03-21 18:25:23 +01004483 if not isinstance(a, Decimal):
4484 raise TypeError("is_canonical requires a Decimal as an argument.")
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004485 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004486
4487 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004488 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004489
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004490 A Decimal instance is considered finite if it is neither
4491 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004492
4493 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004494 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004495 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004496 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004497 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004498 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004499 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004500 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004501 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004502 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004503 >>> ExtendedContext.is_finite(1)
4504 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004505 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004506 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004507 return a.is_finite()
4508
4509 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004510 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004511
4512 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004513 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004514 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004515 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004516 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004517 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004518 >>> ExtendedContext.is_infinite(1)
4519 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004520 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004521 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004522 return a.is_infinite()
4523
4524 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004525 """Return True if the operand is a qNaN or sNaN;
4526 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004527
4528 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004529 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004530 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004531 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004532 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004533 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004534 >>> ExtendedContext.is_nan(1)
4535 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004536 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004537 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004538 return a.is_nan()
4539
4540 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004541 """Return True if the operand is a normal number;
4542 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004543
4544 >>> c = ExtendedContext.copy()
4545 >>> c.Emin = -999
4546 >>> c.Emax = 999
4547 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004548 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004549 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004550 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004551 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004552 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004553 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004554 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004555 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004556 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004557 >>> c.is_normal(1)
4558 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004559 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004560 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004561 return a.is_normal(context=self)
4562
4563 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004564 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004565
4566 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004567 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004568 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004569 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004570 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004571 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004572 >>> ExtendedContext.is_qnan(1)
4573 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004574 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004575 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004576 return a.is_qnan()
4577
4578 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004579 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004580
4581 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004582 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004583 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004584 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004585 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004586 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004587 >>> ExtendedContext.is_signed(8)
4588 False
4589 >>> ExtendedContext.is_signed(-8)
4590 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004591 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004592 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004593 return a.is_signed()
4594
4595 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004596 """Return True if the operand is a signaling NaN;
4597 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004598
4599 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004600 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004601 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004602 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004603 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004604 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004605 >>> ExtendedContext.is_snan(1)
4606 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004607 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004608 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004609 return a.is_snan()
4610
4611 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004612 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004613
4614 >>> c = ExtendedContext.copy()
4615 >>> c.Emin = -999
4616 >>> c.Emax = 999
4617 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004618 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004619 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004620 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004621 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004622 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004623 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004624 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004625 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004626 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004627 >>> c.is_subnormal(1)
4628 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004629 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004630 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004631 return a.is_subnormal(context=self)
4632
4633 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004634 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004635
4636 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004637 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004638 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004639 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004640 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004641 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004642 >>> ExtendedContext.is_zero(1)
4643 False
4644 >>> ExtendedContext.is_zero(0)
4645 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004646 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004647 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004648 return a.is_zero()
4649
4650 def ln(self, a):
4651 """Returns the natural (base e) logarithm of the operand.
4652
4653 >>> c = ExtendedContext.copy()
4654 >>> c.Emin = -999
4655 >>> c.Emax = 999
4656 >>> c.ln(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004657 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004658 >>> c.ln(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004659 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004660 >>> c.ln(Decimal('2.71828183'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004661 Decimal('1.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004662 >>> c.ln(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004663 Decimal('2.30258509')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004664 >>> c.ln(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004665 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004666 >>> c.ln(1)
4667 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004668 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004669 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004670 return a.ln(context=self)
4671
4672 def log10(self, a):
4673 """Returns the base 10 logarithm of the operand.
4674
4675 >>> c = ExtendedContext.copy()
4676 >>> c.Emin = -999
4677 >>> c.Emax = 999
4678 >>> c.log10(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004679 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004680 >>> c.log10(Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004681 Decimal('-3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004682 >>> c.log10(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004683 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004684 >>> c.log10(Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004685 Decimal('0.301029996')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004686 >>> c.log10(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004687 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004688 >>> c.log10(Decimal('70'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004689 Decimal('1.84509804')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004690 >>> c.log10(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004691 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004692 >>> c.log10(0)
4693 Decimal('-Infinity')
4694 >>> c.log10(1)
4695 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004696 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004697 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004698 return a.log10(context=self)
4699
4700 def logb(self, a):
4701 """ Returns the exponent of the magnitude of the operand's MSD.
4702
4703 The result is the integer which is the exponent of the magnitude
4704 of the most significant digit of the operand (as though the
4705 operand were truncated to a single digit while maintaining the
4706 value of that digit and without limiting the resulting exponent).
4707
4708 >>> ExtendedContext.logb(Decimal('250'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004709 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004710 >>> ExtendedContext.logb(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004711 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004712 >>> ExtendedContext.logb(Decimal('0.03'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004713 Decimal('-2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004714 >>> ExtendedContext.logb(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004715 Decimal('-Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004716 >>> ExtendedContext.logb(1)
4717 Decimal('0')
4718 >>> ExtendedContext.logb(10)
4719 Decimal('1')
4720 >>> ExtendedContext.logb(100)
4721 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004722 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004723 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004724 return a.logb(context=self)
4725
4726 def logical_and(self, a, b):
4727 """Applies the logical operation 'and' between each operand's digits.
4728
4729 The operands must be both logical numbers.
4730
4731 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004732 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004733 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004734 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004735 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004736 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004737 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004738 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004739 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004740 Decimal('1000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004741 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004742 Decimal('10')
Mark Dickinson84230a12010-02-18 14:49:50 +00004743 >>> ExtendedContext.logical_and(110, 1101)
4744 Decimal('100')
4745 >>> ExtendedContext.logical_and(Decimal(110), 1101)
4746 Decimal('100')
4747 >>> ExtendedContext.logical_and(110, Decimal(1101))
4748 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004749 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004750 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004751 return a.logical_and(b, context=self)
4752
4753 def logical_invert(self, a):
4754 """Invert all the digits in the operand.
4755
4756 The operand must be a logical number.
4757
4758 >>> ExtendedContext.logical_invert(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004759 Decimal('111111111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004760 >>> ExtendedContext.logical_invert(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004761 Decimal('111111110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004762 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004763 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004764 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004765 Decimal('10101010')
Mark Dickinson84230a12010-02-18 14:49:50 +00004766 >>> ExtendedContext.logical_invert(1101)
4767 Decimal('111110010')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004768 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004769 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004770 return a.logical_invert(context=self)
4771
4772 def logical_or(self, a, b):
4773 """Applies the logical operation 'or' between each operand's digits.
4774
4775 The operands must be both logical numbers.
4776
4777 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004778 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004779 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004780 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004781 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004782 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004783 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004784 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004785 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004786 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004787 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004788 Decimal('1110')
Mark Dickinson84230a12010-02-18 14:49:50 +00004789 >>> ExtendedContext.logical_or(110, 1101)
4790 Decimal('1111')
4791 >>> ExtendedContext.logical_or(Decimal(110), 1101)
4792 Decimal('1111')
4793 >>> ExtendedContext.logical_or(110, Decimal(1101))
4794 Decimal('1111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004795 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004796 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004797 return a.logical_or(b, context=self)
4798
4799 def logical_xor(self, a, b):
4800 """Applies the logical operation 'xor' between each operand's digits.
4801
4802 The operands must be both logical numbers.
4803
4804 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004805 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004806 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004807 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004808 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004809 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004810 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004811 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004812 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004813 Decimal('110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004814 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004815 Decimal('1101')
Mark Dickinson84230a12010-02-18 14:49:50 +00004816 >>> ExtendedContext.logical_xor(110, 1101)
4817 Decimal('1011')
4818 >>> ExtendedContext.logical_xor(Decimal(110), 1101)
4819 Decimal('1011')
4820 >>> ExtendedContext.logical_xor(110, Decimal(1101))
4821 Decimal('1011')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004822 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004823 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004824 return a.logical_xor(b, context=self)
4825
Mark Dickinson84230a12010-02-18 14:49:50 +00004826 def max(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004827 """max compares two values numerically and returns the maximum.
4828
4829 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004830 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004831 operation. If they are numerically equal then the left-hand operand
4832 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004833 infinity) of the two operands is chosen as the result.
4834
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004835 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004836 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004837 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004838 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004839 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004840 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004841 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004842 Decimal('7')
Mark Dickinson84230a12010-02-18 14:49:50 +00004843 >>> ExtendedContext.max(1, 2)
4844 Decimal('2')
4845 >>> ExtendedContext.max(Decimal(1), 2)
4846 Decimal('2')
4847 >>> ExtendedContext.max(1, Decimal(2))
4848 Decimal('2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004849 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004850 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004851 return a.max(b, context=self)
4852
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004853 def max_mag(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004854 """Compares the values numerically with their sign ignored.
4855
4856 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
4857 Decimal('7')
4858 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
4859 Decimal('-10')
4860 >>> ExtendedContext.max_mag(1, -2)
4861 Decimal('-2')
4862 >>> ExtendedContext.max_mag(Decimal(1), -2)
4863 Decimal('-2')
4864 >>> ExtendedContext.max_mag(1, Decimal(-2))
4865 Decimal('-2')
4866 """
4867 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004868 return a.max_mag(b, context=self)
4869
Mark Dickinson84230a12010-02-18 14:49:50 +00004870 def min(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004871 """min compares two values numerically and returns the minimum.
4872
4873 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004874 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004875 operation. If they are numerically equal then the left-hand operand
4876 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004877 infinity) of the two operands is chosen as the result.
4878
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004879 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004880 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004881 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004882 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004883 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004884 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004885 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004886 Decimal('7')
Mark Dickinson84230a12010-02-18 14:49:50 +00004887 >>> ExtendedContext.min(1, 2)
4888 Decimal('1')
4889 >>> ExtendedContext.min(Decimal(1), 2)
4890 Decimal('1')
4891 >>> ExtendedContext.min(1, Decimal(29))
4892 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004893 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004894 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004895 return a.min(b, context=self)
4896
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004897 def min_mag(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004898 """Compares the values numerically with their sign ignored.
4899
4900 >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2'))
4901 Decimal('-2')
4902 >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN'))
4903 Decimal('-3')
4904 >>> ExtendedContext.min_mag(1, -2)
4905 Decimal('1')
4906 >>> ExtendedContext.min_mag(Decimal(1), -2)
4907 Decimal('1')
4908 >>> ExtendedContext.min_mag(1, Decimal(-2))
4909 Decimal('1')
4910 """
4911 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004912 return a.min_mag(b, context=self)
4913
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004914 def minus(self, a):
4915 """Minus corresponds to unary prefix minus in Python.
4916
4917 The operation is evaluated using the same rules as subtract; the
4918 operation minus(a) is calculated as subtract('0', a) where the '0'
4919 has the same exponent as the operand.
4920
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004921 >>> ExtendedContext.minus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004922 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004923 >>> ExtendedContext.minus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004924 Decimal('1.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004925 >>> ExtendedContext.minus(1)
4926 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004927 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004928 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004929 return a.__neg__(context=self)
4930
4931 def multiply(self, a, b):
4932 """multiply multiplies two operands.
4933
4934 If either operand is a special value then the general rules apply.
Mark Dickinson84230a12010-02-18 14:49:50 +00004935 Otherwise, the operands are multiplied together
4936 ('long multiplication'), resulting in a number which may be as long as
4937 the sum of the lengths of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004938
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004939 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004940 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004941 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004942 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004943 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004944 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004945 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004946 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004947 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004948 Decimal('4.28135971E+11')
Mark Dickinson84230a12010-02-18 14:49:50 +00004949 >>> ExtendedContext.multiply(7, 7)
4950 Decimal('49')
4951 >>> ExtendedContext.multiply(Decimal(7), 7)
4952 Decimal('49')
4953 >>> ExtendedContext.multiply(7, Decimal(7))
4954 Decimal('49')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004955 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004956 a = _convert_other(a, raiseit=True)
4957 r = a.__mul__(b, context=self)
4958 if r is NotImplemented:
4959 raise TypeError("Unable to convert %s to Decimal" % b)
4960 else:
4961 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004962
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004963 def next_minus(self, a):
4964 """Returns the largest representable number smaller than a.
4965
4966 >>> c = ExtendedContext.copy()
4967 >>> c.Emin = -999
4968 >>> c.Emax = 999
4969 >>> ExtendedContext.next_minus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004970 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004971 >>> c.next_minus(Decimal('1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004972 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004973 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004974 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004975 >>> c.next_minus(Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004976 Decimal('9.99999999E+999')
Mark Dickinson84230a12010-02-18 14:49:50 +00004977 >>> c.next_minus(1)
4978 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004979 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004980 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004981 return a.next_minus(context=self)
4982
4983 def next_plus(self, a):
4984 """Returns the smallest representable number larger than a.
4985
4986 >>> c = ExtendedContext.copy()
4987 >>> c.Emin = -999
4988 >>> c.Emax = 999
4989 >>> ExtendedContext.next_plus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004990 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004991 >>> c.next_plus(Decimal('-1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004992 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004993 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004994 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004995 >>> c.next_plus(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004996 Decimal('-9.99999999E+999')
Mark Dickinson84230a12010-02-18 14:49:50 +00004997 >>> c.next_plus(1)
4998 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004999 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005000 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005001 return a.next_plus(context=self)
5002
5003 def next_toward(self, a, b):
5004 """Returns the number closest to a, in direction towards b.
5005
5006 The result is the closest representable number from the first
5007 operand (but not the first operand) that is in the direction
5008 towards the second operand, unless the operands have the same
5009 value.
5010
5011 >>> c = ExtendedContext.copy()
5012 >>> c.Emin = -999
5013 >>> c.Emax = 999
5014 >>> c.next_toward(Decimal('1'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005015 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005016 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005017 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005018 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005019 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005020 >>> c.next_toward(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005021 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005022 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005023 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005024 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005025 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005026 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005027 Decimal('-0.00')
Mark Dickinson84230a12010-02-18 14:49:50 +00005028 >>> c.next_toward(0, 1)
5029 Decimal('1E-1007')
5030 >>> c.next_toward(Decimal(0), 1)
5031 Decimal('1E-1007')
5032 >>> c.next_toward(0, Decimal(1))
5033 Decimal('1E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005034 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005035 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005036 return a.next_toward(b, context=self)
5037
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005038 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00005039 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005040
5041 Essentially a plus operation with all trailing zeros removed from the
5042 result.
5043
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005044 >>> ExtendedContext.normalize(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005045 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005046 >>> ExtendedContext.normalize(Decimal('-2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005047 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005048 >>> ExtendedContext.normalize(Decimal('1.200'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005049 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005050 >>> ExtendedContext.normalize(Decimal('-120'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005051 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005052 >>> ExtendedContext.normalize(Decimal('120.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005053 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005054 >>> ExtendedContext.normalize(Decimal('0.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005055 Decimal('0')
Mark Dickinson84230a12010-02-18 14:49:50 +00005056 >>> ExtendedContext.normalize(6)
5057 Decimal('6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005058 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005059 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005060 return a.normalize(context=self)
5061
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005062 def number_class(self, a):
5063 """Returns an indication of the class of the operand.
5064
5065 The class is one of the following strings:
5066 -sNaN
5067 -NaN
5068 -Infinity
5069 -Normal
5070 -Subnormal
5071 -Zero
5072 +Zero
5073 +Subnormal
5074 +Normal
5075 +Infinity
5076
Stefan Krah1919b7e2012-03-21 18:25:23 +01005077 >>> c = ExtendedContext.copy()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005078 >>> c.Emin = -999
5079 >>> c.Emax = 999
5080 >>> c.number_class(Decimal('Infinity'))
5081 '+Infinity'
5082 >>> c.number_class(Decimal('1E-10'))
5083 '+Normal'
5084 >>> c.number_class(Decimal('2.50'))
5085 '+Normal'
5086 >>> c.number_class(Decimal('0.1E-999'))
5087 '+Subnormal'
5088 >>> c.number_class(Decimal('0'))
5089 '+Zero'
5090 >>> c.number_class(Decimal('-0'))
5091 '-Zero'
5092 >>> c.number_class(Decimal('-0.1E-999'))
5093 '-Subnormal'
5094 >>> c.number_class(Decimal('-1E-10'))
5095 '-Normal'
5096 >>> c.number_class(Decimal('-2.50'))
5097 '-Normal'
5098 >>> c.number_class(Decimal('-Infinity'))
5099 '-Infinity'
5100 >>> c.number_class(Decimal('NaN'))
5101 'NaN'
5102 >>> c.number_class(Decimal('-NaN'))
5103 'NaN'
5104 >>> c.number_class(Decimal('sNaN'))
5105 'sNaN'
Mark Dickinson84230a12010-02-18 14:49:50 +00005106 >>> c.number_class(123)
5107 '+Normal'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005108 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005109 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005110 return a.number_class(context=self)
5111
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005112 def plus(self, a):
5113 """Plus corresponds to unary prefix plus in Python.
5114
5115 The operation is evaluated using the same rules as add; the
5116 operation plus(a) is calculated as add('0', a) where the '0'
5117 has the same exponent as the operand.
5118
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005119 >>> ExtendedContext.plus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005120 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005121 >>> ExtendedContext.plus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005122 Decimal('-1.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005123 >>> ExtendedContext.plus(-1)
5124 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005125 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005126 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005127 return a.__pos__(context=self)
5128
5129 def power(self, a, b, modulo=None):
5130 """Raises a to the power of b, to modulo if given.
5131
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005132 With two arguments, compute a**b. If a is negative then b
5133 must be integral. The result will be inexact unless b is
5134 integral and the result is finite and can be expressed exactly
5135 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005136
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005137 With three arguments, compute (a**b) % modulo. For the
5138 three argument form, the following restrictions on the
5139 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005140
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005141 - all three arguments must be integral
5142 - b must be nonnegative
5143 - at least one of a or b must be nonzero
5144 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005145
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005146 The result of pow(a, b, modulo) is identical to the result
5147 that would be obtained by computing (a**b) % modulo with
5148 unbounded precision, but is computed more efficiently. It is
5149 always exact.
5150
5151 >>> c = ExtendedContext.copy()
5152 >>> c.Emin = -999
5153 >>> c.Emax = 999
5154 >>> c.power(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005155 Decimal('8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005156 >>> c.power(Decimal('-2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005157 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005158 >>> c.power(Decimal('2'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005159 Decimal('0.125')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005160 >>> c.power(Decimal('1.7'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005161 Decimal('69.7575744')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005162 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005163 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005164 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005165 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005166 >>> c.power(Decimal('Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005167 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005168 >>> c.power(Decimal('Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005169 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005170 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005171 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005172 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005173 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005174 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005175 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005176 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005177 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005178 >>> c.power(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005179 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005180
5181 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005182 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005183 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005184 Decimal('-11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005185 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005186 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005187 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005188 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005189 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005190 Decimal('11729830')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005191 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005192 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005193 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005194 Decimal('1')
Mark Dickinson84230a12010-02-18 14:49:50 +00005195 >>> ExtendedContext.power(7, 7)
5196 Decimal('823543')
5197 >>> ExtendedContext.power(Decimal(7), 7)
5198 Decimal('823543')
5199 >>> ExtendedContext.power(7, Decimal(7), 2)
5200 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005201 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005202 a = _convert_other(a, raiseit=True)
5203 r = a.__pow__(b, modulo, context=self)
5204 if r is NotImplemented:
5205 raise TypeError("Unable to convert %s to Decimal" % b)
5206 else:
5207 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005208
5209 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005210 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005211
5212 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00005213 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005214 exponent is being increased), multiplied by a positive power of ten (if
5215 the exponent is being decreased), or is unchanged (if the exponent is
5216 already equal to that of the right-hand operand).
5217
5218 Unlike other operations, if the length of the coefficient after the
5219 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00005220 operation condition is raised. This guarantees that, unless there is
5221 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005222 equal to that of the right-hand operand.
5223
5224 Also unlike other operations, quantize will never raise Underflow, even
5225 if the result is subnormal and inexact.
5226
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005227 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005228 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005229 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005230 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005231 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005232 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005233 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005234 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005235 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005236 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005237 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005238 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005239 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005240 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005241 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005242 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005243 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005244 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005245 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005246 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005247 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005248 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005249 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005250 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005251 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005252 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005253 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005254 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005255 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005256 Decimal('2E+2')
Mark Dickinson84230a12010-02-18 14:49:50 +00005257 >>> ExtendedContext.quantize(1, 2)
5258 Decimal('1')
5259 >>> ExtendedContext.quantize(Decimal(1), 2)
5260 Decimal('1')
5261 >>> ExtendedContext.quantize(1, Decimal(2))
5262 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005263 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005264 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005265 return a.quantize(b, context=self)
5266
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005267 def radix(self):
5268 """Just returns 10, as this is Decimal, :)
5269
5270 >>> ExtendedContext.radix()
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005271 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005272 """
5273 return Decimal(10)
5274
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005275 def remainder(self, a, b):
5276 """Returns the remainder from integer division.
5277
5278 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00005279 calculating integer division as described for divide-integer, rounded
5280 to precision digits if necessary. The sign of the result, if
5281 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005282
5283 This operation will fail under the same conditions as integer division
5284 (that is, if integer division on the same two operands would fail, the
5285 remainder cannot be calculated).
5286
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005287 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005288 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005289 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005290 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005291 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005292 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005293 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005294 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005295 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005296 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005297 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005298 Decimal('1.0')
Mark Dickinson84230a12010-02-18 14:49:50 +00005299 >>> ExtendedContext.remainder(22, 6)
5300 Decimal('4')
5301 >>> ExtendedContext.remainder(Decimal(22), 6)
5302 Decimal('4')
5303 >>> ExtendedContext.remainder(22, Decimal(6))
5304 Decimal('4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005305 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005306 a = _convert_other(a, raiseit=True)
5307 r = a.__mod__(b, context=self)
5308 if r is NotImplemented:
5309 raise TypeError("Unable to convert %s to Decimal" % b)
5310 else:
5311 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005312
5313 def remainder_near(self, a, b):
5314 """Returns to be "a - b * n", where n is the integer nearest the exact
5315 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00005316 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005317 sign of a.
5318
5319 This operation will fail under the same conditions as integer division
5320 (that is, if integer division on the same two operands would fail, the
5321 remainder cannot be calculated).
5322
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005323 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005324 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005325 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005326 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005327 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005328 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005329 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005330 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005331 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005332 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005333 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005334 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005335 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005336 Decimal('-0.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005337 >>> ExtendedContext.remainder_near(3, 11)
5338 Decimal('3')
5339 >>> ExtendedContext.remainder_near(Decimal(3), 11)
5340 Decimal('3')
5341 >>> ExtendedContext.remainder_near(3, Decimal(11))
5342 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005343 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005344 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005345 return a.remainder_near(b, context=self)
5346
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005347 def rotate(self, a, b):
5348 """Returns a rotated copy of a, b times.
5349
5350 The coefficient of the result is a rotated copy of the digits in
5351 the coefficient of the first operand. The number of places of
5352 rotation is taken from the absolute value of the second operand,
5353 with the rotation being to the left if the second operand is
5354 positive or to the right otherwise.
5355
5356 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005357 Decimal('400000003')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005358 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005359 Decimal('12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005360 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005361 Decimal('891234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005362 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005363 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005364 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005365 Decimal('345678912')
Mark Dickinson84230a12010-02-18 14:49:50 +00005366 >>> ExtendedContext.rotate(1333333, 1)
5367 Decimal('13333330')
5368 >>> ExtendedContext.rotate(Decimal(1333333), 1)
5369 Decimal('13333330')
5370 >>> ExtendedContext.rotate(1333333, Decimal(1))
5371 Decimal('13333330')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005372 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005373 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005374 return a.rotate(b, context=self)
5375
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005376 def same_quantum(self, a, b):
5377 """Returns True if the two operands have the same exponent.
5378
5379 The result is never affected by either the sign or the coefficient of
5380 either operand.
5381
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005382 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005383 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005384 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005385 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005386 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005387 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005388 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005389 True
Mark Dickinson84230a12010-02-18 14:49:50 +00005390 >>> ExtendedContext.same_quantum(10000, -1)
5391 True
5392 >>> ExtendedContext.same_quantum(Decimal(10000), -1)
5393 True
5394 >>> ExtendedContext.same_quantum(10000, Decimal(-1))
5395 True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005396 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005397 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005398 return a.same_quantum(b)
5399
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005400 def scaleb (self, a, b):
5401 """Returns the first operand after adding the second value its exp.
5402
5403 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005404 Decimal('0.0750')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005405 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005406 Decimal('7.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005407 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005408 Decimal('7.50E+3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005409 >>> ExtendedContext.scaleb(1, 4)
5410 Decimal('1E+4')
5411 >>> ExtendedContext.scaleb(Decimal(1), 4)
5412 Decimal('1E+4')
5413 >>> ExtendedContext.scaleb(1, Decimal(4))
5414 Decimal('1E+4')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005415 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005416 a = _convert_other(a, raiseit=True)
5417 return a.scaleb(b, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005418
5419 def shift(self, a, b):
5420 """Returns a shifted copy of a, b times.
5421
5422 The coefficient of the result is a shifted copy of the digits
5423 in the coefficient of the first operand. The number of places
5424 to shift is taken from the absolute value of the second operand,
5425 with the shift being to the left if the second operand is
5426 positive or to the right otherwise. Digits shifted into the
5427 coefficient are zeros.
5428
5429 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005430 Decimal('400000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005431 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005432 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005433 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005434 Decimal('1234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005435 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005436 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005437 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005438 Decimal('345678900')
Mark Dickinson84230a12010-02-18 14:49:50 +00005439 >>> ExtendedContext.shift(88888888, 2)
5440 Decimal('888888800')
5441 >>> ExtendedContext.shift(Decimal(88888888), 2)
5442 Decimal('888888800')
5443 >>> ExtendedContext.shift(88888888, Decimal(2))
5444 Decimal('888888800')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005445 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005446 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005447 return a.shift(b, context=self)
5448
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005449 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005450 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005451
5452 If the result must be inexact, it is rounded using the round-half-even
5453 algorithm.
5454
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005455 >>> ExtendedContext.sqrt(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005456 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005457 >>> ExtendedContext.sqrt(Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005458 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005459 >>> ExtendedContext.sqrt(Decimal('0.39'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005460 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005461 >>> ExtendedContext.sqrt(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005462 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005463 >>> ExtendedContext.sqrt(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005464 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005465 >>> ExtendedContext.sqrt(Decimal('1.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005466 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005467 >>> ExtendedContext.sqrt(Decimal('1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005468 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005469 >>> ExtendedContext.sqrt(Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005470 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005471 >>> ExtendedContext.sqrt(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005472 Decimal('3.16227766')
Mark Dickinson84230a12010-02-18 14:49:50 +00005473 >>> ExtendedContext.sqrt(2)
5474 Decimal('1.41421356')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005475 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005476 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005477 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005478 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005479 return a.sqrt(context=self)
5480
5481 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00005482 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005483
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005484 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005485 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005486 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005487 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005488 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005489 Decimal('-0.77')
Mark Dickinson84230a12010-02-18 14:49:50 +00005490 >>> ExtendedContext.subtract(8, 5)
5491 Decimal('3')
5492 >>> ExtendedContext.subtract(Decimal(8), 5)
5493 Decimal('3')
5494 >>> ExtendedContext.subtract(8, Decimal(5))
5495 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005496 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005497 a = _convert_other(a, raiseit=True)
5498 r = a.__sub__(b, context=self)
5499 if r is NotImplemented:
5500 raise TypeError("Unable to convert %s to Decimal" % b)
5501 else:
5502 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005503
5504 def to_eng_string(self, a):
5505 """Converts a number to a string, using scientific notation.
5506
5507 The operation is not affected by the context.
5508 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005509 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005510 return a.to_eng_string(context=self)
5511
5512 def to_sci_string(self, a):
5513 """Converts a number to a string, using scientific notation.
5514
5515 The operation is not affected by the context.
5516 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005517 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005518 return a.__str__(context=self)
5519
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005520 def to_integral_exact(self, a):
5521 """Rounds to an integer.
5522
5523 When the operand has a negative exponent, the result is the same
5524 as using the quantize() operation using the given operand as the
5525 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5526 of the operand as the precision setting; Inexact and Rounded flags
5527 are allowed in this operation. The rounding mode is taken from the
5528 context.
5529
5530 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005531 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005532 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005533 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005534 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005535 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005536 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005537 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005538 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005539 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005540 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005541 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005542 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005543 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005544 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005545 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005546 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005547 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005548 return a.to_integral_exact(context=self)
5549
5550 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005551 """Rounds to an integer.
5552
5553 When the operand has a negative exponent, the result is the same
5554 as using the quantize() operation using the given operand as the
5555 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5556 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00005557 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005558
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005559 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005560 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005561 >>> ExtendedContext.to_integral_value(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005562 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005563 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005564 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005565 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005566 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005567 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005568 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005569 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005570 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005571 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005572 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005573 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005574 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005575 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005576 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005577 return a.to_integral_value(context=self)
5578
5579 # the method name changed, but we provide also the old one, for compatibility
5580 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005581
5582class _WorkRep(object):
5583 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00005584 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005585 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005586 # exp: None, int, or string
5587
5588 def __init__(self, value=None):
5589 if value is None:
5590 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005591 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005592 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00005593 elif isinstance(value, Decimal):
5594 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005595 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005596 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00005597 else:
5598 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005599 self.sign = value[0]
5600 self.int = value[1]
5601 self.exp = value[2]
5602
5603 def __repr__(self):
5604 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5605
5606 __str__ = __repr__
5607
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005608
5609
Christian Heimes2c181612007-12-17 20:04:13 +00005610def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005611 """Normalizes op1, op2 to have the same exp and length of coefficient.
5612
5613 Done during addition.
5614 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005615 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005616 tmp = op2
5617 other = op1
5618 else:
5619 tmp = op1
5620 other = op2
5621
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005622 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5623 # Then adding 10**exp to tmp has the same effect (after rounding)
5624 # as adding any positive quantity smaller than 10**exp; similarly
5625 # for subtraction. So if other is smaller than 10**exp we replace
5626 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00005627 tmp_len = len(str(tmp.int))
5628 other_len = len(str(other.int))
5629 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5630 if other_len + other.exp - 1 < exp:
5631 other.int = 1
5632 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005633
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005634 tmp.int *= 10 ** (tmp.exp - other.exp)
5635 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005636 return op1, op2
5637
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005638##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005639
Raymond Hettingerdb213a22010-11-27 08:09:40 +00005640_nbits = int.bit_length
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005641
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01005642def _decimal_lshift_exact(n, e):
5643 """ Given integers n and e, return n * 10**e if it's an integer, else None.
5644
5645 The computation is designed to avoid computing large powers of 10
5646 unnecessarily.
5647
5648 >>> _decimal_lshift_exact(3, 4)
5649 30000
5650 >>> _decimal_lshift_exact(300, -999999999) # returns None
5651
5652 """
5653 if n == 0:
5654 return 0
5655 elif e >= 0:
5656 return n * 10**e
5657 else:
5658 # val_n = largest power of 10 dividing n.
5659 str_n = str(abs(n))
5660 val_n = len(str_n) - len(str_n.rstrip('0'))
5661 return None if val_n < -e else n // 10**-e
5662
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005663def _sqrt_nearest(n, a):
5664 """Closest integer to the square root of the positive integer n. a is
5665 an initial approximation to the square root. Any positive integer
5666 will do for a, but the closer a is to the square root of n the
5667 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005668
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005669 """
5670 if n <= 0 or a <= 0:
5671 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5672
5673 b=0
5674 while a != b:
5675 b, a = a, a--n//a>>1
5676 return a
5677
5678def _rshift_nearest(x, shift):
5679 """Given an integer x and a nonnegative integer shift, return closest
5680 integer to x / 2**shift; use round-to-even in case of a tie.
5681
5682 """
5683 b, q = 1 << shift, x >> shift
5684 return q + (2*(x & (b-1)) + (q&1) > b)
5685
5686def _div_nearest(a, b):
5687 """Closest integer to a/b, a and b positive integers; rounds to even
5688 in the case of a tie.
5689
5690 """
5691 q, r = divmod(a, b)
5692 return q + (2*r + (q&1) > b)
5693
5694def _ilog(x, M, L = 8):
5695 """Integer approximation to M*log(x/M), with absolute error boundable
5696 in terms only of x/M.
5697
5698 Given positive integers x and M, return an integer approximation to
5699 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5700 between the approximation and the exact result is at most 22. For
5701 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5702 both cases these are upper bounds on the error; it will usually be
5703 much smaller."""
5704
5705 # The basic algorithm is the following: let log1p be the function
5706 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5707 # the reduction
5708 #
5709 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5710 #
5711 # repeatedly until the argument to log1p is small (< 2**-L in
5712 # absolute value). For small y we can use the Taylor series
5713 # expansion
5714 #
5715 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5716 #
5717 # truncating at T such that y**T is small enough. The whole
5718 # computation is carried out in a form of fixed-point arithmetic,
5719 # with a real number z being represented by an integer
5720 # approximation to z*M. To avoid loss of precision, the y below
5721 # is actually an integer approximation to 2**R*y*M, where R is the
5722 # number of reductions performed so far.
5723
5724 y = x-M
5725 # argument reduction; R = number of reductions performed
5726 R = 0
5727 while (R <= L and abs(y) << L-R >= M or
5728 R > L and abs(y) >> R-L >= M):
5729 y = _div_nearest((M*y) << 1,
5730 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5731 R += 1
5732
5733 # Taylor series with T terms
5734 T = -int(-10*len(str(M))//(3*L))
5735 yshift = _rshift_nearest(y, R)
5736 w = _div_nearest(M, T)
5737 for k in range(T-1, 0, -1):
5738 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5739
5740 return _div_nearest(w*y, M)
5741
5742def _dlog10(c, e, p):
5743 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5744 approximation to 10**p * log10(c*10**e), with an absolute error of
5745 at most 1. Assumes that c*10**e is not exactly 1."""
5746
5747 # increase precision by 2; compensate for this by dividing
5748 # final result by 100
5749 p += 2
5750
5751 # write c*10**e as d*10**f with either:
5752 # f >= 0 and 1 <= d <= 10, or
5753 # f <= 0 and 0.1 <= d <= 1.
5754 # Thus for c*10**e close to 1, f = 0
5755 l = len(str(c))
5756 f = e+l - (e+l >= 1)
5757
5758 if p > 0:
5759 M = 10**p
5760 k = e+p-f
5761 if k >= 0:
5762 c *= 10**k
5763 else:
5764 c = _div_nearest(c, 10**-k)
5765
5766 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005767 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005768 log_d = _div_nearest(log_d*M, log_10)
5769 log_tenpower = f*M # exact
5770 else:
5771 log_d = 0 # error < 2.31
Neal Norwitz2f99b242008-08-24 05:48:10 +00005772 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005773
5774 return _div_nearest(log_tenpower+log_d, 100)
5775
5776def _dlog(c, e, p):
5777 """Given integers c, e and p with c > 0, compute an integer
5778 approximation to 10**p * log(c*10**e), with an absolute error of
5779 at most 1. Assumes that c*10**e is not exactly 1."""
5780
5781 # Increase precision by 2. The precision increase is compensated
5782 # for at the end with a division by 100.
5783 p += 2
5784
5785 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5786 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5787 # as 10**p * log(d) + 10**p*f * log(10).
5788 l = len(str(c))
5789 f = e+l - (e+l >= 1)
5790
5791 # compute approximation to 10**p*log(d), with error < 27
5792 if p > 0:
5793 k = e+p-f
5794 if k >= 0:
5795 c *= 10**k
5796 else:
5797 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5798
5799 # _ilog magnifies existing error in c by a factor of at most 10
5800 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5801 else:
5802 # p <= 0: just approximate the whole thing by 0; error < 2.31
5803 log_d = 0
5804
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005805 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005806 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005807 extra = len(str(abs(f)))-1
5808 if p + extra >= 0:
5809 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5810 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5811 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005812 else:
5813 f_log_ten = 0
5814 else:
5815 f_log_ten = 0
5816
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005817 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005818 return _div_nearest(f_log_ten + log_d, 100)
5819
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005820class _Log10Memoize(object):
5821 """Class to compute, store, and allow retrieval of, digits of the
5822 constant log(10) = 2.302585.... This constant is needed by
5823 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5824 def __init__(self):
5825 self.digits = "23025850929940456840179914546843642076011014886"
5826
5827 def getdigits(self, p):
5828 """Given an integer p >= 0, return floor(10**p)*log(10).
5829
5830 For example, self.getdigits(3) returns 2302.
5831 """
5832 # digits are stored as a string, for quick conversion to
5833 # integer in the case that we've already computed enough
5834 # digits; the stored digits should always be correct
5835 # (truncated, not rounded to nearest).
5836 if p < 0:
5837 raise ValueError("p should be nonnegative")
5838
5839 if p >= len(self.digits):
5840 # compute p+3, p+6, p+9, ... digits; continue until at
5841 # least one of the extra digits is nonzero
5842 extra = 3
5843 while True:
5844 # compute p+extra digits, correct to within 1ulp
5845 M = 10**(p+extra+2)
5846 digits = str(_div_nearest(_ilog(10*M, M), 100))
5847 if digits[-extra:] != '0'*extra:
5848 break
5849 extra += 3
5850 # keep all reliable digits so far; remove trailing zeros
5851 # and next nonzero digit
5852 self.digits = digits.rstrip('0')[:-1]
5853 return int(self.digits[:p+1])
5854
5855_log10_digits = _Log10Memoize().getdigits
5856
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005857def _iexp(x, M, L=8):
5858 """Given integers x and M, M > 0, such that x/M is small in absolute
5859 value, compute an integer approximation to M*exp(x/M). For 0 <=
5860 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5861 is usually much smaller)."""
5862
5863 # Algorithm: to compute exp(z) for a real number z, first divide z
5864 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5865 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5866 # series
5867 #
5868 # expm1(x) = x + x**2/2! + x**3/3! + ...
5869 #
5870 # Now use the identity
5871 #
5872 # expm1(2x) = expm1(x)*(expm1(x)+2)
5873 #
5874 # R times to compute the sequence expm1(z/2**R),
5875 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5876
5877 # Find R such that x/2**R/M <= 2**-L
5878 R = _nbits((x<<L)//M)
5879
5880 # Taylor series. (2**L)**T > M
5881 T = -int(-10*len(str(M))//(3*L))
5882 y = _div_nearest(x, T)
5883 Mshift = M<<R
5884 for i in range(T-1, 0, -1):
5885 y = _div_nearest(x*(Mshift + y), Mshift * i)
5886
5887 # Expansion
5888 for k in range(R-1, -1, -1):
5889 Mshift = M<<(k+2)
5890 y = _div_nearest(y*(y+Mshift), Mshift)
5891
5892 return M+y
5893
5894def _dexp(c, e, p):
5895 """Compute an approximation to exp(c*10**e), with p decimal places of
5896 precision.
5897
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005898 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005899
5900 10**(p-1) <= d <= 10**p, and
5901 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5902
5903 In other words, d*10**f is an approximation to exp(c*10**e) with p
5904 digits of precision, and with an error in d of at most 1. This is
5905 almost, but not quite, the same as the error being < 1ulp: when d
5906 = 10**(p-1) the error could be up to 10 ulp."""
5907
5908 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5909 p += 2
5910
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005911 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005912 extra = max(0, e + len(str(c)) - 1)
5913 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005914
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005915 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005916 # rounding down
5917 shift = e+q
5918 if shift >= 0:
5919 cshift = c*10**shift
5920 else:
5921 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005922 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005923
5924 # reduce remainder back to original precision
5925 rem = _div_nearest(rem, 10**extra)
5926
5927 # error in result of _iexp < 120; error after division < 0.62
5928 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5929
5930def _dpower(xc, xe, yc, ye, p):
5931 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5932 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5933
5934 10**(p-1) <= c <= 10**p, and
5935 (c-1)*10**e < x**y < (c+1)*10**e
5936
5937 in other words, c*10**e is an approximation to x**y with p digits
5938 of precision, and with an error in c of at most 1. (This is
5939 almost, but not quite, the same as the error being < 1ulp: when c
5940 == 10**(p-1) we can only guarantee error < 10ulp.)
5941
5942 We assume that: x is positive and not equal to 1, and y is nonzero.
5943 """
5944
5945 # Find b such that 10**(b-1) <= |y| <= 10**b
5946 b = len(str(abs(yc))) + ye
5947
5948 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5949 lxc = _dlog(xc, xe, p+b+1)
5950
5951 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5952 shift = ye-b
5953 if shift >= 0:
5954 pc = lxc*yc*10**shift
5955 else:
5956 pc = _div_nearest(lxc*yc, 10**-shift)
5957
5958 if pc == 0:
5959 # we prefer a result that isn't exactly 1; this makes it
5960 # easier to compute a correctly rounded result in __pow__
5961 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5962 coeff, exp = 10**(p-1)+1, 1-p
5963 else:
5964 coeff, exp = 10**p-1, -p
5965 else:
5966 coeff, exp = _dexp(pc, -(p+1), p+1)
5967 coeff = _div_nearest(coeff, 10)
5968 exp += 1
5969
5970 return coeff, exp
5971
5972def _log10_lb(c, correction = {
5973 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5974 '6': 23, '7': 16, '8': 10, '9': 5}):
5975 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5976 if c <= 0:
5977 raise ValueError("The argument to _log10_lb should be nonnegative.")
5978 str_c = str(c)
5979 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005980
Guido van Rossumd8faa362007-04-27 19:54:29 +00005981##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005982
Mark Dickinsonac256ab2010-04-03 11:08:14 +00005983def _convert_other(other, raiseit=False, allow_float=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005984 """Convert other to Decimal.
5985
5986 Verifies that it's ok to use in an implicit construction.
Mark Dickinsonac256ab2010-04-03 11:08:14 +00005987 If allow_float is true, allow conversion from float; this
5988 is used in the comparison methods (__eq__ and friends).
5989
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005990 """
5991 if isinstance(other, Decimal):
5992 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005993 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005994 return Decimal(other)
Mark Dickinsonac256ab2010-04-03 11:08:14 +00005995 if allow_float and isinstance(other, float):
5996 return Decimal.from_float(other)
5997
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005998 if raiseit:
5999 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00006000 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006001
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006002def _convert_for_comparison(self, other, equality_op=False):
6003 """Given a Decimal instance self and a Python object other, return
Mark Dickinson1c164a62010-06-11 16:49:20 +00006004 a pair (s, o) of Decimal instances such that "s op o" is
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006005 equivalent to "self op other" for any of the 6 comparison
6006 operators "op".
6007
6008 """
6009 if isinstance(other, Decimal):
6010 return self, other
6011
6012 # Comparison with a Rational instance (also includes integers):
6013 # self op n/d <=> self*d op n (for n and d integers, d positive).
6014 # A NaN or infinity can be left unchanged without affecting the
6015 # comparison result.
6016 if isinstance(other, _numbers.Rational):
6017 if not self._is_special:
6018 self = _dec_from_triple(self._sign,
6019 str(int(self._int) * other.denominator),
6020 self._exp)
6021 return self, Decimal(other.numerator)
6022
6023 # Comparisons with float and complex types. == and != comparisons
6024 # with complex numbers should succeed, returning either True or False
6025 # as appropriate. Other comparisons return NotImplemented.
6026 if equality_op and isinstance(other, _numbers.Complex) and other.imag == 0:
6027 other = other.real
6028 if isinstance(other, float):
Stefan Krah1919b7e2012-03-21 18:25:23 +01006029 context = getcontext()
6030 if equality_op:
6031 context.flags[FloatOperation] = 1
6032 else:
6033 context._raise_error(FloatOperation,
6034 "strict semantics for mixing floats and Decimals are enabled")
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006035 return self, Decimal.from_float(other)
6036 return NotImplemented, NotImplemented
6037
6038
Guido van Rossumd8faa362007-04-27 19:54:29 +00006039##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006040
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006041# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00006042# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006043
6044DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00006045 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006046 traps=[DivisionByZero, Overflow, InvalidOperation],
6047 flags=[],
Stefan Krah1919b7e2012-03-21 18:25:23 +01006048 Emax=999999,
6049 Emin=-999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00006050 capitals=1,
6051 clamp=0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006052)
6053
6054# Pre-made alternate contexts offered by the specification
6055# Don't change these; the user should be able to select these
6056# contexts and be able to reproduce results from other implementations
6057# of the spec.
6058
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00006059BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006060 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006061 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
6062 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006063)
6064
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00006065ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00006066 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006067 traps=[],
6068 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006069)
6070
6071
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006072##### crud for parsing strings #############################################
Christian Heimes23daade02008-02-25 12:39:23 +00006073#
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006074# Regular expression used for parsing numeric strings. Additional
6075# comments:
6076#
6077# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
6078# whitespace. But note that the specification disallows whitespace in
6079# a numeric string.
6080#
6081# 2. For finite numbers (not infinities and NaNs) the body of the
6082# number between the optional sign and the optional exponent must have
6083# at least one decimal digit, possibly after the decimal point. The
Mark Dickinson345adc42009-08-02 10:14:23 +00006084# lookahead expression '(?=\d|\.\d)' checks this.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006085
6086import re
Benjamin Peterson41181742008-07-02 20:22:54 +00006087_parser = re.compile(r""" # A numeric string consists of:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006088# \s*
Benjamin Peterson41181742008-07-02 20:22:54 +00006089 (?P<sign>[-+])? # an optional sign, followed by either...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006090 (
Mark Dickinson345adc42009-08-02 10:14:23 +00006091 (?=\d|\.\d) # ...a number (with at least one digit)
6092 (?P<int>\d*) # having a (possibly empty) integer part
6093 (\.(?P<frac>\d*))? # followed by an optional fractional part
6094 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006095 |
Benjamin Peterson41181742008-07-02 20:22:54 +00006096 Inf(inity)? # ...an infinity, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006097 |
Benjamin Peterson41181742008-07-02 20:22:54 +00006098 (?P<signal>s)? # ...an (optionally signaling)
6099 NaN # NaN
Mark Dickinson345adc42009-08-02 10:14:23 +00006100 (?P<diag>\d*) # with (possibly empty) diagnostic info.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006101 )
6102# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00006103 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006104""", re.VERBOSE | re.IGNORECASE).match
6105
Christian Heimescbf3b5c2007-12-03 21:02:03 +00006106_all_zeros = re.compile('0*$').match
6107_exact_half = re.compile('50*$').match
Christian Heimesf16baeb2008-02-29 14:57:44 +00006108
6109##### PEP3101 support functions ##############################################
Mark Dickinson79f52032009-03-17 23:12:51 +00006110# The functions in this section have little to do with the Decimal
6111# class, and could potentially be reused or adapted for other pure
Christian Heimesf16baeb2008-02-29 14:57:44 +00006112# Python numeric classes that want to implement __format__
6113#
6114# A format specifier for Decimal looks like:
6115#
Eric Smith984bb582010-11-25 16:08:06 +00006116# [[fill]align][sign][#][0][minimumwidth][,][.precision][type]
Christian Heimesf16baeb2008-02-29 14:57:44 +00006117
6118_parse_format_specifier_regex = re.compile(r"""\A
6119(?:
6120 (?P<fill>.)?
6121 (?P<align>[<>=^])
6122)?
6123(?P<sign>[-+ ])?
Eric Smith984bb582010-11-25 16:08:06 +00006124(?P<alt>\#)?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006125(?P<zeropad>0)?
6126(?P<minimumwidth>(?!0)\d+)?
Mark Dickinson79f52032009-03-17 23:12:51 +00006127(?P<thousands_sep>,)?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006128(?:\.(?P<precision>0|(?!0)\d+))?
Mark Dickinson79f52032009-03-17 23:12:51 +00006129(?P<type>[eEfFgGn%])?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006130\Z
Stefan Krah6edda142013-05-29 15:45:38 +02006131""", re.VERBOSE|re.DOTALL)
Christian Heimesf16baeb2008-02-29 14:57:44 +00006132
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006133del re
6134
Mark Dickinson79f52032009-03-17 23:12:51 +00006135# The locale module is only needed for the 'n' format specifier. The
6136# rest of the PEP 3101 code functions quite happily without it, so we
6137# don't care too much if locale isn't present.
6138try:
6139 import locale as _locale
Brett Cannoncd171c82013-07-04 17:43:24 -04006140except ImportError:
Mark Dickinson79f52032009-03-17 23:12:51 +00006141 pass
6142
6143def _parse_format_specifier(format_spec, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00006144 """Parse and validate a format specifier.
6145
6146 Turns a standard numeric format specifier into a dict, with the
6147 following entries:
6148
6149 fill: fill character to pad field to minimum width
6150 align: alignment type, either '<', '>', '=' or '^'
6151 sign: either '+', '-' or ' '
6152 minimumwidth: nonnegative integer giving minimum width
Mark Dickinson79f52032009-03-17 23:12:51 +00006153 zeropad: boolean, indicating whether to pad with zeros
6154 thousands_sep: string to use as thousands separator, or ''
6155 grouping: grouping for thousands separators, in format
6156 used by localeconv
6157 decimal_point: string to use for decimal point
Christian Heimesf16baeb2008-02-29 14:57:44 +00006158 precision: nonnegative integer giving precision, or None
6159 type: one of the characters 'eEfFgG%', or None
Christian Heimesf16baeb2008-02-29 14:57:44 +00006160
6161 """
6162 m = _parse_format_specifier_regex.match(format_spec)
6163 if m is None:
6164 raise ValueError("Invalid format specifier: " + format_spec)
6165
6166 # get the dictionary
6167 format_dict = m.groupdict()
6168
Mark Dickinson79f52032009-03-17 23:12:51 +00006169 # zeropad; defaults for fill and alignment. If zero padding
6170 # is requested, the fill and align fields should be absent.
Christian Heimesf16baeb2008-02-29 14:57:44 +00006171 fill = format_dict['fill']
6172 align = format_dict['align']
Mark Dickinson79f52032009-03-17 23:12:51 +00006173 format_dict['zeropad'] = (format_dict['zeropad'] is not None)
6174 if format_dict['zeropad']:
6175 if fill is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00006176 raise ValueError("Fill character conflicts with '0'"
6177 " in format specifier: " + format_spec)
Mark Dickinson79f52032009-03-17 23:12:51 +00006178 if align is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00006179 raise ValueError("Alignment conflicts with '0' in "
6180 "format specifier: " + format_spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00006181 format_dict['fill'] = fill or ' '
Mark Dickinson46ab5d02009-09-08 20:22:46 +00006182 # PEP 3101 originally specified that the default alignment should
6183 # be left; it was later agreed that right-aligned makes more sense
6184 # for numeric types. See http://bugs.python.org/issue6857.
6185 format_dict['align'] = align or '>'
Christian Heimesf16baeb2008-02-29 14:57:44 +00006186
Mark Dickinson79f52032009-03-17 23:12:51 +00006187 # default sign handling: '-' for negative, '' for positive
Christian Heimesf16baeb2008-02-29 14:57:44 +00006188 if format_dict['sign'] is None:
6189 format_dict['sign'] = '-'
6190
Christian Heimesf16baeb2008-02-29 14:57:44 +00006191 # minimumwidth defaults to 0; precision remains None if not given
6192 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
6193 if format_dict['precision'] is not None:
6194 format_dict['precision'] = int(format_dict['precision'])
6195
6196 # if format type is 'g' or 'G' then a precision of 0 makes little
6197 # sense; convert it to 1. Same if format type is unspecified.
6198 if format_dict['precision'] == 0:
Stefan Krah1919b7e2012-03-21 18:25:23 +01006199 if format_dict['type'] is None or format_dict['type'] in 'gGn':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006200 format_dict['precision'] = 1
6201
Mark Dickinson79f52032009-03-17 23:12:51 +00006202 # determine thousands separator, grouping, and decimal separator, and
6203 # add appropriate entries to format_dict
6204 if format_dict['type'] == 'n':
6205 # apart from separators, 'n' behaves just like 'g'
6206 format_dict['type'] = 'g'
6207 if _localeconv is None:
6208 _localeconv = _locale.localeconv()
6209 if format_dict['thousands_sep'] is not None:
6210 raise ValueError("Explicit thousands separator conflicts with "
6211 "'n' type in format specifier: " + format_spec)
6212 format_dict['thousands_sep'] = _localeconv['thousands_sep']
6213 format_dict['grouping'] = _localeconv['grouping']
6214 format_dict['decimal_point'] = _localeconv['decimal_point']
6215 else:
6216 if format_dict['thousands_sep'] is None:
6217 format_dict['thousands_sep'] = ''
6218 format_dict['grouping'] = [3, 0]
6219 format_dict['decimal_point'] = '.'
Christian Heimesf16baeb2008-02-29 14:57:44 +00006220
6221 return format_dict
6222
Mark Dickinson79f52032009-03-17 23:12:51 +00006223def _format_align(sign, body, spec):
6224 """Given an unpadded, non-aligned numeric string 'body' and sign
Ezio Melotti42da6632011-03-15 05:18:48 +02006225 string 'sign', add padding and alignment conforming to the given
Mark Dickinson79f52032009-03-17 23:12:51 +00006226 format specifier dictionary 'spec' (as produced by
6227 parse_format_specifier).
Christian Heimesf16baeb2008-02-29 14:57:44 +00006228
6229 """
Christian Heimesf16baeb2008-02-29 14:57:44 +00006230 # how much extra space do we have to play with?
Mark Dickinson79f52032009-03-17 23:12:51 +00006231 minimumwidth = spec['minimumwidth']
6232 fill = spec['fill']
6233 padding = fill*(minimumwidth - len(sign) - len(body))
Christian Heimesf16baeb2008-02-29 14:57:44 +00006234
Mark Dickinson79f52032009-03-17 23:12:51 +00006235 align = spec['align']
Christian Heimesf16baeb2008-02-29 14:57:44 +00006236 if align == '<':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006237 result = sign + body + padding
Mark Dickinsonad416342009-03-17 18:10:15 +00006238 elif align == '>':
6239 result = padding + sign + body
Christian Heimesf16baeb2008-02-29 14:57:44 +00006240 elif align == '=':
6241 result = sign + padding + body
Mark Dickinson79f52032009-03-17 23:12:51 +00006242 elif align == '^':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006243 half = len(padding)//2
6244 result = padding[:half] + sign + body + padding[half:]
Mark Dickinson79f52032009-03-17 23:12:51 +00006245 else:
6246 raise ValueError('Unrecognised alignment field')
Christian Heimesf16baeb2008-02-29 14:57:44 +00006247
Christian Heimesf16baeb2008-02-29 14:57:44 +00006248 return result
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006249
Mark Dickinson79f52032009-03-17 23:12:51 +00006250def _group_lengths(grouping):
6251 """Convert a localeconv-style grouping into a (possibly infinite)
6252 iterable of integers representing group lengths.
6253
6254 """
6255 # The result from localeconv()['grouping'], and the input to this
6256 # function, should be a list of integers in one of the
6257 # following three forms:
6258 #
6259 # (1) an empty list, or
6260 # (2) nonempty list of positive integers + [0]
6261 # (3) list of positive integers + [locale.CHAR_MAX], or
6262
6263 from itertools import chain, repeat
6264 if not grouping:
6265 return []
6266 elif grouping[-1] == 0 and len(grouping) >= 2:
6267 return chain(grouping[:-1], repeat(grouping[-2]))
6268 elif grouping[-1] == _locale.CHAR_MAX:
6269 return grouping[:-1]
6270 else:
6271 raise ValueError('unrecognised format for grouping')
6272
6273def _insert_thousands_sep(digits, spec, min_width=1):
6274 """Insert thousands separators into a digit string.
6275
6276 spec is a dictionary whose keys should include 'thousands_sep' and
6277 'grouping'; typically it's the result of parsing the format
6278 specifier using _parse_format_specifier.
6279
6280 The min_width keyword argument gives the minimum length of the
6281 result, which will be padded on the left with zeros if necessary.
6282
6283 If necessary, the zero padding adds an extra '0' on the left to
6284 avoid a leading thousands separator. For example, inserting
6285 commas every three digits in '123456', with min_width=8, gives
6286 '0,123,456', even though that has length 9.
6287
6288 """
6289
6290 sep = spec['thousands_sep']
6291 grouping = spec['grouping']
6292
6293 groups = []
6294 for l in _group_lengths(grouping):
Mark Dickinson79f52032009-03-17 23:12:51 +00006295 if l <= 0:
6296 raise ValueError("group length should be positive")
6297 # max(..., 1) forces at least 1 digit to the left of a separator
6298 l = min(max(len(digits), min_width, 1), l)
6299 groups.append('0'*(l - len(digits)) + digits[-l:])
6300 digits = digits[:-l]
6301 min_width -= l
6302 if not digits and min_width <= 0:
6303 break
Mark Dickinson7303b592009-03-18 08:25:36 +00006304 min_width -= len(sep)
Mark Dickinson79f52032009-03-17 23:12:51 +00006305 else:
6306 l = max(len(digits), min_width, 1)
6307 groups.append('0'*(l - len(digits)) + digits[-l:])
6308 return sep.join(reversed(groups))
6309
6310def _format_sign(is_negative, spec):
6311 """Determine sign character."""
6312
6313 if is_negative:
6314 return '-'
6315 elif spec['sign'] in ' +':
6316 return spec['sign']
6317 else:
6318 return ''
6319
6320def _format_number(is_negative, intpart, fracpart, exp, spec):
6321 """Format a number, given the following data:
6322
6323 is_negative: true if the number is negative, else false
6324 intpart: string of digits that must appear before the decimal point
6325 fracpart: string of digits that must come after the point
6326 exp: exponent, as an integer
6327 spec: dictionary resulting from parsing the format specifier
6328
6329 This function uses the information in spec to:
6330 insert separators (decimal separator and thousands separators)
6331 format the sign
6332 format the exponent
6333 add trailing '%' for the '%' type
6334 zero-pad if necessary
6335 fill and align if necessary
6336 """
6337
6338 sign = _format_sign(is_negative, spec)
6339
Eric Smith984bb582010-11-25 16:08:06 +00006340 if fracpart or spec['alt']:
Mark Dickinson79f52032009-03-17 23:12:51 +00006341 fracpart = spec['decimal_point'] + fracpart
6342
6343 if exp != 0 or spec['type'] in 'eE':
6344 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
6345 fracpart += "{0}{1:+}".format(echar, exp)
6346 if spec['type'] == '%':
6347 fracpart += '%'
6348
6349 if spec['zeropad']:
6350 min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
6351 else:
6352 min_width = 0
6353 intpart = _insert_thousands_sep(intpart, spec, min_width)
6354
6355 return _format_align(sign, intpart+fracpart, spec)
6356
6357
Guido van Rossumd8faa362007-04-27 19:54:29 +00006358##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006359
Guido van Rossumd8faa362007-04-27 19:54:29 +00006360# Reusable defaults
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006361_Infinity = Decimal('Inf')
6362_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonf9236412009-01-02 23:23:21 +00006363_NaN = Decimal('NaN')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006364_Zero = Decimal(0)
6365_One = Decimal(1)
6366_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006367
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006368# _SignedInfinity[sign] is infinity w/ that sign
6369_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006370
Mark Dickinsondc787d22010-05-23 13:33:13 +00006371# Constants related to the hash implementation; hash(x) is based
6372# on the reduction of x modulo _PyHASH_MODULUS
Mark Dickinsondc787d22010-05-23 13:33:13 +00006373_PyHASH_MODULUS = sys.hash_info.modulus
6374# hash values to use for positive and negative infinities, and nans
6375_PyHASH_INF = sys.hash_info.inf
6376_PyHASH_NAN = sys.hash_info.nan
Mark Dickinsondc787d22010-05-23 13:33:13 +00006377
6378# _PyHASH_10INV is the inverse of 10 modulo the prime _PyHASH_MODULUS
6379_PyHASH_10INV = pow(10, _PyHASH_MODULUS - 2, _PyHASH_MODULUS)
Stefan Krah1919b7e2012-03-21 18:25:23 +01006380del sys
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006381
Stefan Krah1919b7e2012-03-21 18:25:23 +01006382try:
6383 import _decimal
Brett Cannoncd171c82013-07-04 17:43:24 -04006384except ImportError:
Stefan Krah1919b7e2012-03-21 18:25:23 +01006385 pass
6386else:
6387 s1 = set(dir())
6388 s2 = set(dir(_decimal))
6389 for name in s1 - s2:
6390 del globals()[name]
6391 del s1, s2, name
6392 from _decimal import *
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006393
6394if __name__ == '__main__':
Raymond Hettinger6d7e26e2011-02-01 23:54:43 +00006395 import doctest, decimal
6396 doctest.testmod(decimal)