blob: 746b34a8946a892b72ebd718b9e6b132afd78c88 [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
24 www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
25
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/
Raymond Hettinger960dc362009-04-21 03:43:15 +0000143
Raymond Hettingereb260842005-06-07 18:52:34 +0000144import copy as _copy
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')
152except ImportError:
153 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
433except ImportError:
434 # 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 Dickinsonba298e42009-01-04 21:17:43 +0000706 # @classmethod, but @decorator is not valid Python 2.3 syntax, so
707 # don't use it (see notes on Py2.3 compatibility at top of file)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000708 def from_float(cls, f):
709 """Converts a float to a decimal number, exactly.
710
711 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
712 Since 0.1 is not exactly representable in binary floating point, the
713 value is stored as the nearest representable value which is
714 0x1.999999999999ap-4. The exact equivalent of the value in decimal
715 is 0.1000000000000000055511151231257827021181583404541015625.
716
717 >>> Decimal.from_float(0.1)
718 Decimal('0.1000000000000000055511151231257827021181583404541015625')
719 >>> Decimal.from_float(float('nan'))
720 Decimal('NaN')
721 >>> Decimal.from_float(float('inf'))
722 Decimal('Infinity')
723 >>> Decimal.from_float(-float('inf'))
724 Decimal('-Infinity')
725 >>> Decimal.from_float(-0.0)
726 Decimal('-0')
727
728 """
729 if isinstance(f, int): # handle integer inputs
730 return cls(f)
Stefan Krah1919b7e2012-03-21 18:25:23 +0100731 if not isinstance(f, float):
732 raise TypeError("argument must be int or float.")
733 if _math.isinf(f) or _math.isnan(f):
Raymond Hettinger771ed762009-01-03 19:20:32 +0000734 return cls(repr(f))
Mark Dickinsonba298e42009-01-04 21:17:43 +0000735 if _math.copysign(1.0, f) == 1.0:
736 sign = 0
737 else:
738 sign = 1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000739 n, d = abs(f).as_integer_ratio()
740 k = d.bit_length() - 1
741 result = _dec_from_triple(sign, str(n*5**k), -k)
Mark Dickinsonba298e42009-01-04 21:17:43 +0000742 if cls is Decimal:
743 return result
744 else:
745 return cls(result)
746 from_float = classmethod(from_float)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000747
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000748 def _isnan(self):
749 """Returns whether the number is not actually one.
750
751 0 if a number
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000752 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000753 2 if sNaN
754 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000755 if self._is_special:
756 exp = self._exp
757 if exp == 'n':
758 return 1
759 elif exp == 'N':
760 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000761 return 0
762
763 def _isinfinity(self):
764 """Returns whether the number is infinite
765
766 0 if finite or not a number
767 1 if +INF
768 -1 if -INF
769 """
770 if self._exp == 'F':
771 if self._sign:
772 return -1
773 return 1
774 return 0
775
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000776 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000777 """Returns whether the number is not actually one.
778
779 if self, other are sNaN, signal
780 if self, other are NaN return nan
781 return 0
782
783 Done before operations.
784 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000785
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000786 self_is_nan = self._isnan()
787 if other is None:
788 other_is_nan = False
789 else:
790 other_is_nan = other._isnan()
791
792 if self_is_nan or other_is_nan:
793 if context is None:
794 context = getcontext()
795
796 if self_is_nan == 2:
797 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000798 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000799 if other_is_nan == 2:
800 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000801 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000802 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000803 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000804
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000805 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000806 return 0
807
Christian Heimes77c02eb2008-02-09 02:18:51 +0000808 def _compare_check_nans(self, other, context):
809 """Version of _check_nans used for the signaling comparisons
810 compare_signal, __le__, __lt__, __ge__, __gt__.
811
812 Signal InvalidOperation if either self or other is a (quiet
813 or signaling) NaN. Signaling NaNs take precedence over quiet
814 NaNs.
815
816 Return 0 if neither operand is a NaN.
817
818 """
819 if context is None:
820 context = getcontext()
821
822 if self._is_special or other._is_special:
823 if self.is_snan():
824 return context._raise_error(InvalidOperation,
825 'comparison involving sNaN',
826 self)
827 elif other.is_snan():
828 return context._raise_error(InvalidOperation,
829 'comparison involving sNaN',
830 other)
831 elif self.is_qnan():
832 return context._raise_error(InvalidOperation,
833 'comparison involving NaN',
834 self)
835 elif other.is_qnan():
836 return context._raise_error(InvalidOperation,
837 'comparison involving NaN',
838 other)
839 return 0
840
Jack Diederich4dafcc42006-11-28 19:15:13 +0000841 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000842 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000843
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000844 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000845 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000846 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000847
Christian Heimes77c02eb2008-02-09 02:18:51 +0000848 def _cmp(self, other):
849 """Compare the two non-NaN decimal instances self and other.
850
851 Returns -1 if self < other, 0 if self == other and 1
852 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000853
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000854 if self._is_special or other._is_special:
Mark Dickinsone6aad752009-01-25 10:48:51 +0000855 self_inf = self._isinfinity()
856 other_inf = other._isinfinity()
857 if self_inf == other_inf:
858 return 0
859 elif self_inf < other_inf:
860 return -1
861 else:
862 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000863
Mark Dickinsone6aad752009-01-25 10:48:51 +0000864 # check for zeros; Decimal('0') == Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000865 if not self:
866 if not other:
867 return 0
868 else:
869 return -((-1)**other._sign)
870 if not other:
871 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000872
Guido van Rossumd8faa362007-04-27 19:54:29 +0000873 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000874 if other._sign < self._sign:
875 return -1
876 if self._sign < other._sign:
877 return 1
878
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000879 self_adjusted = self.adjusted()
880 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000881 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000882 self_padded = self._int + '0'*(self._exp - other._exp)
883 other_padded = other._int + '0'*(other._exp - self._exp)
Mark Dickinsone6aad752009-01-25 10:48:51 +0000884 if self_padded == other_padded:
885 return 0
886 elif self_padded < other_padded:
887 return -(-1)**self._sign
888 else:
889 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000891 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000892 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000893 return -((-1)**self._sign)
894
Christian Heimes77c02eb2008-02-09 02:18:51 +0000895 # Note: The Decimal standard doesn't cover rich comparisons for
896 # Decimals. In particular, the specification is silent on the
897 # subject of what should happen for a comparison involving a NaN.
898 # We take the following approach:
899 #
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000900 # == comparisons involving a quiet NaN always return False
901 # != comparisons involving a quiet NaN always return True
902 # == or != comparisons involving a signaling NaN signal
903 # InvalidOperation, and return False or True as above if the
904 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000905 # <, >, <= and >= comparisons involving a (quiet or signaling)
906 # NaN signal InvalidOperation, and return False if the
Christian Heimes3feef612008-02-11 06:19:17 +0000907 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000908 #
909 # This behavior is designed to conform as closely as possible to
910 # that specified by IEEE 754.
911
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000912 def __eq__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000913 self, other = _convert_for_comparison(self, other, equality_op=True)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000914 if other is NotImplemented:
915 return other
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000916 if self._check_nans(other, context):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000917 return False
918 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000919
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000920 def __ne__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000921 self, other = _convert_for_comparison(self, other, equality_op=True)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000922 if other is NotImplemented:
923 return other
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000924 if self._check_nans(other, context):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000925 return True
926 return self._cmp(other) != 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000927
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000928
Christian Heimes77c02eb2008-02-09 02:18:51 +0000929 def __lt__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000930 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000931 if other is NotImplemented:
932 return other
933 ans = self._compare_check_nans(other, context)
934 if ans:
935 return False
936 return self._cmp(other) < 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000937
Christian Heimes77c02eb2008-02-09 02:18:51 +0000938 def __le__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000939 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000940 if other is NotImplemented:
941 return other
942 ans = self._compare_check_nans(other, context)
943 if ans:
944 return False
945 return self._cmp(other) <= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000946
Christian Heimes77c02eb2008-02-09 02:18:51 +0000947 def __gt__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000948 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000949 if other is NotImplemented:
950 return other
951 ans = self._compare_check_nans(other, context)
952 if ans:
953 return False
954 return self._cmp(other) > 0
955
956 def __ge__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000957 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000958 if other is NotImplemented:
959 return other
960 ans = self._compare_check_nans(other, context)
961 if ans:
962 return False
963 return self._cmp(other) >= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000964
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000965 def compare(self, other, context=None):
966 """Compares one to another.
967
968 -1 => a < b
969 0 => a = b
970 1 => a > b
971 NaN => one is NaN
972 Like __cmp__, but returns Decimal instances.
973 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000974 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000975
Guido van Rossumd8faa362007-04-27 19:54:29 +0000976 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000977 if (self._is_special or other and other._is_special):
978 ans = self._check_nans(other, context)
979 if ans:
980 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000981
Christian Heimes77c02eb2008-02-09 02:18:51 +0000982 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000983
984 def __hash__(self):
985 """x.__hash__() <==> hash(x)"""
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000986
Mark Dickinsondc787d22010-05-23 13:33:13 +0000987 # In order to make sure that the hash of a Decimal instance
988 # agrees with the hash of a numerically equal integer, float
989 # or Fraction, we follow the rules for numeric hashes outlined
990 # in the documentation. (See library docs, 'Built-in Types').
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000991 if self._is_special:
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000992 if self.is_snan():
Raymond Hettingerd325c4b2010-11-21 04:08:28 +0000993 raise TypeError('Cannot hash a signaling NaN value.')
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000994 elif self.is_nan():
Mark Dickinsondc787d22010-05-23 13:33:13 +0000995 return _PyHASH_NAN
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000996 else:
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000997 if self._sign:
Mark Dickinsondc787d22010-05-23 13:33:13 +0000998 return -_PyHASH_INF
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000999 else:
Mark Dickinsondc787d22010-05-23 13:33:13 +00001000 return _PyHASH_INF
Mark Dickinsonac256ab2010-04-03 11:08:14 +00001001
Mark Dickinsondc787d22010-05-23 13:33:13 +00001002 if self._exp >= 0:
1003 exp_hash = pow(10, self._exp, _PyHASH_MODULUS)
1004 else:
1005 exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS)
1006 hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS
Stefan Krahdc817b22010-11-17 11:16:34 +00001007 ans = hash_ if self >= 0 else -hash_
1008 return -2 if ans == -1 else ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001009
1010 def as_tuple(self):
1011 """Represents the number as a triple tuple.
1012
1013 To show the internals exactly as they are.
1014 """
Christian Heimes25bb7832008-01-11 16:17:00 +00001015 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001016
1017 def __repr__(self):
1018 """Represents the number as an instance of Decimal."""
1019 # Invariant: eval(repr(d)) == d
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001020 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001021
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001022 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001023 """Return string representation of the number in scientific notation.
1024
1025 Captures all of the information in the underlying representation.
1026 """
1027
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001028 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +00001029 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001030 if self._exp == 'F':
1031 return sign + 'Infinity'
1032 elif self._exp == 'n':
1033 return sign + 'NaN' + self._int
1034 else: # self._exp == 'N'
1035 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001036
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001037 # number of digits of self._int to left of decimal point
1038 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001039
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001040 # dotplace is number of digits of self._int to the left of the
1041 # decimal point in the mantissa of the output string (that is,
1042 # after adjusting the exponent)
1043 if self._exp <= 0 and leftdigits > -6:
1044 # no exponent required
1045 dotplace = leftdigits
1046 elif not eng:
1047 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001048 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001049 elif self._int == '0':
1050 # engineering notation, zero
1051 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001052 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001053 # engineering notation, nonzero
1054 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001055
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001056 if dotplace <= 0:
1057 intpart = '0'
1058 fracpart = '.' + '0'*(-dotplace) + self._int
1059 elif dotplace >= len(self._int):
1060 intpart = self._int+'0'*(dotplace-len(self._int))
1061 fracpart = ''
1062 else:
1063 intpart = self._int[:dotplace]
1064 fracpart = '.' + self._int[dotplace:]
1065 if leftdigits == dotplace:
1066 exp = ''
1067 else:
1068 if context is None:
1069 context = getcontext()
1070 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1071
1072 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001073
1074 def to_eng_string(self, context=None):
1075 """Convert to engineering-type string.
1076
1077 Engineering notation has an exponent which is a multiple of 3, so there
1078 are up to 3 digits left of the decimal place.
1079
1080 Same rules for when in exponential and when as a value as in __str__.
1081 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001082 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001083
1084 def __neg__(self, context=None):
1085 """Returns a copy with the sign switched.
1086
1087 Rounds, if it has reason.
1088 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001089 if self._is_special:
1090 ans = self._check_nans(context=context)
1091 if ans:
1092 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001093
Mark Dickinson37a79fb2011-03-12 11:12:52 +00001094 if context is None:
1095 context = getcontext()
1096
1097 if not self and context.rounding != ROUND_FLOOR:
1098 # -Decimal('0') is Decimal('0'), not Decimal('-0'), except
1099 # in ROUND_FLOOR rounding mode.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001100 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001101 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001102 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001103
Christian Heimes2c181612007-12-17 20:04:13 +00001104 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001105
1106 def __pos__(self, context=None):
1107 """Returns a copy, unless it is a sNaN.
1108
1109 Rounds the number (if more then precision digits)
1110 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001111 if self._is_special:
1112 ans = self._check_nans(context=context)
1113 if ans:
1114 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001115
Mark Dickinson37a79fb2011-03-12 11:12:52 +00001116 if context is None:
1117 context = getcontext()
1118
1119 if not self and context.rounding != ROUND_FLOOR:
1120 # + (-0) = 0, except in ROUND_FLOOR rounding mode.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001121 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001122 else:
1123 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001124
Christian Heimes2c181612007-12-17 20:04:13 +00001125 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001126
Christian Heimes2c181612007-12-17 20:04:13 +00001127 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001128 """Returns the absolute value of self.
1129
Christian Heimes2c181612007-12-17 20:04:13 +00001130 If the keyword argument 'round' is false, do not round. The
1131 expression self.__abs__(round=False) is equivalent to
1132 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001133 """
Christian Heimes2c181612007-12-17 20:04:13 +00001134 if not round:
1135 return self.copy_abs()
1136
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001137 if self._is_special:
1138 ans = self._check_nans(context=context)
1139 if ans:
1140 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001142 if self._sign:
1143 ans = self.__neg__(context=context)
1144 else:
1145 ans = self.__pos__(context=context)
1146
1147 return ans
1148
1149 def __add__(self, other, context=None):
1150 """Returns self + other.
1151
1152 -INF + INF (or the reverse) cause InvalidOperation errors.
1153 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001154 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001155 if other is NotImplemented:
1156 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001157
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001158 if context is None:
1159 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001160
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001161 if self._is_special or other._is_special:
1162 ans = self._check_nans(other, context)
1163 if ans:
1164 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001165
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001166 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001167 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001168 if self._sign != other._sign and other._isinfinity():
1169 return context._raise_error(InvalidOperation, '-INF + INF')
1170 return Decimal(self)
1171 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001172 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001173
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001174 exp = min(self._exp, other._exp)
1175 negativezero = 0
1176 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001177 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001178 negativezero = 1
1179
1180 if not self and not other:
1181 sign = min(self._sign, other._sign)
1182 if negativezero:
1183 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001184 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001185 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001186 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001187 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001188 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001189 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001190 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001191 return ans
1192 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001193 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001194 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001195 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001196 return ans
1197
1198 op1 = _WorkRep(self)
1199 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001200 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001201
1202 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001203 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001204 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001205 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001206 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001207 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001208 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001209 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001210 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001211 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001212 if op1.sign == 1:
1213 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001214 op1.sign, op2.sign = op2.sign, op1.sign
1215 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001216 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001217 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001218 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001219 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001220 op1.sign, op2.sign = (0, 0)
1221 else:
1222 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001223 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001224
Raymond Hettinger17931de2004-10-27 06:21:46 +00001225 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001226 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001227 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001228 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001229
1230 result.exp = op1.exp
1231 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001232 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001233 return ans
1234
1235 __radd__ = __add__
1236
1237 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001238 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001239 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001240 if other is NotImplemented:
1241 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001242
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001243 if self._is_special or other._is_special:
1244 ans = self._check_nans(other, context=context)
1245 if ans:
1246 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001247
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001248 # self - other is computed as self + other.copy_negate()
1249 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001250
1251 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001252 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001253 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001254 if other is NotImplemented:
1255 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001256
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001257 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001258
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001259 def __mul__(self, other, context=None):
1260 """Return self * other.
1261
1262 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1263 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001264 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001265 if other is NotImplemented:
1266 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001267
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001268 if context is None:
1269 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001270
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001271 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001272
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001273 if self._is_special or other._is_special:
1274 ans = self._check_nans(other, context)
1275 if ans:
1276 return ans
1277
1278 if self._isinfinity():
1279 if not other:
1280 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001281 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001282
1283 if other._isinfinity():
1284 if not self:
1285 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001286 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001287
1288 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001289
1290 # Special case for multiplying by zero
1291 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001292 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001293 # Fixing in case the exponent is out of bounds
1294 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001295 return ans
1296
1297 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001298 if self._int == '1':
1299 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001300 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001301 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001302 if other._int == '1':
1303 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001304 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001305 return ans
1306
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001307 op1 = _WorkRep(self)
1308 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001309
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001310 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001311 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001312
1313 return ans
1314 __rmul__ = __mul__
1315
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001316 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001317 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001318 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001319 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001320 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001321
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001322 if context is None:
1323 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001324
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001325 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001326
1327 if self._is_special or other._is_special:
1328 ans = self._check_nans(other, context)
1329 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001330 return ans
1331
1332 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001333 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001334
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001335 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001336 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001337
1338 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001339 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001340 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001341
1342 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001343 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001344 if not self:
1345 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001346 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001347
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001348 if not self:
1349 exp = self._exp - other._exp
1350 coeff = 0
1351 else:
1352 # OK, so neither = 0, INF or NaN
1353 shift = len(other._int) - len(self._int) + context.prec + 1
1354 exp = self._exp - other._exp - shift
1355 op1 = _WorkRep(self)
1356 op2 = _WorkRep(other)
1357 if shift >= 0:
1358 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1359 else:
1360 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1361 if remainder:
1362 # result is not exact; adjust to ensure correct rounding
1363 if coeff % 5 == 0:
1364 coeff += 1
1365 else:
1366 # result is exact; get as close to ideal exponent as possible
1367 ideal_exp = self._exp - other._exp
1368 while exp < ideal_exp and coeff % 10 == 0:
1369 coeff //= 10
1370 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001371
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001372 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001373 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001374
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001375 def _divide(self, other, context):
1376 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001377
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001378 Assumes that neither self nor other is a NaN, that self is not
1379 infinite and that other is nonzero.
1380 """
1381 sign = self._sign ^ other._sign
1382 if other._isinfinity():
1383 ideal_exp = self._exp
1384 else:
1385 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001386
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001387 expdiff = self.adjusted() - other.adjusted()
1388 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001389 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001390 self._rescale(ideal_exp, context.rounding))
1391 if expdiff <= context.prec:
1392 op1 = _WorkRep(self)
1393 op2 = _WorkRep(other)
1394 if op1.exp >= op2.exp:
1395 op1.int *= 10**(op1.exp - op2.exp)
1396 else:
1397 op2.int *= 10**(op2.exp - op1.exp)
1398 q, r = divmod(op1.int, op2.int)
1399 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001400 return (_dec_from_triple(sign, str(q), 0),
1401 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001402
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001403 # Here the quotient is too large to be representable
1404 ans = context._raise_error(DivisionImpossible,
1405 'quotient too large in //, % or divmod')
1406 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001407
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001408 def __rtruediv__(self, other, context=None):
1409 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001410 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001411 if other is NotImplemented:
1412 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001413 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001414
1415 def __divmod__(self, other, context=None):
1416 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001417 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001418 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001419 other = _convert_other(other)
1420 if other is NotImplemented:
1421 return other
1422
1423 if context is None:
1424 context = getcontext()
1425
1426 ans = self._check_nans(other, context)
1427 if ans:
1428 return (ans, ans)
1429
1430 sign = self._sign ^ other._sign
1431 if self._isinfinity():
1432 if other._isinfinity():
1433 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1434 return ans, ans
1435 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001436 return (_SignedInfinity[sign],
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001437 context._raise_error(InvalidOperation, 'INF % x'))
1438
1439 if not other:
1440 if not self:
1441 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1442 return ans, ans
1443 else:
1444 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1445 context._raise_error(InvalidOperation, 'x % 0'))
1446
1447 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001448 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001449 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001450
1451 def __rdivmod__(self, other, context=None):
1452 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001453 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001454 if other is NotImplemented:
1455 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001456 return other.__divmod__(self, context=context)
1457
1458 def __mod__(self, other, context=None):
1459 """
1460 self % other
1461 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001462 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001463 if other is NotImplemented:
1464 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001465
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001466 if context is None:
1467 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001468
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001469 ans = self._check_nans(other, context)
1470 if ans:
1471 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001472
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001473 if self._isinfinity():
1474 return context._raise_error(InvalidOperation, 'INF % x')
1475 elif not other:
1476 if self:
1477 return context._raise_error(InvalidOperation, 'x % 0')
1478 else:
1479 return context._raise_error(DivisionUndefined, '0 % 0')
1480
1481 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001482 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001483 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001484
1485 def __rmod__(self, other, context=None):
1486 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001487 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001488 if other is NotImplemented:
1489 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001490 return other.__mod__(self, context=context)
1491
1492 def remainder_near(self, other, context=None):
1493 """
1494 Remainder nearest to 0- abs(remainder-near) <= other/2
1495 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001496 if context is None:
1497 context = getcontext()
1498
1499 other = _convert_other(other, raiseit=True)
1500
1501 ans = self._check_nans(other, context)
1502 if ans:
1503 return ans
1504
1505 # self == +/-infinity -> InvalidOperation
1506 if self._isinfinity():
1507 return context._raise_error(InvalidOperation,
1508 'remainder_near(infinity, x)')
1509
1510 # other == 0 -> either InvalidOperation or DivisionUndefined
1511 if not other:
1512 if self:
1513 return context._raise_error(InvalidOperation,
1514 'remainder_near(x, 0)')
1515 else:
1516 return context._raise_error(DivisionUndefined,
1517 'remainder_near(0, 0)')
1518
1519 # other = +/-infinity -> remainder = self
1520 if other._isinfinity():
1521 ans = Decimal(self)
1522 return ans._fix(context)
1523
1524 # self = 0 -> remainder = self, with ideal exponent
1525 ideal_exponent = min(self._exp, other._exp)
1526 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001527 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001528 return ans._fix(context)
1529
1530 # catch most cases of large or small quotient
1531 expdiff = self.adjusted() - other.adjusted()
1532 if expdiff >= context.prec + 1:
1533 # expdiff >= prec+1 => abs(self/other) > 10**prec
1534 return context._raise_error(DivisionImpossible)
1535 if expdiff <= -2:
1536 # expdiff <= -2 => abs(self/other) < 0.1
1537 ans = self._rescale(ideal_exponent, context.rounding)
1538 return ans._fix(context)
1539
1540 # adjust both arguments to have the same exponent, then divide
1541 op1 = _WorkRep(self)
1542 op2 = _WorkRep(other)
1543 if op1.exp >= op2.exp:
1544 op1.int *= 10**(op1.exp - op2.exp)
1545 else:
1546 op2.int *= 10**(op2.exp - op1.exp)
1547 q, r = divmod(op1.int, op2.int)
1548 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1549 # 10**ideal_exponent. Apply correction to ensure that
1550 # abs(remainder) <= abs(other)/2
1551 if 2*r + (q&1) > op2.int:
1552 r -= op2.int
1553 q += 1
1554
1555 if q >= 10**context.prec:
1556 return context._raise_error(DivisionImpossible)
1557
1558 # result has same sign as self unless r is negative
1559 sign = self._sign
1560 if r < 0:
1561 sign = 1-sign
1562 r = -r
1563
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001564 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001565 return ans._fix(context)
1566
1567 def __floordiv__(self, other, context=None):
1568 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001569 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001570 if other is NotImplemented:
1571 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001572
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001573 if context is None:
1574 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001575
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001576 ans = self._check_nans(other, context)
1577 if ans:
1578 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001579
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001580 if self._isinfinity():
1581 if other._isinfinity():
1582 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001583 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001584 return _SignedInfinity[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001585
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001586 if not other:
1587 if self:
1588 return context._raise_error(DivisionByZero, 'x // 0',
1589 self._sign ^ other._sign)
1590 else:
1591 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001592
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001593 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001594
1595 def __rfloordiv__(self, other, context=None):
1596 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001597 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001598 if other is NotImplemented:
1599 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001600 return other.__floordiv__(self, context=context)
1601
1602 def __float__(self):
1603 """Float representation."""
Mark Dickinsonfc33d4c2012-08-24 18:53:10 +01001604 if self._isnan():
1605 if self.is_snan():
1606 raise ValueError("Cannot convert signaling NaN to float")
1607 s = "-nan" if self._sign else "nan"
1608 else:
1609 s = str(self)
1610 return float(s)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001611
1612 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001613 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001614 if self._is_special:
1615 if self._isnan():
Mark Dickinson825fce32009-09-07 18:08:12 +00001616 raise ValueError("Cannot convert NaN to integer")
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001617 elif self._isinfinity():
Mark Dickinson825fce32009-09-07 18:08:12 +00001618 raise OverflowError("Cannot convert infinity to integer")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001619 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001620 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001621 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001622 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001623 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001624
Christian Heimes969fe572008-01-25 11:23:10 +00001625 __trunc__ = __int__
1626
Christian Heimes0bd4e112008-02-12 22:59:25 +00001627 def real(self):
1628 return self
Mark Dickinson315a20a2009-01-04 21:34:18 +00001629 real = property(real)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001630
Christian Heimes0bd4e112008-02-12 22:59:25 +00001631 def imag(self):
1632 return Decimal(0)
Mark Dickinson315a20a2009-01-04 21:34:18 +00001633 imag = property(imag)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001634
1635 def conjugate(self):
1636 return self
1637
1638 def __complex__(self):
1639 return complex(float(self))
1640
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001641 def _fix_nan(self, context):
1642 """Decapitate the payload of a NaN to fit the context"""
1643 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001644
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001645 # maximum length of payload is precision if clamp=0,
1646 # precision-1 if clamp=1.
1647 max_payload_len = context.prec - context.clamp
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001648 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001649 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1650 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001651 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001652
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001653 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001654 """Round if it is necessary to keep self within prec precision.
1655
1656 Rounds and fixes the exponent. Does not raise on a sNaN.
1657
1658 Arguments:
1659 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001660 context - context used.
1661 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001662
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001663 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001664 if self._isnan():
1665 # decapitate payload if necessary
1666 return self._fix_nan(context)
1667 else:
1668 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001669 return Decimal(self)
1670
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001671 # if self is zero then exponent should be between Etiny and
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001672 # Emax if clamp==0, and between Etiny and Etop if clamp==1.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001673 Etiny = context.Etiny()
1674 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001675 if not self:
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001676 exp_max = [context.Emax, Etop][context.clamp]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001677 new_exp = min(max(self._exp, Etiny), exp_max)
1678 if new_exp != self._exp:
1679 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001680 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001681 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001682 return Decimal(self)
1683
1684 # exp_min is the smallest allowable exponent of the result,
1685 # equal to max(self.adjusted()-context.prec+1, Etiny)
1686 exp_min = len(self._int) + self._exp - context.prec
1687 if exp_min > Etop:
1688 # overflow: exp_min > Etop iff self.adjusted() > Emax
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001689 ans = context._raise_error(Overflow, 'above Emax', self._sign)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001690 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001691 context._raise_error(Rounded)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001692 return ans
1693
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001694 self_is_subnormal = exp_min < Etiny
1695 if self_is_subnormal:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001696 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001697
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001698 # round if self has too many digits
1699 if self._exp < exp_min:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001700 digits = len(self._int) + self._exp - exp_min
1701 if digits < 0:
1702 self = _dec_from_triple(self._sign, '1', exp_min-1)
1703 digits = 0
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001704 rounding_method = self._pick_rounding_function[context.rounding]
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04001705 changed = rounding_method(self, digits)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001706 coeff = self._int[:digits] or '0'
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001707 if changed > 0:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001708 coeff = str(int(coeff)+1)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001709 if len(coeff) > context.prec:
1710 coeff = coeff[:-1]
1711 exp_min += 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001712
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001713 # check whether the rounding pushed the exponent out of range
1714 if exp_min > Etop:
1715 ans = context._raise_error(Overflow, 'above Emax', self._sign)
1716 else:
1717 ans = _dec_from_triple(self._sign, coeff, exp_min)
1718
1719 # raise the appropriate signals, taking care to respect
1720 # the precedence described in the specification
1721 if changed and self_is_subnormal:
1722 context._raise_error(Underflow)
1723 if self_is_subnormal:
1724 context._raise_error(Subnormal)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001725 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001726 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001727 context._raise_error(Rounded)
1728 if not ans:
1729 # raise Clamped on underflow to 0
1730 context._raise_error(Clamped)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001731 return ans
1732
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001733 if self_is_subnormal:
1734 context._raise_error(Subnormal)
1735
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001736 # fold down if clamp == 1 and self has too few digits
1737 if context.clamp == 1 and self._exp > Etop:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001738 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001739 self_padded = self._int + '0'*(self._exp - Etop)
1740 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001741
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001742 # here self was representable to begin with; return unchanged
1743 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001744
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001745 # for each of the rounding functions below:
1746 # self is a finite, nonzero Decimal
1747 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001748 #
1749 # each function returns either -1, 0, or 1, as follows:
1750 # 1 indicates that self should be rounded up (away from zero)
1751 # 0 indicates that self should be truncated, and that all the
1752 # digits to be truncated are zeros (so the value is unchanged)
1753 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001754
1755 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001756 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001757 if _all_zeros(self._int, prec):
1758 return 0
1759 else:
1760 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001761
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001762 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001763 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001764 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001765
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001766 def _round_half_up(self, prec):
1767 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001768 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001769 return 1
1770 elif _all_zeros(self._int, prec):
1771 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001772 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001773 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001774
1775 def _round_half_down(self, prec):
1776 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001777 if _exact_half(self._int, prec):
1778 return -1
1779 else:
1780 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001781
1782 def _round_half_even(self, prec):
1783 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001784 if _exact_half(self._int, prec) and \
1785 (prec == 0 or self._int[prec-1] in '02468'):
1786 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001787 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001788 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001789
1790 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001791 """Rounds up (not away from 0 if negative.)"""
1792 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001793 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001794 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001795 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001796
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001797 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001798 """Rounds down (not towards 0 if negative)"""
1799 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001800 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001801 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001802 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001803
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001804 def _round_05up(self, prec):
1805 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001806 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001807 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001808 else:
1809 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001810
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04001811 _pick_rounding_function = dict(
1812 ROUND_DOWN = _round_down,
1813 ROUND_UP = _round_up,
1814 ROUND_HALF_UP = _round_half_up,
1815 ROUND_HALF_DOWN = _round_half_down,
1816 ROUND_HALF_EVEN = _round_half_even,
1817 ROUND_CEILING = _round_ceiling,
1818 ROUND_FLOOR = _round_floor,
1819 ROUND_05UP = _round_05up,
1820 )
1821
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001822 def __round__(self, n=None):
1823 """Round self to the nearest integer, or to a given precision.
1824
1825 If only one argument is supplied, round a finite Decimal
1826 instance self to the nearest integer. If self is infinite or
1827 a NaN then a Python exception is raised. If self is finite
1828 and lies exactly halfway between two integers then it is
1829 rounded to the integer with even last digit.
1830
1831 >>> round(Decimal('123.456'))
1832 123
1833 >>> round(Decimal('-456.789'))
1834 -457
1835 >>> round(Decimal('-3.0'))
1836 -3
1837 >>> round(Decimal('2.5'))
1838 2
1839 >>> round(Decimal('3.5'))
1840 4
1841 >>> round(Decimal('Inf'))
1842 Traceback (most recent call last):
1843 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001844 OverflowError: cannot round an infinity
1845 >>> round(Decimal('NaN'))
1846 Traceback (most recent call last):
1847 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001848 ValueError: cannot round a NaN
1849
1850 If a second argument n is supplied, self is rounded to n
1851 decimal places using the rounding mode for the current
1852 context.
1853
1854 For an integer n, round(self, -n) is exactly equivalent to
1855 self.quantize(Decimal('1En')).
1856
1857 >>> round(Decimal('123.456'), 0)
1858 Decimal('123')
1859 >>> round(Decimal('123.456'), 2)
1860 Decimal('123.46')
1861 >>> round(Decimal('123.456'), -2)
1862 Decimal('1E+2')
1863 >>> round(Decimal('-Infinity'), 37)
1864 Decimal('NaN')
1865 >>> round(Decimal('sNaN123'), 0)
1866 Decimal('NaN123')
1867
1868 """
1869 if n is not None:
1870 # two-argument form: use the equivalent quantize call
1871 if not isinstance(n, int):
1872 raise TypeError('Second argument to round should be integral')
1873 exp = _dec_from_triple(0, '1', -n)
1874 return self.quantize(exp)
1875
1876 # one-argument form
1877 if self._is_special:
1878 if self.is_nan():
1879 raise ValueError("cannot round a NaN")
1880 else:
1881 raise OverflowError("cannot round an infinity")
1882 return int(self._rescale(0, ROUND_HALF_EVEN))
1883
1884 def __floor__(self):
1885 """Return the floor of self, as an integer.
1886
1887 For a finite Decimal instance self, return the greatest
1888 integer n such that n <= self. If self is infinite or a NaN
1889 then a Python exception is raised.
1890
1891 """
1892 if self._is_special:
1893 if self.is_nan():
1894 raise ValueError("cannot round a NaN")
1895 else:
1896 raise OverflowError("cannot round an infinity")
1897 return int(self._rescale(0, ROUND_FLOOR))
1898
1899 def __ceil__(self):
1900 """Return the ceiling of self, as an integer.
1901
1902 For a finite Decimal instance self, return the least integer n
1903 such that n >= self. If self is infinite or a NaN then a
1904 Python exception is raised.
1905
1906 """
1907 if self._is_special:
1908 if self.is_nan():
1909 raise ValueError("cannot round a NaN")
1910 else:
1911 raise OverflowError("cannot round an infinity")
1912 return int(self._rescale(0, ROUND_CEILING))
1913
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001914 def fma(self, other, third, context=None):
1915 """Fused multiply-add.
1916
1917 Returns self*other+third with no rounding of the intermediate
1918 product self*other.
1919
1920 self and other are multiplied together, with no rounding of
1921 the result. The third operand is then added to the result,
1922 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001923 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001924
1925 other = _convert_other(other, raiseit=True)
Mark Dickinsonb455e582011-05-22 12:53:18 +01001926 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001927
1928 # compute product; raise InvalidOperation if either operand is
1929 # a signaling NaN or if the product is zero times infinity.
1930 if self._is_special or other._is_special:
1931 if context is None:
1932 context = getcontext()
1933 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001934 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001935 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001936 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001937 if self._exp == 'n':
1938 product = self
1939 elif other._exp == 'n':
1940 product = other
1941 elif self._exp == 'F':
1942 if not other:
1943 return context._raise_error(InvalidOperation,
1944 'INF * 0 in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001945 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001946 elif other._exp == 'F':
1947 if not self:
1948 return context._raise_error(InvalidOperation,
1949 '0 * INF in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001950 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001951 else:
1952 product = _dec_from_triple(self._sign ^ other._sign,
1953 str(int(self._int) * int(other._int)),
1954 self._exp + other._exp)
1955
Christian Heimes8b0facf2007-12-04 19:30:01 +00001956 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001957
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001958 def _power_modulo(self, other, modulo, context=None):
1959 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001960
Stefan Krah1919b7e2012-03-21 18:25:23 +01001961 other = _convert_other(other)
1962 if other is NotImplemented:
1963 return other
1964 modulo = _convert_other(modulo)
1965 if modulo is NotImplemented:
1966 return modulo
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001967
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001968 if context is None:
1969 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001970
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001971 # deal with NaNs: if there are any sNaNs then first one wins,
1972 # (i.e. behaviour for NaNs is identical to that of fma)
1973 self_is_nan = self._isnan()
1974 other_is_nan = other._isnan()
1975 modulo_is_nan = modulo._isnan()
1976 if self_is_nan or other_is_nan or modulo_is_nan:
1977 if self_is_nan == 2:
1978 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001979 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001980 if other_is_nan == 2:
1981 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001982 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001983 if modulo_is_nan == 2:
1984 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001985 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001986 if self_is_nan:
1987 return self._fix_nan(context)
1988 if other_is_nan:
1989 return other._fix_nan(context)
1990 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001991
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001992 # check inputs: we apply same restrictions as Python's pow()
1993 if not (self._isinteger() and
1994 other._isinteger() and
1995 modulo._isinteger()):
1996 return context._raise_error(InvalidOperation,
1997 'pow() 3rd argument not allowed '
1998 'unless all arguments are integers')
1999 if other < 0:
2000 return context._raise_error(InvalidOperation,
2001 'pow() 2nd argument cannot be '
2002 'negative when 3rd argument specified')
2003 if not modulo:
2004 return context._raise_error(InvalidOperation,
2005 'pow() 3rd argument cannot be 0')
2006
2007 # additional restriction for decimal: the modulus must be less
2008 # than 10**prec in absolute value
2009 if modulo.adjusted() >= context.prec:
2010 return context._raise_error(InvalidOperation,
2011 'insufficient precision: pow() 3rd '
2012 'argument must not have more than '
2013 'precision digits')
2014
2015 # define 0**0 == NaN, for consistency with two-argument pow
2016 # (even though it hurts!)
2017 if not other and not self:
2018 return context._raise_error(InvalidOperation,
2019 'at least one of pow() 1st argument '
2020 'and 2nd argument must be nonzero ;'
2021 '0**0 is not defined')
2022
2023 # compute sign of result
2024 if other._iseven():
2025 sign = 0
2026 else:
2027 sign = self._sign
2028
2029 # convert modulo to a Python integer, and self and other to
2030 # Decimal integers (i.e. force their exponents to be >= 0)
2031 modulo = abs(int(modulo))
2032 base = _WorkRep(self.to_integral_value())
2033 exponent = _WorkRep(other.to_integral_value())
2034
2035 # compute result using integer pow()
2036 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
2037 for i in range(exponent.exp):
2038 base = pow(base, 10, modulo)
2039 base = pow(base, exponent.int, modulo)
2040
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002041 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002042
2043 def _power_exact(self, other, p):
2044 """Attempt to compute self**other exactly.
2045
2046 Given Decimals self and other and an integer p, attempt to
2047 compute an exact result for the power self**other, with p
2048 digits of precision. Return None if self**other is not
2049 exactly representable in p digits.
2050
2051 Assumes that elimination of special cases has already been
2052 performed: self and other must both be nonspecial; self must
2053 be positive and not numerically equal to 1; other must be
2054 nonzero. For efficiency, other._exp should not be too large,
2055 so that 10**abs(other._exp) is a feasible calculation."""
2056
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002057 # In the comments below, we write x for the value of self and y for the
2058 # value of other. Write x = xc*10**xe and abs(y) = yc*10**ye, with xc
2059 # and yc positive integers not divisible by 10.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002060
2061 # The main purpose of this method is to identify the *failure*
2062 # of x**y to be exactly representable with as little effort as
2063 # possible. So we look for cheap and easy tests that
2064 # eliminate the possibility of x**y being exact. Only if all
2065 # these tests are passed do we go on to actually compute x**y.
2066
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002067 # Here's the main idea. Express y as a rational number m/n, with m and
2068 # n relatively prime and n>0. Then for x**y to be exactly
2069 # representable (at *any* precision), xc must be the nth power of a
2070 # positive integer and xe must be divisible by n. If y is negative
2071 # then additionally xc must be a power of either 2 or 5, hence a power
2072 # of 2**n or 5**n.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002073 #
2074 # There's a limit to how small |y| can be: if y=m/n as above
2075 # then:
2076 #
2077 # (1) if xc != 1 then for the result to be representable we
2078 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
2079 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
2080 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
2081 # representable.
2082 #
2083 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
2084 # |y| < 1/|xe| then the result is not representable.
2085 #
2086 # Note that since x is not equal to 1, at least one of (1) and
2087 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
2088 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
2089 #
2090 # There's also a limit to how large y can be, at least if it's
2091 # positive: the normalized result will have coefficient xc**y,
2092 # so if it's representable then xc**y < 10**p, and y <
2093 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
2094 # not exactly representable.
2095
2096 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
2097 # so |y| < 1/xe and the result is not representable.
2098 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
2099 # < 1/nbits(xc).
2100
2101 x = _WorkRep(self)
2102 xc, xe = x.int, x.exp
2103 while xc % 10 == 0:
2104 xc //= 10
2105 xe += 1
2106
2107 y = _WorkRep(other)
2108 yc, ye = y.int, y.exp
2109 while yc % 10 == 0:
2110 yc //= 10
2111 ye += 1
2112
2113 # case where xc == 1: result is 10**(xe*y), with xe*y
2114 # required to be an integer
2115 if xc == 1:
Mark Dickinsona1236312010-07-08 19:03:34 +00002116 xe *= yc
2117 # result is now 10**(xe * 10**ye); xe * 10**ye must be integral
2118 while xe % 10 == 0:
2119 xe //= 10
2120 ye += 1
2121 if ye < 0:
2122 return None
2123 exponent = xe * 10**ye
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002124 if y.sign == 1:
2125 exponent = -exponent
2126 # if other is a nonnegative integer, use ideal exponent
2127 if other._isinteger() and other._sign == 0:
2128 ideal_exponent = self._exp*int(other)
2129 zeros = min(exponent-ideal_exponent, p-1)
2130 else:
2131 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002132 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002133
2134 # case where y is negative: xc must be either a power
2135 # of 2 or a power of 5.
2136 if y.sign == 1:
2137 last_digit = xc % 10
2138 if last_digit in (2,4,6,8):
2139 # quick test for power of 2
2140 if xc & -xc != xc:
2141 return None
2142 # now xc is a power of 2; e is its exponent
2143 e = _nbits(xc)-1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002144
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002145 # We now have:
2146 #
2147 # x = 2**e * 10**xe, e > 0, and y < 0.
2148 #
2149 # The exact result is:
2150 #
2151 # x**y = 5**(-e*y) * 10**(e*y + xe*y)
2152 #
2153 # provided that both e*y and xe*y are integers. Note that if
2154 # 5**(-e*y) >= 10**p, then the result can't be expressed
2155 # exactly with p digits of precision.
2156 #
2157 # Using the above, we can guard against large values of ye.
2158 # 93/65 is an upper bound for log(10)/log(5), so if
2159 #
2160 # ye >= len(str(93*p//65))
2161 #
2162 # then
2163 #
2164 # -e*y >= -y >= 10**ye > 93*p/65 > p*log(10)/log(5),
2165 #
2166 # so 5**(-e*y) >= 10**p, and the coefficient of the result
2167 # can't be expressed in p digits.
2168
2169 # emax >= largest e such that 5**e < 10**p.
2170 emax = p*93//65
2171 if ye >= len(str(emax)):
2172 return None
2173
2174 # Find -e*y and -xe*y; both must be integers
2175 e = _decimal_lshift_exact(e * yc, ye)
2176 xe = _decimal_lshift_exact(xe * yc, ye)
2177 if e is None or xe is None:
2178 return None
2179
2180 if e > emax:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002181 return None
2182 xc = 5**e
2183
2184 elif last_digit == 5:
2185 # e >= log_5(xc) if xc is a power of 5; we have
2186 # equality all the way up to xc=5**2658
2187 e = _nbits(xc)*28//65
2188 xc, remainder = divmod(5**e, xc)
2189 if remainder:
2190 return None
2191 while xc % 5 == 0:
2192 xc //= 5
2193 e -= 1
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002194
2195 # Guard against large values of ye, using the same logic as in
2196 # the 'xc is a power of 2' branch. 10/3 is an upper bound for
2197 # log(10)/log(2).
2198 emax = p*10//3
2199 if ye >= len(str(emax)):
2200 return None
2201
2202 e = _decimal_lshift_exact(e * yc, ye)
2203 xe = _decimal_lshift_exact(xe * yc, ye)
2204 if e is None or xe is None:
2205 return None
2206
2207 if e > emax:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002208 return None
2209 xc = 2**e
2210 else:
2211 return None
2212
2213 if xc >= 10**p:
2214 return None
2215 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002216 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002217
2218 # now y is positive; find m and n such that y = m/n
2219 if ye >= 0:
2220 m, n = yc*10**ye, 1
2221 else:
2222 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2223 return None
2224 xc_bits = _nbits(xc)
2225 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2226 return None
2227 m, n = yc, 10**(-ye)
2228 while m % 2 == n % 2 == 0:
2229 m //= 2
2230 n //= 2
2231 while m % 5 == n % 5 == 0:
2232 m //= 5
2233 n //= 5
2234
2235 # compute nth root of xc*10**xe
2236 if n > 1:
2237 # if 1 < xc < 2**n then xc isn't an nth power
2238 if xc != 1 and xc_bits <= n:
2239 return None
2240
2241 xe, rem = divmod(xe, n)
2242 if rem != 0:
2243 return None
2244
2245 # compute nth root of xc using Newton's method
2246 a = 1 << -(-_nbits(xc)//n) # initial estimate
2247 while True:
2248 q, r = divmod(xc, a**(n-1))
2249 if a <= q:
2250 break
2251 else:
2252 a = (a*(n-1) + q)//n
2253 if not (a == q and r == 0):
2254 return None
2255 xc = a
2256
2257 # now xc*10**xe is the nth root of the original xc*10**xe
2258 # compute mth power of xc*10**xe
2259
2260 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2261 # 10**p and the result is not representable.
2262 if xc > 1 and m > p*100//_log10_lb(xc):
2263 return None
2264 xc = xc**m
2265 xe *= m
2266 if xc > 10**p:
2267 return None
2268
2269 # by this point the result *is* exactly representable
2270 # adjust the exponent to get as close as possible to the ideal
2271 # exponent, if necessary
2272 str_xc = str(xc)
2273 if other._isinteger() and other._sign == 0:
2274 ideal_exponent = self._exp*int(other)
2275 zeros = min(xe-ideal_exponent, p-len(str_xc))
2276 else:
2277 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002278 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002279
2280 def __pow__(self, other, modulo=None, context=None):
2281 """Return self ** other [ % modulo].
2282
2283 With two arguments, compute self**other.
2284
2285 With three arguments, compute (self**other) % modulo. For the
2286 three argument form, the following restrictions on the
2287 arguments hold:
2288
2289 - all three arguments must be integral
2290 - other must be nonnegative
2291 - either self or other (or both) must be nonzero
2292 - modulo must be nonzero and must have at most p digits,
2293 where p is the context precision.
2294
2295 If any of these restrictions is violated the InvalidOperation
2296 flag is raised.
2297
2298 The result of pow(self, other, modulo) is identical to the
2299 result that would be obtained by computing (self**other) %
2300 modulo with unbounded precision, but is computed more
2301 efficiently. It is always exact.
2302 """
2303
2304 if modulo is not None:
2305 return self._power_modulo(other, modulo, context)
2306
2307 other = _convert_other(other)
2308 if other is NotImplemented:
2309 return other
2310
2311 if context is None:
2312 context = getcontext()
2313
2314 # either argument is a NaN => result is NaN
2315 ans = self._check_nans(other, context)
2316 if ans:
2317 return ans
2318
2319 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2320 if not other:
2321 if not self:
2322 return context._raise_error(InvalidOperation, '0 ** 0')
2323 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002324 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002325
2326 # result has sign 1 iff self._sign is 1 and other is an odd integer
2327 result_sign = 0
2328 if self._sign == 1:
2329 if other._isinteger():
2330 if not other._iseven():
2331 result_sign = 1
2332 else:
2333 # -ve**noninteger = NaN
2334 # (-0)**noninteger = 0**noninteger
2335 if self:
2336 return context._raise_error(InvalidOperation,
2337 'x ** y with x negative and y not an integer')
2338 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002339 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002340
2341 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2342 if not self:
2343 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002344 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002345 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002346 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002347
2348 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002349 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002350 if other._sign == 0:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002351 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002352 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002353 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002354
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002355 # 1**other = 1, but the choice of exponent and the flags
2356 # depend on the exponent of self, and on whether other is a
2357 # positive integer, a negative integer, or neither
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002358 if self == _One:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002359 if other._isinteger():
2360 # exp = max(self._exp*max(int(other), 0),
2361 # 1-context.prec) but evaluating int(other) directly
2362 # is dangerous until we know other is small (other
2363 # could be 1e999999999)
2364 if other._sign == 1:
2365 multiplier = 0
2366 elif other > context.prec:
2367 multiplier = context.prec
2368 else:
2369 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002370
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002371 exp = self._exp * multiplier
2372 if exp < 1-context.prec:
2373 exp = 1-context.prec
2374 context._raise_error(Rounded)
2375 else:
2376 context._raise_error(Inexact)
2377 context._raise_error(Rounded)
2378 exp = 1-context.prec
2379
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002380 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002381
2382 # compute adjusted exponent of self
2383 self_adj = self.adjusted()
2384
2385 # self ** infinity is infinity if self > 1, 0 if self < 1
2386 # self ** -infinity is infinity if self < 1, 0 if self > 1
2387 if other._isinfinity():
2388 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002389 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002390 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002391 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002392
2393 # from here on, the result always goes through the call
2394 # to _fix at the end of this function.
2395 ans = None
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002396 exact = False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002397
2398 # crude test to catch cases of extreme overflow/underflow. If
2399 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2400 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2401 # self**other >= 10**(Emax+1), so overflow occurs. The test
2402 # for underflow is similar.
2403 bound = self._log10_exp_bound() + other.adjusted()
2404 if (self_adj >= 0) == (other._sign == 0):
2405 # self > 1 and other +ve, or self < 1 and other -ve
2406 # possibility of overflow
2407 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002408 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002409 else:
2410 # self > 1 and other -ve, or self < 1 and other +ve
2411 # possibility of underflow to 0
2412 Etiny = context.Etiny()
2413 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002414 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002415
2416 # try for an exact result with precision +1
2417 if ans is None:
2418 ans = self._power_exact(other, context.prec + 1)
Mark Dickinsone42f1bb2010-07-08 19:09:16 +00002419 if ans is not None:
2420 if result_sign == 1:
2421 ans = _dec_from_triple(1, ans._int, ans._exp)
2422 exact = True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002423
2424 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2425 if ans is None:
2426 p = context.prec
2427 x = _WorkRep(self)
2428 xc, xe = x.int, x.exp
2429 y = _WorkRep(other)
2430 yc, ye = y.int, y.exp
2431 if y.sign == 1:
2432 yc = -yc
2433
2434 # compute correctly rounded result: start with precision +3,
2435 # then increase precision until result is unambiguously roundable
2436 extra = 3
2437 while True:
2438 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2439 if coeff % (5*10**(len(str(coeff))-p-1)):
2440 break
2441 extra += 3
2442
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002443 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002444
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002445 # unlike exp, ln and log10, the power function respects the
2446 # rounding mode; no need to switch to ROUND_HALF_EVEN here
2447
2448 # There's a difficulty here when 'other' is not an integer and
2449 # the result is exact. In this case, the specification
2450 # requires that the Inexact flag be raised (in spite of
2451 # exactness), but since the result is exact _fix won't do this
2452 # for us. (Correspondingly, the Underflow signal should also
2453 # be raised for subnormal results.) We can't directly raise
2454 # these signals either before or after calling _fix, since
2455 # that would violate the precedence for signals. So we wrap
2456 # the ._fix call in a temporary context, and reraise
2457 # afterwards.
2458 if exact and not other._isinteger():
2459 # pad with zeros up to length context.prec+1 if necessary; this
2460 # ensures that the Rounded signal will be raised.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002461 if len(ans._int) <= context.prec:
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002462 expdiff = context.prec + 1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002463 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2464 ans._exp-expdiff)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002465
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002466 # create a copy of the current context, with cleared flags/traps
2467 newcontext = context.copy()
2468 newcontext.clear_flags()
2469 for exception in _signals:
2470 newcontext.traps[exception] = 0
2471
2472 # round in the new context
2473 ans = ans._fix(newcontext)
2474
2475 # raise Inexact, and if necessary, Underflow
2476 newcontext._raise_error(Inexact)
2477 if newcontext.flags[Subnormal]:
2478 newcontext._raise_error(Underflow)
2479
2480 # propagate signals to the original context; _fix could
2481 # have raised any of Overflow, Underflow, Subnormal,
2482 # Inexact, Rounded, Clamped. Overflow needs the correct
2483 # arguments. Note that the order of the exceptions is
2484 # important here.
2485 if newcontext.flags[Overflow]:
2486 context._raise_error(Overflow, 'above Emax', ans._sign)
2487 for exception in Underflow, Subnormal, Inexact, Rounded, Clamped:
2488 if newcontext.flags[exception]:
2489 context._raise_error(exception)
2490
2491 else:
2492 ans = ans._fix(context)
2493
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002494 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002495
2496 def __rpow__(self, other, context=None):
2497 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002498 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002499 if other is NotImplemented:
2500 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002501 return other.__pow__(self, context=context)
2502
2503 def normalize(self, context=None):
2504 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002505
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002506 if context is None:
2507 context = getcontext()
2508
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002509 if self._is_special:
2510 ans = self._check_nans(context=context)
2511 if ans:
2512 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002513
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002514 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002515 if dup._isinfinity():
2516 return dup
2517
2518 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002519 return _dec_from_triple(dup._sign, '0', 0)
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00002520 exp_max = [context.Emax, context.Etop()][context.clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002521 end = len(dup._int)
2522 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002523 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002524 exp += 1
2525 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002526 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002527
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002528 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002529 """Quantize self so its exponent is the same as that of exp.
2530
2531 Similar to self._rescale(exp._exp) but with error checking.
2532 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002533 exp = _convert_other(exp, raiseit=True)
2534
2535 if context is None:
2536 context = getcontext()
2537 if rounding is None:
2538 rounding = context.rounding
2539
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002540 if self._is_special or exp._is_special:
2541 ans = self._check_nans(exp, context)
2542 if ans:
2543 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002544
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002545 if exp._isinfinity() or self._isinfinity():
2546 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002547 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002548 return context._raise_error(InvalidOperation,
2549 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002550
2551 # if we're not watching exponents, do a simple rescale
2552 if not watchexp:
2553 ans = self._rescale(exp._exp, rounding)
2554 # raise Inexact and Rounded where appropriate
2555 if ans._exp > self._exp:
2556 context._raise_error(Rounded)
2557 if ans != self:
2558 context._raise_error(Inexact)
2559 return ans
2560
2561 # exp._exp should be between Etiny and Emax
2562 if not (context.Etiny() <= exp._exp <= context.Emax):
2563 return context._raise_error(InvalidOperation,
2564 'target exponent out of bounds in quantize')
2565
2566 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002567 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002568 return ans._fix(context)
2569
2570 self_adjusted = self.adjusted()
2571 if self_adjusted > context.Emax:
2572 return context._raise_error(InvalidOperation,
2573 'exponent of quantize result too large for current context')
2574 if self_adjusted - exp._exp + 1 > context.prec:
2575 return context._raise_error(InvalidOperation,
2576 'quantize result has too many digits for current context')
2577
2578 ans = self._rescale(exp._exp, rounding)
2579 if ans.adjusted() > context.Emax:
2580 return context._raise_error(InvalidOperation,
2581 'exponent of quantize result too large for current context')
2582 if len(ans._int) > context.prec:
2583 return context._raise_error(InvalidOperation,
2584 'quantize result has too many digits for current context')
2585
2586 # raise appropriate flags
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002587 if ans and ans.adjusted() < context.Emin:
2588 context._raise_error(Subnormal)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002589 if ans._exp > self._exp:
2590 if ans != self:
2591 context._raise_error(Inexact)
2592 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002593
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002594 # call to fix takes care of any necessary folddown, and
2595 # signals Clamped if necessary
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002596 ans = ans._fix(context)
2597 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002598
Stefan Krah040e3112012-12-15 22:33:33 +01002599 def same_quantum(self, other, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002600 """Return True if self and other have the same exponent; otherwise
2601 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002602
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002603 If either operand is a special value, the following rules are used:
2604 * return True if both operands are infinities
2605 * return True if both operands are NaNs
2606 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002607 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002608 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002609 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002610 return (self.is_nan() and other.is_nan() or
2611 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002612 return self._exp == other._exp
2613
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002614 def _rescale(self, exp, rounding):
2615 """Rescale self so that the exponent is exp, either by padding with zeros
2616 or by truncating digits, using the given rounding mode.
2617
2618 Specials are returned without change. This operation is
2619 quiet: it raises no flags, and uses no information from the
2620 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002621
2622 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002623 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002624 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002625 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002626 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002627 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002628 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002629
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002630 if self._exp >= exp:
2631 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002632 return _dec_from_triple(self._sign,
2633 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002634
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002635 # too many digits; round and lose data. If self.adjusted() <
2636 # exp-1, replace self by 10**(exp-1) before rounding
2637 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002638 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002639 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002640 digits = 0
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04002641 this_function = self._pick_rounding_function[rounding]
2642 changed = this_function(self, digits)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002643 coeff = self._int[:digits] or '0'
2644 if changed == 1:
2645 coeff = str(int(coeff)+1)
2646 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002647
Christian Heimesf16baeb2008-02-29 14:57:44 +00002648 def _round(self, places, rounding):
2649 """Round a nonzero, nonspecial Decimal to a fixed number of
2650 significant figures, using the given rounding mode.
2651
2652 Infinities, NaNs and zeros are returned unaltered.
2653
2654 This operation is quiet: it raises no flags, and uses no
2655 information from the context.
2656
2657 """
2658 if places <= 0:
2659 raise ValueError("argument should be at least 1 in _round")
2660 if self._is_special or not self:
2661 return Decimal(self)
2662 ans = self._rescale(self.adjusted()+1-places, rounding)
2663 # it can happen that the rescale alters the adjusted exponent;
2664 # for example when rounding 99.97 to 3 significant figures.
2665 # When this happens we end up with an extra 0 at the end of
2666 # the number; a second rescale fixes this.
2667 if ans.adjusted() != self.adjusted():
2668 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2669 return ans
2670
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002671 def to_integral_exact(self, rounding=None, context=None):
2672 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002673
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002674 If no rounding mode is specified, take the rounding mode from
2675 the context. This method raises the Rounded and Inexact flags
2676 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002677
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002678 See also: to_integral_value, which does exactly the same as
2679 this method except that it doesn't raise Inexact or Rounded.
2680 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002681 if self._is_special:
2682 ans = self._check_nans(context=context)
2683 if ans:
2684 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002685 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002686 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002687 return Decimal(self)
2688 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002689 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002690 if context is None:
2691 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002692 if rounding is None:
2693 rounding = context.rounding
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002694 ans = self._rescale(0, rounding)
2695 if ans != self:
2696 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002697 context._raise_error(Rounded)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002698 return ans
2699
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002700 def to_integral_value(self, rounding=None, context=None):
2701 """Rounds to the nearest integer, without raising inexact, rounded."""
2702 if context is None:
2703 context = getcontext()
2704 if rounding is None:
2705 rounding = context.rounding
2706 if self._is_special:
2707 ans = self._check_nans(context=context)
2708 if ans:
2709 return ans
2710 return Decimal(self)
2711 if self._exp >= 0:
2712 return Decimal(self)
2713 else:
2714 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002715
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002716 # the method name changed, but we provide also the old one, for compatibility
2717 to_integral = to_integral_value
2718
2719 def sqrt(self, context=None):
2720 """Return the square root of self."""
Christian Heimes0348fb62008-03-26 12:55:56 +00002721 if context is None:
2722 context = getcontext()
2723
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002724 if self._is_special:
2725 ans = self._check_nans(context=context)
2726 if ans:
2727 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002728
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002729 if self._isinfinity() and self._sign == 0:
2730 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002731
2732 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002733 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002734 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002735 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002736
2737 if self._sign == 1:
2738 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2739
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002740 # At this point self represents a positive number. Let p be
2741 # the desired precision and express self in the form c*100**e
2742 # with c a positive real number and e an integer, c and e
2743 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2744 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2745 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2746 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2747 # the closest integer to sqrt(c) with the even integer chosen
2748 # in the case of a tie.
2749 #
2750 # To ensure correct rounding in all cases, we use the
2751 # following trick: we compute the square root to an extra
2752 # place (precision p+1 instead of precision p), rounding down.
2753 # Then, if the result is inexact and its last digit is 0 or 5,
2754 # we increase the last digit to 1 or 6 respectively; if it's
2755 # exact we leave the last digit alone. Now the final round to
2756 # p places (or fewer in the case of underflow) will round
2757 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002758
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002759 # use an extra digit of precision
2760 prec = context.prec+1
2761
2762 # write argument in the form c*100**e where e = self._exp//2
2763 # is the 'ideal' exponent, to be used if the square root is
2764 # exactly representable. l is the number of 'digits' of c in
2765 # base 100, so that 100**(l-1) <= c < 100**l.
2766 op = _WorkRep(self)
2767 e = op.exp >> 1
2768 if op.exp & 1:
2769 c = op.int * 10
2770 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002771 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002772 c = op.int
2773 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002774
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002775 # rescale so that c has exactly prec base 100 'digits'
2776 shift = prec-l
2777 if shift >= 0:
2778 c *= 100**shift
2779 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002780 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002781 c, remainder = divmod(c, 100**-shift)
2782 exact = not remainder
2783 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002784
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002785 # find n = floor(sqrt(c)) using Newton's method
2786 n = 10**prec
2787 while True:
2788 q = c//n
2789 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002790 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002791 else:
2792 n = n + q >> 1
2793 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002794
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002795 if exact:
2796 # result is exact; rescale to use ideal exponent e
2797 if shift >= 0:
2798 # assert n % 10**shift == 0
2799 n //= 10**shift
2800 else:
2801 n *= 10**-shift
2802 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002803 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002804 # result is not exact; fix last digit as described above
2805 if n % 5 == 0:
2806 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002807
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002808 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002809
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002810 # round, and fit to current context
2811 context = context._shallow_copy()
2812 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002813 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002814 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002815
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002816 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002817
2818 def max(self, other, context=None):
2819 """Returns the larger value.
2820
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002821 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002822 NaN (and signals if one is sNaN). Also rounds.
2823 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002824 other = _convert_other(other, raiseit=True)
2825
2826 if context is None:
2827 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002828
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002829 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002830 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002831 # number is always returned
2832 sn = self._isnan()
2833 on = other._isnan()
2834 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002835 if on == 1 and sn == 0:
2836 return self._fix(context)
2837 if sn == 1 and on == 0:
2838 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002839 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002840
Christian Heimes77c02eb2008-02-09 02:18:51 +00002841 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002842 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002843 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002844 # then an ordering is applied:
2845 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002846 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002847 # positive sign and min returns the operand with the negative sign
2848 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002849 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002850 # the result. This is exactly the ordering used in compare_total.
2851 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002852
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002853 if c == -1:
2854 ans = other
2855 else:
2856 ans = self
2857
Christian Heimes2c181612007-12-17 20:04:13 +00002858 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002859
2860 def min(self, other, context=None):
2861 """Returns the smaller value.
2862
Guido van Rossumd8faa362007-04-27 19:54:29 +00002863 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002864 NaN (and signals if one is sNaN). Also rounds.
2865 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002866 other = _convert_other(other, raiseit=True)
2867
2868 if context is None:
2869 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002870
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002871 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002872 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002873 # number is always returned
2874 sn = self._isnan()
2875 on = other._isnan()
2876 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002877 if on == 1 and sn == 0:
2878 return self._fix(context)
2879 if sn == 1 and on == 0:
2880 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002881 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002882
Christian Heimes77c02eb2008-02-09 02:18:51 +00002883 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002884 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002885 c = self.compare_total(other)
2886
2887 if c == -1:
2888 ans = self
2889 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002890 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002891
Christian Heimes2c181612007-12-17 20:04:13 +00002892 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002893
2894 def _isinteger(self):
2895 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002896 if self._is_special:
2897 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002898 if self._exp >= 0:
2899 return True
2900 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002901 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002902
2903 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002904 """Returns True if self is even. Assumes self is an integer."""
2905 if not self or self._exp > 0:
2906 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002907 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002908
2909 def adjusted(self):
2910 """Return the adjusted exponent of self"""
2911 try:
2912 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002913 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002914 except TypeError:
2915 return 0
2916
Stefan Krah040e3112012-12-15 22:33:33 +01002917 def canonical(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002918 """Returns the same Decimal object.
2919
2920 As we do not have different encodings for the same number, the
2921 received object already is in its canonical form.
2922 """
2923 return self
2924
2925 def compare_signal(self, other, context=None):
2926 """Compares self to the other operand numerically.
2927
2928 It's pretty much like compare(), but all NaNs signal, with signaling
2929 NaNs taking precedence over quiet NaNs.
2930 """
Christian Heimes77c02eb2008-02-09 02:18:51 +00002931 other = _convert_other(other, raiseit = True)
2932 ans = self._compare_check_nans(other, context)
2933 if ans:
2934 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002935 return self.compare(other, context=context)
2936
Stefan Krah040e3112012-12-15 22:33:33 +01002937 def compare_total(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002938 """Compares self to other using the abstract representations.
2939
2940 This is not like the standard compare, which use their numerical
2941 value. Note that a total ordering is defined for all possible abstract
2942 representations.
2943 """
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00002944 other = _convert_other(other, raiseit=True)
2945
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002946 # if one is negative and the other is positive, it's easy
2947 if self._sign and not other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002948 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002949 if not self._sign and other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002950 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002951 sign = self._sign
2952
2953 # let's handle both NaN types
2954 self_nan = self._isnan()
2955 other_nan = other._isnan()
2956 if self_nan or other_nan:
2957 if self_nan == other_nan:
Mark Dickinsond314e1b2009-08-28 13:39:53 +00002958 # compare payloads as though they're integers
2959 self_key = len(self._int), self._int
2960 other_key = len(other._int), other._int
2961 if self_key < other_key:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002962 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002963 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002964 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002965 return _NegativeOne
Mark Dickinsond314e1b2009-08-28 13:39:53 +00002966 if self_key > other_key:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002967 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002968 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002969 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002970 return _One
2971 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002972
2973 if sign:
2974 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002975 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002976 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002977 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002978 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002979 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002980 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002981 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002982 else:
2983 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002984 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002985 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002986 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002987 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002988 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002989 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002990 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002991
2992 if self < other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002993 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002994 if self > other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002995 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002996
2997 if self._exp < other._exp:
2998 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002999 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003000 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003001 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003002 if self._exp > other._exp:
3003 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003004 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003005 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003006 return _One
3007 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003008
3009
Stefan Krah040e3112012-12-15 22:33:33 +01003010 def compare_total_mag(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003011 """Compares self to other using abstract repr., ignoring sign.
3012
3013 Like compare_total, but with operand's sign ignored and assumed to be 0.
3014 """
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003015 other = _convert_other(other, raiseit=True)
3016
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003017 s = self.copy_abs()
3018 o = other.copy_abs()
3019 return s.compare_total(o)
3020
3021 def copy_abs(self):
3022 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003023 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003024
3025 def copy_negate(self):
3026 """Returns a copy with the sign inverted."""
3027 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003028 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003029 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003030 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003031
Stefan Krah040e3112012-12-15 22:33:33 +01003032 def copy_sign(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003033 """Returns self with the sign of other."""
Mark Dickinson84230a12010-02-18 14:49:50 +00003034 other = _convert_other(other, raiseit=True)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003035 return _dec_from_triple(other._sign, self._int,
3036 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003037
3038 def exp(self, context=None):
3039 """Returns e ** self."""
3040
3041 if context is None:
3042 context = getcontext()
3043
3044 # exp(NaN) = NaN
3045 ans = self._check_nans(context=context)
3046 if ans:
3047 return ans
3048
3049 # exp(-Infinity) = 0
3050 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003051 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003052
3053 # exp(0) = 1
3054 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003055 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003056
3057 # exp(Infinity) = Infinity
3058 if self._isinfinity() == 1:
3059 return Decimal(self)
3060
3061 # the result is now guaranteed to be inexact (the true
3062 # mathematical result is transcendental). There's no need to
3063 # raise Rounded and Inexact here---they'll always be raised as
3064 # a result of the call to _fix.
3065 p = context.prec
3066 adj = self.adjusted()
3067
3068 # we only need to do any computation for quite a small range
3069 # of adjusted exponents---for example, -29 <= adj <= 10 for
3070 # the default context. For smaller exponent the result is
3071 # indistinguishable from 1 at the given precision, while for
3072 # larger exponent the result either overflows or underflows.
3073 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
3074 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003075 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003076 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
3077 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003078 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003079 elif self._sign == 0 and adj < -p:
3080 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003081 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003082 elif self._sign == 1 and adj < -p-1:
3083 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003084 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003085 # general case
3086 else:
3087 op = _WorkRep(self)
3088 c, e = op.int, op.exp
3089 if op.sign == 1:
3090 c = -c
3091
3092 # compute correctly rounded result: increase precision by
3093 # 3 digits at a time until we get an unambiguously
3094 # roundable result
3095 extra = 3
3096 while True:
3097 coeff, exp = _dexp(c, e, p+extra)
3098 if coeff % (5*10**(len(str(coeff))-p-1)):
3099 break
3100 extra += 3
3101
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003102 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003103
3104 # at this stage, ans should round correctly with *any*
3105 # rounding mode, not just with ROUND_HALF_EVEN
3106 context = context._shallow_copy()
3107 rounding = context._set_rounding(ROUND_HALF_EVEN)
3108 ans = ans._fix(context)
3109 context.rounding = rounding
3110
3111 return ans
3112
3113 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003114 """Return True if self is canonical; otherwise return False.
3115
3116 Currently, the encoding of a Decimal instance is always
3117 canonical, so this method returns True for any Decimal.
3118 """
3119 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003120
3121 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003122 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003123
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003124 A Decimal instance is considered finite if it is neither
3125 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003126 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003127 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003128
3129 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003130 """Return True if self is infinite; otherwise return False."""
3131 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003132
3133 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003134 """Return True if self is a qNaN or sNaN; otherwise return False."""
3135 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003136
3137 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003138 """Return True if self is a normal number; otherwise return False."""
3139 if self._is_special or not self:
3140 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003141 if context is None:
3142 context = getcontext()
Mark Dickinson06bb6742009-10-20 13:38:04 +00003143 return context.Emin <= self.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003144
3145 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003146 """Return True if self is a quiet NaN; otherwise return False."""
3147 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003148
3149 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003150 """Return True if self is negative; otherwise return False."""
3151 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003152
3153 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003154 """Return True if self is a signaling NaN; otherwise return False."""
3155 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003156
3157 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003158 """Return True if self is subnormal; otherwise return False."""
3159 if self._is_special or not self:
3160 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003161 if context is None:
3162 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003163 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003164
3165 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003166 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003167 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003168
3169 def _ln_exp_bound(self):
3170 """Compute a lower bound for the adjusted exponent of self.ln().
3171 In other words, compute r such that self.ln() >= 10**r. Assumes
3172 that self is finite and positive and that self != 1.
3173 """
3174
3175 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
3176 adj = self._exp + len(self._int) - 1
3177 if adj >= 1:
3178 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
3179 return len(str(adj*23//10)) - 1
3180 if adj <= -2:
3181 # argument <= 0.1
3182 return len(str((-1-adj)*23//10)) - 1
3183 op = _WorkRep(self)
3184 c, e = op.int, op.exp
3185 if adj == 0:
3186 # 1 < self < 10
3187 num = str(c-10**-e)
3188 den = str(c)
3189 return len(num) - len(den) - (num < den)
3190 # adj == -1, 0.1 <= self < 1
3191 return e + len(str(10**-e - c)) - 1
3192
3193
3194 def ln(self, context=None):
3195 """Returns the natural (base e) logarithm of self."""
3196
3197 if context is None:
3198 context = getcontext()
3199
3200 # ln(NaN) = NaN
3201 ans = self._check_nans(context=context)
3202 if ans:
3203 return ans
3204
3205 # ln(0.0) == -Infinity
3206 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003207 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003208
3209 # ln(Infinity) = Infinity
3210 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003211 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003212
3213 # ln(1.0) == 0.0
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003214 if self == _One:
3215 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003216
3217 # ln(negative) raises InvalidOperation
3218 if self._sign == 1:
3219 return context._raise_error(InvalidOperation,
3220 'ln of a negative value')
3221
3222 # result is irrational, so necessarily inexact
3223 op = _WorkRep(self)
3224 c, e = op.int, op.exp
3225 p = context.prec
3226
3227 # correctly rounded result: repeatedly increase precision by 3
3228 # until we get an unambiguously roundable result
3229 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3230 while True:
3231 coeff = _dlog(c, e, places)
3232 # assert len(str(abs(coeff)))-p >= 1
3233 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3234 break
3235 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003236 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003237
3238 context = context._shallow_copy()
3239 rounding = context._set_rounding(ROUND_HALF_EVEN)
3240 ans = ans._fix(context)
3241 context.rounding = rounding
3242 return ans
3243
3244 def _log10_exp_bound(self):
3245 """Compute a lower bound for the adjusted exponent of self.log10().
3246 In other words, find r such that self.log10() >= 10**r.
3247 Assumes that self is finite and positive and that self != 1.
3248 """
3249
3250 # For x >= 10 or x < 0.1 we only need a bound on the integer
3251 # part of log10(self), and this comes directly from the
3252 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3253 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3254 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3255
3256 adj = self._exp + len(self._int) - 1
3257 if adj >= 1:
3258 # self >= 10
3259 return len(str(adj))-1
3260 if adj <= -2:
3261 # self < 0.1
3262 return len(str(-1-adj))-1
3263 op = _WorkRep(self)
3264 c, e = op.int, op.exp
3265 if adj == 0:
3266 # 1 < self < 10
3267 num = str(c-10**-e)
3268 den = str(231*c)
3269 return len(num) - len(den) - (num < den) + 2
3270 # adj == -1, 0.1 <= self < 1
3271 num = str(10**-e-c)
3272 return len(num) + e - (num < "231") - 1
3273
3274 def log10(self, context=None):
3275 """Returns the base 10 logarithm of self."""
3276
3277 if context is None:
3278 context = getcontext()
3279
3280 # log10(NaN) = NaN
3281 ans = self._check_nans(context=context)
3282 if ans:
3283 return ans
3284
3285 # log10(0.0) == -Infinity
3286 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003287 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003288
3289 # log10(Infinity) = Infinity
3290 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003291 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003292
3293 # log10(negative or -Infinity) raises InvalidOperation
3294 if self._sign == 1:
3295 return context._raise_error(InvalidOperation,
3296 'log10 of a negative value')
3297
3298 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003299 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003300 # answer may need rounding
3301 ans = Decimal(self._exp + len(self._int) - 1)
3302 else:
3303 # result is irrational, so necessarily inexact
3304 op = _WorkRep(self)
3305 c, e = op.int, op.exp
3306 p = context.prec
3307
3308 # correctly rounded result: repeatedly increase precision
3309 # until result is unambiguously roundable
3310 places = p-self._log10_exp_bound()+2
3311 while True:
3312 coeff = _dlog10(c, e, places)
3313 # assert len(str(abs(coeff)))-p >= 1
3314 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3315 break
3316 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003317 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003318
3319 context = context._shallow_copy()
3320 rounding = context._set_rounding(ROUND_HALF_EVEN)
3321 ans = ans._fix(context)
3322 context.rounding = rounding
3323 return ans
3324
3325 def logb(self, context=None):
3326 """ Returns the exponent of the magnitude of self's MSD.
3327
3328 The result is the integer which is the exponent of the magnitude
3329 of the most significant digit of self (as though it were truncated
3330 to a single digit while maintaining the value of that digit and
3331 without limiting the resulting exponent).
3332 """
3333 # logb(NaN) = NaN
3334 ans = self._check_nans(context=context)
3335 if ans:
3336 return ans
3337
3338 if context is None:
3339 context = getcontext()
3340
3341 # logb(+/-Inf) = +Inf
3342 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003343 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003344
3345 # logb(0) = -Inf, DivisionByZero
3346 if not self:
3347 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3348
3349 # otherwise, simply return the adjusted exponent of self, as a
3350 # Decimal. Note that no attempt is made to fit the result
3351 # into the current context.
Mark Dickinson56df8872009-10-07 19:23:50 +00003352 ans = Decimal(self.adjusted())
3353 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003354
3355 def _islogical(self):
3356 """Return True if self is a logical operand.
3357
Christian Heimes679db4a2008-01-18 09:56:22 +00003358 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003359 an exponent of 0, and a coefficient whose digits must all be
3360 either 0 or 1.
3361 """
3362 if self._sign != 0 or self._exp != 0:
3363 return False
3364 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003365 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003366 return False
3367 return True
3368
3369 def _fill_logical(self, context, opa, opb):
3370 dif = context.prec - len(opa)
3371 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003372 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003373 elif dif < 0:
3374 opa = opa[-context.prec:]
3375 dif = context.prec - len(opb)
3376 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003377 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003378 elif dif < 0:
3379 opb = opb[-context.prec:]
3380 return opa, opb
3381
3382 def logical_and(self, other, context=None):
3383 """Applies an 'and' operation between self and other's digits."""
3384 if context is None:
3385 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003386
3387 other = _convert_other(other, raiseit=True)
3388
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003389 if not self._islogical() or not other._islogical():
3390 return context._raise_error(InvalidOperation)
3391
3392 # fill to context.prec
3393 (opa, opb) = self._fill_logical(context, self._int, other._int)
3394
3395 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003396 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3397 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003398
3399 def logical_invert(self, context=None):
3400 """Invert all its digits."""
3401 if context is None:
3402 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003403 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3404 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003405
3406 def logical_or(self, other, context=None):
3407 """Applies an 'or' operation between self and other's digits."""
3408 if context is None:
3409 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003410
3411 other = _convert_other(other, raiseit=True)
3412
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003413 if not self._islogical() or not other._islogical():
3414 return context._raise_error(InvalidOperation)
3415
3416 # fill to context.prec
3417 (opa, opb) = self._fill_logical(context, self._int, other._int)
3418
3419 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003420 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003421 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003422
3423 def logical_xor(self, other, context=None):
3424 """Applies an 'xor' operation between self and other's digits."""
3425 if context is None:
3426 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003427
3428 other = _convert_other(other, raiseit=True)
3429
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003430 if not self._islogical() or not other._islogical():
3431 return context._raise_error(InvalidOperation)
3432
3433 # fill to context.prec
3434 (opa, opb) = self._fill_logical(context, self._int, other._int)
3435
3436 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003437 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003438 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003439
3440 def max_mag(self, other, context=None):
3441 """Compares the values numerically with their sign ignored."""
3442 other = _convert_other(other, raiseit=True)
3443
3444 if context is None:
3445 context = getcontext()
3446
3447 if self._is_special or other._is_special:
3448 # If one operand is a quiet NaN and the other is number, then the
3449 # number is always returned
3450 sn = self._isnan()
3451 on = other._isnan()
3452 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003453 if on == 1 and sn == 0:
3454 return self._fix(context)
3455 if sn == 1 and on == 0:
3456 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003457 return self._check_nans(other, context)
3458
Christian Heimes77c02eb2008-02-09 02:18:51 +00003459 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003460 if c == 0:
3461 c = self.compare_total(other)
3462
3463 if c == -1:
3464 ans = other
3465 else:
3466 ans = self
3467
Christian Heimes2c181612007-12-17 20:04:13 +00003468 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003469
3470 def min_mag(self, other, context=None):
3471 """Compares the values numerically with their sign ignored."""
3472 other = _convert_other(other, raiseit=True)
3473
3474 if context is None:
3475 context = getcontext()
3476
3477 if self._is_special or other._is_special:
3478 # If one operand is a quiet NaN and the other is number, then the
3479 # number is always returned
3480 sn = self._isnan()
3481 on = other._isnan()
3482 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003483 if on == 1 and sn == 0:
3484 return self._fix(context)
3485 if sn == 1 and on == 0:
3486 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003487 return self._check_nans(other, context)
3488
Christian Heimes77c02eb2008-02-09 02:18:51 +00003489 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003490 if c == 0:
3491 c = self.compare_total(other)
3492
3493 if c == -1:
3494 ans = self
3495 else:
3496 ans = other
3497
Christian Heimes2c181612007-12-17 20:04:13 +00003498 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003499
3500 def next_minus(self, context=None):
3501 """Returns the largest representable number smaller than itself."""
3502 if context is None:
3503 context = getcontext()
3504
3505 ans = self._check_nans(context=context)
3506 if ans:
3507 return ans
3508
3509 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003510 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003511 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003512 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003513
3514 context = context.copy()
3515 context._set_rounding(ROUND_FLOOR)
3516 context._ignore_all_flags()
3517 new_self = self._fix(context)
3518 if new_self != self:
3519 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003520 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3521 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003522
3523 def next_plus(self, context=None):
3524 """Returns the smallest representable number larger than itself."""
3525 if context is None:
3526 context = getcontext()
3527
3528 ans = self._check_nans(context=context)
3529 if ans:
3530 return ans
3531
3532 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003533 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003534 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003535 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003536
3537 context = context.copy()
3538 context._set_rounding(ROUND_CEILING)
3539 context._ignore_all_flags()
3540 new_self = self._fix(context)
3541 if new_self != self:
3542 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003543 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3544 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003545
3546 def next_toward(self, other, context=None):
3547 """Returns the number closest to self, in the direction towards other.
3548
3549 The result is the closest representable number to self
3550 (excluding self) that is in the direction towards other,
3551 unless both have the same value. If the two operands are
3552 numerically equal, then the result is a copy of self with the
3553 sign set to be the same as the sign of other.
3554 """
3555 other = _convert_other(other, raiseit=True)
3556
3557 if context is None:
3558 context = getcontext()
3559
3560 ans = self._check_nans(other, context)
3561 if ans:
3562 return ans
3563
Christian Heimes77c02eb2008-02-09 02:18:51 +00003564 comparison = self._cmp(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003565 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003566 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003567
3568 if comparison == -1:
3569 ans = self.next_plus(context)
3570 else: # comparison == 1
3571 ans = self.next_minus(context)
3572
3573 # decide which flags to raise using value of ans
3574 if ans._isinfinity():
3575 context._raise_error(Overflow,
3576 'Infinite result from next_toward',
3577 ans._sign)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003578 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00003579 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003580 elif ans.adjusted() < context.Emin:
3581 context._raise_error(Underflow)
3582 context._raise_error(Subnormal)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003583 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00003584 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003585 # if precision == 1 then we don't raise Clamped for a
3586 # result 0E-Etiny.
3587 if not ans:
3588 context._raise_error(Clamped)
3589
3590 return ans
3591
3592 def number_class(self, context=None):
3593 """Returns an indication of the class of self.
3594
3595 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003596 sNaN
3597 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003598 -Infinity
3599 -Normal
3600 -Subnormal
3601 -Zero
3602 +Zero
3603 +Subnormal
3604 +Normal
3605 +Infinity
3606 """
3607 if self.is_snan():
3608 return "sNaN"
3609 if self.is_qnan():
3610 return "NaN"
3611 inf = self._isinfinity()
3612 if inf == 1:
3613 return "+Infinity"
3614 if inf == -1:
3615 return "-Infinity"
3616 if self.is_zero():
3617 if self._sign:
3618 return "-Zero"
3619 else:
3620 return "+Zero"
3621 if context is None:
3622 context = getcontext()
3623 if self.is_subnormal(context=context):
3624 if self._sign:
3625 return "-Subnormal"
3626 else:
3627 return "+Subnormal"
3628 # just a normal, regular, boring number, :)
3629 if self._sign:
3630 return "-Normal"
3631 else:
3632 return "+Normal"
3633
3634 def radix(self):
3635 """Just returns 10, as this is Decimal, :)"""
3636 return Decimal(10)
3637
3638 def rotate(self, other, context=None):
3639 """Returns a rotated copy of self, value-of-other times."""
3640 if context is None:
3641 context = getcontext()
3642
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003643 other = _convert_other(other, raiseit=True)
3644
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003645 ans = self._check_nans(other, context)
3646 if ans:
3647 return ans
3648
3649 if other._exp != 0:
3650 return context._raise_error(InvalidOperation)
3651 if not (-context.prec <= int(other) <= context.prec):
3652 return context._raise_error(InvalidOperation)
3653
3654 if self._isinfinity():
3655 return Decimal(self)
3656
3657 # get values, pad if necessary
3658 torot = int(other)
3659 rotdig = self._int
3660 topad = context.prec - len(rotdig)
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003661 if topad > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003662 rotdig = '0'*topad + rotdig
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003663 elif topad < 0:
3664 rotdig = rotdig[-topad:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003665
3666 # let's rotate!
3667 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003668 return _dec_from_triple(self._sign,
3669 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003670
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003671 def scaleb(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003672 """Returns self operand after adding the second value to its exp."""
3673 if context is None:
3674 context = getcontext()
3675
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003676 other = _convert_other(other, raiseit=True)
3677
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003678 ans = self._check_nans(other, context)
3679 if ans:
3680 return ans
3681
3682 if other._exp != 0:
3683 return context._raise_error(InvalidOperation)
3684 liminf = -2 * (context.Emax + context.prec)
3685 limsup = 2 * (context.Emax + context.prec)
3686 if not (liminf <= int(other) <= limsup):
3687 return context._raise_error(InvalidOperation)
3688
3689 if self._isinfinity():
3690 return Decimal(self)
3691
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003692 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003693 d = d._fix(context)
3694 return d
3695
3696 def shift(self, other, context=None):
3697 """Returns a shifted copy of self, value-of-other times."""
3698 if context is None:
3699 context = getcontext()
3700
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003701 other = _convert_other(other, raiseit=True)
3702
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003703 ans = self._check_nans(other, context)
3704 if ans:
3705 return ans
3706
3707 if other._exp != 0:
3708 return context._raise_error(InvalidOperation)
3709 if not (-context.prec <= int(other) <= context.prec):
3710 return context._raise_error(InvalidOperation)
3711
3712 if self._isinfinity():
3713 return Decimal(self)
3714
3715 # get values, pad if necessary
3716 torot = int(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003717 rotdig = self._int
3718 topad = context.prec - len(rotdig)
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003719 if topad > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003720 rotdig = '0'*topad + rotdig
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003721 elif topad < 0:
3722 rotdig = rotdig[-topad:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003723
3724 # let's shift!
3725 if torot < 0:
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003726 shifted = rotdig[:torot]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003727 else:
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003728 shifted = rotdig + '0'*torot
3729 shifted = shifted[-context.prec:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003730
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003731 return _dec_from_triple(self._sign,
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003732 shifted.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003733
Guido van Rossumd8faa362007-04-27 19:54:29 +00003734 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003735 def __reduce__(self):
3736 return (self.__class__, (str(self),))
3737
3738 def __copy__(self):
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00003739 if type(self) is Decimal:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003740 return self # I'm immutable; therefore I am my own clone
3741 return self.__class__(str(self))
3742
3743 def __deepcopy__(self, memo):
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00003744 if type(self) is Decimal:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003745 return self # My components are also immutable
3746 return self.__class__(str(self))
3747
Mark Dickinson79f52032009-03-17 23:12:51 +00003748 # PEP 3101 support. the _localeconv keyword argument should be
3749 # considered private: it's provided for ease of testing only.
3750 def __format__(self, specifier, context=None, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00003751 """Format a Decimal instance according to the given specifier.
3752
3753 The specifier should be a standard format specifier, with the
3754 form described in PEP 3101. Formatting types 'e', 'E', 'f',
Mark Dickinson79f52032009-03-17 23:12:51 +00003755 'F', 'g', 'G', 'n' and '%' are supported. If the formatting
3756 type is omitted it defaults to 'g' or 'G', depending on the
3757 value of context.capitals.
Christian Heimesf16baeb2008-02-29 14:57:44 +00003758 """
3759
3760 # Note: PEP 3101 says that if the type is not present then
3761 # there should be at least one digit after the decimal point.
3762 # We take the liberty of ignoring this requirement for
3763 # Decimal---it's presumably there to make sure that
3764 # format(float, '') behaves similarly to str(float).
3765 if context is None:
3766 context = getcontext()
3767
Mark Dickinson79f52032009-03-17 23:12:51 +00003768 spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003769
Mark Dickinson79f52032009-03-17 23:12:51 +00003770 # special values don't care about the type or precision
Christian Heimesf16baeb2008-02-29 14:57:44 +00003771 if self._is_special:
Mark Dickinson79f52032009-03-17 23:12:51 +00003772 sign = _format_sign(self._sign, spec)
3773 body = str(self.copy_abs())
3774 return _format_align(sign, body, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003775
3776 # a type of None defaults to 'g' or 'G', depending on context
Christian Heimesf16baeb2008-02-29 14:57:44 +00003777 if spec['type'] is None:
3778 spec['type'] = ['g', 'G'][context.capitals]
Mark Dickinson79f52032009-03-17 23:12:51 +00003779
3780 # if type is '%', adjust exponent of self accordingly
3781 if spec['type'] == '%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003782 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3783
3784 # round if necessary, taking rounding mode from the context
3785 rounding = context.rounding
3786 precision = spec['precision']
3787 if precision is not None:
3788 if spec['type'] in 'eE':
3789 self = self._round(precision+1, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003790 elif spec['type'] in 'fF%':
3791 self = self._rescale(-precision, rounding)
Mark Dickinson79f52032009-03-17 23:12:51 +00003792 elif spec['type'] in 'gG' and len(self._int) > precision:
3793 self = self._round(precision, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003794 # special case: zeros with a positive exponent can't be
3795 # represented in fixed point; rescale them to 0e0.
Mark Dickinson79f52032009-03-17 23:12:51 +00003796 if not self and self._exp > 0 and spec['type'] in 'fF%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003797 self = self._rescale(0, rounding)
3798
3799 # figure out placement of the decimal point
3800 leftdigits = self._exp + len(self._int)
Mark Dickinson79f52032009-03-17 23:12:51 +00003801 if spec['type'] in 'eE':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003802 if not self and precision is not None:
3803 dotplace = 1 - precision
3804 else:
3805 dotplace = 1
Mark Dickinson79f52032009-03-17 23:12:51 +00003806 elif spec['type'] in 'fF%':
3807 dotplace = leftdigits
Christian Heimesf16baeb2008-02-29 14:57:44 +00003808 elif spec['type'] in 'gG':
3809 if self._exp <= 0 and leftdigits > -6:
3810 dotplace = leftdigits
3811 else:
3812 dotplace = 1
3813
Mark Dickinson79f52032009-03-17 23:12:51 +00003814 # find digits before and after decimal point, and get exponent
3815 if dotplace < 0:
3816 intpart = '0'
3817 fracpart = '0'*(-dotplace) + self._int
3818 elif dotplace > len(self._int):
3819 intpart = self._int + '0'*(dotplace-len(self._int))
3820 fracpart = ''
Christian Heimesf16baeb2008-02-29 14:57:44 +00003821 else:
Mark Dickinson79f52032009-03-17 23:12:51 +00003822 intpart = self._int[:dotplace] or '0'
3823 fracpart = self._int[dotplace:]
3824 exp = leftdigits-dotplace
Christian Heimesf16baeb2008-02-29 14:57:44 +00003825
Mark Dickinson79f52032009-03-17 23:12:51 +00003826 # done with the decimal-specific stuff; hand over the rest
3827 # of the formatting to the _format_number function
3828 return _format_number(self._sign, intpart, fracpart, exp, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003829
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003830def _dec_from_triple(sign, coefficient, exponent, special=False):
3831 """Create a decimal instance directly, without any validation,
3832 normalization (e.g. removal of leading zeros) or argument
3833 conversion.
3834
3835 This function is for *internal use only*.
3836 """
3837
3838 self = object.__new__(Decimal)
3839 self._sign = sign
3840 self._int = coefficient
3841 self._exp = exponent
3842 self._is_special = special
3843
3844 return self
3845
Raymond Hettinger82417ca2009-02-03 03:54:28 +00003846# Register Decimal as a kind of Number (an abstract base class).
3847# However, do not register it as Real (because Decimals are not
3848# interoperable with floats).
3849_numbers.Number.register(Decimal)
3850
3851
Guido van Rossumd8faa362007-04-27 19:54:29 +00003852##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003853
Thomas Wouters89f507f2006-12-13 04:49:30 +00003854class _ContextManager(object):
3855 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003856
Thomas Wouters89f507f2006-12-13 04:49:30 +00003857 Sets a copy of the supplied context in __enter__() and restores
3858 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003859 """
3860 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003861 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003862 def __enter__(self):
3863 self.saved_context = getcontext()
3864 setcontext(self.new_context)
3865 return self.new_context
3866 def __exit__(self, t, v, tb):
3867 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003868
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003869class Context(object):
3870 """Contains the context for a Decimal instance.
3871
3872 Contains:
3873 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003874 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003875 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003876 raised when it is caused. Otherwise, a value is
3877 substituted in.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003878 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003879 (Whether or not the trap_enabler is set)
3880 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003881 Emin - Minimum exponent
3882 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003883 capitals - If 1, 1*10^1 is printed as 1E+1.
3884 If 0, printed as 1e1
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00003885 clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003886 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003887
Stefan Krah1919b7e2012-03-21 18:25:23 +01003888 def __init__(self, prec=None, rounding=None, Emin=None, Emax=None,
3889 capitals=None, clamp=None, flags=None, traps=None,
3890 _ignored_flags=None):
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003891 # Set defaults; for everything except flags and _ignored_flags,
3892 # inherit from DefaultContext.
3893 try:
3894 dc = DefaultContext
3895 except NameError:
3896 pass
3897
3898 self.prec = prec if prec is not None else dc.prec
3899 self.rounding = rounding if rounding is not None else dc.rounding
3900 self.Emin = Emin if Emin is not None else dc.Emin
3901 self.Emax = Emax if Emax is not None else dc.Emax
3902 self.capitals = capitals if capitals is not None else dc.capitals
3903 self.clamp = clamp if clamp is not None else dc.clamp
3904
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003905 if _ignored_flags is None:
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003906 self._ignored_flags = []
3907 else:
3908 self._ignored_flags = _ignored_flags
3909
3910 if traps is None:
3911 self.traps = dc.traps.copy()
3912 elif not isinstance(traps, dict):
Stefan Krah1919b7e2012-03-21 18:25:23 +01003913 self.traps = dict((s, int(s in traps)) for s in _signals + traps)
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003914 else:
3915 self.traps = traps
3916
3917 if flags is None:
3918 self.flags = dict.fromkeys(_signals, 0)
3919 elif not isinstance(flags, dict):
Stefan Krah1919b7e2012-03-21 18:25:23 +01003920 self.flags = dict((s, int(s in flags)) for s in _signals + flags)
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003921 else:
3922 self.flags = flags
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003923
Stefan Krah1919b7e2012-03-21 18:25:23 +01003924 def _set_integer_check(self, name, value, vmin, vmax):
3925 if not isinstance(value, int):
3926 raise TypeError("%s must be an integer" % name)
3927 if vmin == '-inf':
3928 if value > vmax:
3929 raise ValueError("%s must be in [%s, %d]. got: %s" % (name, vmin, vmax, value))
3930 elif vmax == 'inf':
3931 if value < vmin:
3932 raise ValueError("%s must be in [%d, %s]. got: %s" % (name, vmin, vmax, value))
3933 else:
3934 if value < vmin or value > vmax:
3935 raise ValueError("%s must be in [%d, %d]. got %s" % (name, vmin, vmax, value))
3936 return object.__setattr__(self, name, value)
3937
3938 def _set_signal_dict(self, name, d):
3939 if not isinstance(d, dict):
3940 raise TypeError("%s must be a signal dict" % d)
3941 for key in d:
3942 if not key in _signals:
3943 raise KeyError("%s is not a valid signal dict" % d)
3944 for key in _signals:
3945 if not key in d:
3946 raise KeyError("%s is not a valid signal dict" % d)
3947 return object.__setattr__(self, name, d)
3948
3949 def __setattr__(self, name, value):
3950 if name == 'prec':
3951 return self._set_integer_check(name, value, 1, 'inf')
3952 elif name == 'Emin':
3953 return self._set_integer_check(name, value, '-inf', 0)
3954 elif name == 'Emax':
3955 return self._set_integer_check(name, value, 0, 'inf')
3956 elif name == 'capitals':
3957 return self._set_integer_check(name, value, 0, 1)
3958 elif name == 'clamp':
3959 return self._set_integer_check(name, value, 0, 1)
3960 elif name == 'rounding':
3961 if not value in _rounding_modes:
3962 # raise TypeError even for strings to have consistency
3963 # among various implementations.
3964 raise TypeError("%s: invalid rounding mode" % value)
3965 return object.__setattr__(self, name, value)
3966 elif name == 'flags' or name == 'traps':
3967 return self._set_signal_dict(name, value)
3968 elif name == '_ignored_flags':
3969 return object.__setattr__(self, name, value)
3970 else:
3971 raise AttributeError(
3972 "'decimal.Context' object has no attribute '%s'" % name)
3973
3974 def __delattr__(self, name):
3975 raise AttributeError("%s cannot be deleted" % name)
3976
3977 # Support for pickling, copy, and deepcopy
3978 def __reduce__(self):
3979 flags = [sig for sig, v in self.flags.items() if v]
3980 traps = [sig for sig, v in self.traps.items() if v]
3981 return (self.__class__,
3982 (self.prec, self.rounding, self.Emin, self.Emax,
3983 self.capitals, self.clamp, flags, traps))
3984
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003985 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003986 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003987 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003988 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00003989 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d, '
3990 'clamp=%(clamp)d'
Guido van Rossumd8faa362007-04-27 19:54:29 +00003991 % vars(self))
3992 names = [f.__name__ for f, v in self.flags.items() if v]
3993 s.append('flags=[' + ', '.join(names) + ']')
3994 names = [t.__name__ for t, v in self.traps.items() if v]
3995 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003996 return ', '.join(s) + ')'
3997
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003998 def clear_flags(self):
3999 """Reset all flags to zero"""
4000 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00004001 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00004002
Stefan Krah1919b7e2012-03-21 18:25:23 +01004003 def clear_traps(self):
4004 """Reset all traps to zero"""
4005 for flag in self.traps:
4006 self.traps[flag] = 0
4007
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004008 def _shallow_copy(self):
4009 """Returns a shallow copy from self."""
Stefan Krah1919b7e2012-03-21 18:25:23 +01004010 nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
4011 self.capitals, self.clamp, self.flags, self.traps,
4012 self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004013 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004014
4015 def copy(self):
4016 """Returns a deep copy from self."""
Stefan Krah1919b7e2012-03-21 18:25:23 +01004017 nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
4018 self.capitals, self.clamp,
4019 self.flags.copy(), self.traps.copy(),
4020 self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004021 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004022 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004023
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004024 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004025 """Handles an error
4026
4027 If the flag is in _ignored_flags, returns the default response.
Raymond Hettinger86173da2008-02-01 20:38:12 +00004028 Otherwise, it sets the flag, then, if the corresponding
Stefan Krah2eb4a072010-05-19 15:52:31 +00004029 trap_enabler is set, it reraises the exception. Otherwise, it returns
Raymond Hettinger86173da2008-02-01 20:38:12 +00004030 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004031 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004032 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004033 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00004034 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004035 return error().handle(self, *args)
4036
Raymond Hettinger86173da2008-02-01 20:38:12 +00004037 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00004038 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00004039 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004040 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004041
4042 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00004043 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00004044 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004045
4046 def _ignore_all_flags(self):
4047 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00004048 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004049
4050 def _ignore_flags(self, *flags):
4051 """Ignore the flags, if they are raised"""
4052 # Do not mutate-- This way, copies of a context leave the original
4053 # alone.
4054 self._ignored_flags = (self._ignored_flags + list(flags))
4055 return list(flags)
4056
4057 def _regard_flags(self, *flags):
4058 """Stop ignoring the flags, if they are raised"""
4059 if flags and isinstance(flags[0], (tuple,list)):
4060 flags = flags[0]
4061 for flag in flags:
4062 self._ignored_flags.remove(flag)
4063
Nick Coghland1abd252008-07-15 15:46:38 +00004064 # We inherit object.__hash__, so we must deny this explicitly
4065 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004066
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004067 def Etiny(self):
4068 """Returns Etiny (= Emin - prec + 1)"""
4069 return int(self.Emin - self.prec + 1)
4070
4071 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004072 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004073 return int(self.Emax - self.prec + 1)
4074
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004075 def _set_rounding(self, type):
4076 """Sets the rounding type.
4077
4078 Sets the rounding type, and returns the current (previous)
4079 rounding type. Often used like:
4080
4081 context = context.copy()
4082 # so you don't change the calling context
4083 # if an error occurs in the middle.
4084 rounding = context._set_rounding(ROUND_UP)
4085 val = self.__sub__(other, context=context)
4086 context._set_rounding(rounding)
4087
4088 This will make it round up for that operation.
4089 """
4090 rounding = self.rounding
4091 self.rounding= type
4092 return rounding
4093
Raymond Hettingerfed52962004-07-14 15:41:57 +00004094 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00004095 """Creates a new Decimal instance but using self as context.
4096
4097 This method implements the to-number operation of the
4098 IBM Decimal specification."""
4099
4100 if isinstance(num, str) and num != num.strip():
4101 return self._raise_error(ConversionSyntax,
4102 "no trailing or leading whitespace is "
4103 "permitted.")
4104
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004105 d = Decimal(num, context=self)
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00004106 if d._isnan() and len(d._int) > self.prec - self.clamp:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004107 return self._raise_error(ConversionSyntax,
4108 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00004109 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004110
Raymond Hettinger771ed762009-01-03 19:20:32 +00004111 def create_decimal_from_float(self, f):
4112 """Creates a new Decimal instance from a float but rounding using self
4113 as the context.
4114
4115 >>> context = Context(prec=5, rounding=ROUND_DOWN)
4116 >>> context.create_decimal_from_float(3.1415926535897932)
4117 Decimal('3.1415')
4118 >>> context = Context(prec=5, traps=[Inexact])
4119 >>> context.create_decimal_from_float(3.1415926535897932)
4120 Traceback (most recent call last):
4121 ...
4122 decimal.Inexact: None
4123
4124 """
4125 d = Decimal.from_float(f) # An exact conversion
4126 return d._fix(self) # Apply the context rounding
4127
Guido van Rossumd8faa362007-04-27 19:54:29 +00004128 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004129 def abs(self, a):
4130 """Returns the absolute value of the operand.
4131
4132 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00004133 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004134 the plus operation on the operand.
4135
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004136 >>> ExtendedContext.abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004137 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004138 >>> ExtendedContext.abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004139 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004140 >>> ExtendedContext.abs(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004141 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004142 >>> ExtendedContext.abs(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004143 Decimal('101.5')
Mark Dickinson84230a12010-02-18 14:49:50 +00004144 >>> ExtendedContext.abs(-1)
4145 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004146 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004147 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004148 return a.__abs__(context=self)
4149
4150 def add(self, a, b):
4151 """Return the sum of the two operands.
4152
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004153 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004154 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004155 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004156 Decimal('1.02E+4')
Mark Dickinson84230a12010-02-18 14:49:50 +00004157 >>> ExtendedContext.add(1, Decimal(2))
4158 Decimal('3')
4159 >>> ExtendedContext.add(Decimal(8), 5)
4160 Decimal('13')
4161 >>> ExtendedContext.add(5, 5)
4162 Decimal('10')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004163 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004164 a = _convert_other(a, raiseit=True)
4165 r = a.__add__(b, context=self)
4166 if r is NotImplemented:
4167 raise TypeError("Unable to convert %s to Decimal" % b)
4168 else:
4169 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004170
4171 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00004172 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004173
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004174 def canonical(self, a):
4175 """Returns the same Decimal object.
4176
4177 As we do not have different encodings for the same number, the
4178 received object already is in its canonical form.
4179
4180 >>> ExtendedContext.canonical(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004181 Decimal('2.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004182 """
Stefan Krah1919b7e2012-03-21 18:25:23 +01004183 if not isinstance(a, Decimal):
4184 raise TypeError("canonical requires a Decimal as an argument.")
Stefan Krah040e3112012-12-15 22:33:33 +01004185 return a.canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004186
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004187 def compare(self, a, b):
4188 """Compares values numerically.
4189
4190 If the signs of the operands differ, a value representing each operand
4191 ('-1' if the operand is less than zero, '0' if the operand is zero or
4192 negative zero, or '1' if the operand is greater than zero) is used in
4193 place of that operand for the comparison instead of the actual
4194 operand.
4195
4196 The comparison is then effected by subtracting the second operand from
4197 the first and then returning a value according to the result of the
4198 subtraction: '-1' if the result is less than zero, '0' if the result is
4199 zero or negative zero, or '1' if the result is greater than zero.
4200
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004201 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004202 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004203 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004204 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004205 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004206 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004207 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004208 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004209 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004210 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004211 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004212 Decimal('-1')
Mark Dickinson84230a12010-02-18 14:49:50 +00004213 >>> ExtendedContext.compare(1, 2)
4214 Decimal('-1')
4215 >>> ExtendedContext.compare(Decimal(1), 2)
4216 Decimal('-1')
4217 >>> ExtendedContext.compare(1, Decimal(2))
4218 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004219 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004220 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004221 return a.compare(b, context=self)
4222
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004223 def compare_signal(self, a, b):
4224 """Compares the values of the two operands numerically.
4225
4226 It's pretty much like compare(), but all NaNs signal, with signaling
4227 NaNs taking precedence over quiet NaNs.
4228
4229 >>> c = ExtendedContext
4230 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004231 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004232 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004233 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004234 >>> c.flags[InvalidOperation] = 0
4235 >>> print(c.flags[InvalidOperation])
4236 0
4237 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004238 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004239 >>> print(c.flags[InvalidOperation])
4240 1
4241 >>> c.flags[InvalidOperation] = 0
4242 >>> print(c.flags[InvalidOperation])
4243 0
4244 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004245 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004246 >>> print(c.flags[InvalidOperation])
4247 1
Mark Dickinson84230a12010-02-18 14:49:50 +00004248 >>> c.compare_signal(-1, 2)
4249 Decimal('-1')
4250 >>> c.compare_signal(Decimal(-1), 2)
4251 Decimal('-1')
4252 >>> c.compare_signal(-1, Decimal(2))
4253 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004254 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004255 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004256 return a.compare_signal(b, context=self)
4257
4258 def compare_total(self, a, b):
4259 """Compares two operands using their abstract representation.
4260
4261 This is not like the standard compare, which use their numerical
4262 value. Note that a total ordering is defined for all possible abstract
4263 representations.
4264
4265 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004266 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004267 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004268 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004269 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004270 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004271 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004272 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004273 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004274 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004275 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004276 Decimal('-1')
Mark Dickinson84230a12010-02-18 14:49:50 +00004277 >>> ExtendedContext.compare_total(1, 2)
4278 Decimal('-1')
4279 >>> ExtendedContext.compare_total(Decimal(1), 2)
4280 Decimal('-1')
4281 >>> ExtendedContext.compare_total(1, Decimal(2))
4282 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004283 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004284 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004285 return a.compare_total(b)
4286
4287 def compare_total_mag(self, a, b):
4288 """Compares two operands using their abstract representation ignoring sign.
4289
4290 Like compare_total, but with operand's sign ignored and assumed to be 0.
4291 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004292 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004293 return a.compare_total_mag(b)
4294
4295 def copy_abs(self, a):
4296 """Returns a copy of the operand with the sign set to 0.
4297
4298 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004299 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004300 >>> ExtendedContext.copy_abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004301 Decimal('100')
Mark Dickinson84230a12010-02-18 14:49:50 +00004302 >>> ExtendedContext.copy_abs(-1)
4303 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004304 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004305 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004306 return a.copy_abs()
4307
4308 def copy_decimal(self, a):
Mark Dickinson84230a12010-02-18 14:49:50 +00004309 """Returns a copy of the decimal object.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004310
4311 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004312 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004313 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004314 Decimal('-1.00')
Mark Dickinson84230a12010-02-18 14:49:50 +00004315 >>> ExtendedContext.copy_decimal(1)
4316 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004317 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004318 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004319 return Decimal(a)
4320
4321 def copy_negate(self, a):
4322 """Returns a copy of the operand with the sign inverted.
4323
4324 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004325 Decimal('-101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004326 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004327 Decimal('101.5')
Mark Dickinson84230a12010-02-18 14:49:50 +00004328 >>> ExtendedContext.copy_negate(1)
4329 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004330 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004331 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004332 return a.copy_negate()
4333
4334 def copy_sign(self, a, b):
4335 """Copies the second operand's sign to the first one.
4336
4337 In detail, it returns a copy of the first operand with the sign
4338 equal to the sign of the second operand.
4339
4340 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004341 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004342 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004343 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004344 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004345 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004346 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004347 Decimal('-1.50')
Mark Dickinson84230a12010-02-18 14:49:50 +00004348 >>> ExtendedContext.copy_sign(1, -2)
4349 Decimal('-1')
4350 >>> ExtendedContext.copy_sign(Decimal(1), -2)
4351 Decimal('-1')
4352 >>> ExtendedContext.copy_sign(1, Decimal(-2))
4353 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004354 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004355 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004356 return a.copy_sign(b)
4357
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004358 def divide(self, a, b):
4359 """Decimal division in a specified context.
4360
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004361 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004362 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004363 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004364 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004365 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004366 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004367 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004368 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004369 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004370 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004371 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004372 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004373 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004374 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004375 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004376 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004377 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004378 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004379 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004380 Decimal('1.20E+6')
Mark Dickinson84230a12010-02-18 14:49:50 +00004381 >>> ExtendedContext.divide(5, 5)
4382 Decimal('1')
4383 >>> ExtendedContext.divide(Decimal(5), 5)
4384 Decimal('1')
4385 >>> ExtendedContext.divide(5, Decimal(5))
4386 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004387 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004388 a = _convert_other(a, raiseit=True)
4389 r = a.__truediv__(b, context=self)
4390 if r is NotImplemented:
4391 raise TypeError("Unable to convert %s to Decimal" % b)
4392 else:
4393 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004394
4395 def divide_int(self, a, b):
4396 """Divides two numbers and returns the integer part of the result.
4397
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004398 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004399 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004400 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004401 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004402 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004403 Decimal('3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004404 >>> ExtendedContext.divide_int(10, 3)
4405 Decimal('3')
4406 >>> ExtendedContext.divide_int(Decimal(10), 3)
4407 Decimal('3')
4408 >>> ExtendedContext.divide_int(10, Decimal(3))
4409 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004410 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004411 a = _convert_other(a, raiseit=True)
4412 r = a.__floordiv__(b, context=self)
4413 if r is NotImplemented:
4414 raise TypeError("Unable to convert %s to Decimal" % b)
4415 else:
4416 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004417
4418 def divmod(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004419 """Return (a // b, a % b).
Mark Dickinsonc53796e2010-01-06 16:22:15 +00004420
4421 >>> ExtendedContext.divmod(Decimal(8), Decimal(3))
4422 (Decimal('2'), Decimal('2'))
4423 >>> ExtendedContext.divmod(Decimal(8), Decimal(4))
4424 (Decimal('2'), Decimal('0'))
Mark Dickinson84230a12010-02-18 14:49:50 +00004425 >>> ExtendedContext.divmod(8, 4)
4426 (Decimal('2'), Decimal('0'))
4427 >>> ExtendedContext.divmod(Decimal(8), 4)
4428 (Decimal('2'), Decimal('0'))
4429 >>> ExtendedContext.divmod(8, Decimal(4))
4430 (Decimal('2'), Decimal('0'))
Mark Dickinsonc53796e2010-01-06 16:22:15 +00004431 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004432 a = _convert_other(a, raiseit=True)
4433 r = a.__divmod__(b, context=self)
4434 if r is NotImplemented:
4435 raise TypeError("Unable to convert %s to Decimal" % b)
4436 else:
4437 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004438
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004439 def exp(self, a):
4440 """Returns e ** a.
4441
4442 >>> c = ExtendedContext.copy()
4443 >>> c.Emin = -999
4444 >>> c.Emax = 999
4445 >>> c.exp(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004446 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004447 >>> c.exp(Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004448 Decimal('0.367879441')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004449 >>> c.exp(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004450 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004451 >>> c.exp(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004452 Decimal('2.71828183')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004453 >>> c.exp(Decimal('0.693147181'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004454 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004455 >>> c.exp(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004456 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004457 >>> c.exp(10)
4458 Decimal('22026.4658')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004459 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004460 a =_convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004461 return a.exp(context=self)
4462
4463 def fma(self, a, b, c):
4464 """Returns a multiplied by b, plus c.
4465
4466 The first two operands are multiplied together, using multiply,
4467 the third operand is then added to the result of that
4468 multiplication, using add, all with only one final rounding.
4469
4470 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004471 Decimal('22')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004472 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004473 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004474 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004475 Decimal('1.38435736E+12')
Mark Dickinson84230a12010-02-18 14:49:50 +00004476 >>> ExtendedContext.fma(1, 3, 4)
4477 Decimal('7')
4478 >>> ExtendedContext.fma(1, Decimal(3), 4)
4479 Decimal('7')
4480 >>> ExtendedContext.fma(1, 3, Decimal(4))
4481 Decimal('7')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004482 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004483 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004484 return a.fma(b, c, context=self)
4485
4486 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004487 """Return True if the operand is canonical; otherwise return False.
4488
4489 Currently, the encoding of a Decimal instance is always
4490 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004491
4492 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004493 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004494 """
Stefan Krah1919b7e2012-03-21 18:25:23 +01004495 if not isinstance(a, Decimal):
4496 raise TypeError("is_canonical requires a Decimal as an argument.")
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004497 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004498
4499 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004500 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004501
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004502 A Decimal instance is considered finite if it is neither
4503 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004504
4505 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004506 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004507 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004508 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004509 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004510 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004511 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004512 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004513 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004514 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004515 >>> ExtendedContext.is_finite(1)
4516 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004517 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004518 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004519 return a.is_finite()
4520
4521 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004522 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004523
4524 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004525 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004526 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004527 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004528 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004529 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004530 >>> ExtendedContext.is_infinite(1)
4531 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004532 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004533 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004534 return a.is_infinite()
4535
4536 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004537 """Return True if the operand is a qNaN or sNaN;
4538 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004539
4540 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004541 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004542 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004543 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004544 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004545 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004546 >>> ExtendedContext.is_nan(1)
4547 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004548 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004549 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004550 return a.is_nan()
4551
4552 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004553 """Return True if the operand is a normal number;
4554 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004555
4556 >>> c = ExtendedContext.copy()
4557 >>> c.Emin = -999
4558 >>> c.Emax = 999
4559 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004560 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004561 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004562 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004563 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004564 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004565 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004566 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004567 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004568 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004569 >>> c.is_normal(1)
4570 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004571 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004572 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004573 return a.is_normal(context=self)
4574
4575 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004576 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004577
4578 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004579 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004580 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004581 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004582 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004583 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004584 >>> ExtendedContext.is_qnan(1)
4585 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004586 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004587 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004588 return a.is_qnan()
4589
4590 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004591 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004592
4593 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004594 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004595 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004596 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004597 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004598 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004599 >>> ExtendedContext.is_signed(8)
4600 False
4601 >>> ExtendedContext.is_signed(-8)
4602 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004603 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004604 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004605 return a.is_signed()
4606
4607 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004608 """Return True if the operand is a signaling NaN;
4609 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004610
4611 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004612 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004613 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004614 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004615 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004616 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004617 >>> ExtendedContext.is_snan(1)
4618 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004619 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004620 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004621 return a.is_snan()
4622
4623 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004624 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004625
4626 >>> c = ExtendedContext.copy()
4627 >>> c.Emin = -999
4628 >>> c.Emax = 999
4629 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004630 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004631 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004632 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004633 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004634 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004635 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004636 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004637 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004638 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004639 >>> c.is_subnormal(1)
4640 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004641 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004642 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004643 return a.is_subnormal(context=self)
4644
4645 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004646 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004647
4648 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004649 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004650 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004651 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004652 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004653 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004654 >>> ExtendedContext.is_zero(1)
4655 False
4656 >>> ExtendedContext.is_zero(0)
4657 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004658 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004659 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004660 return a.is_zero()
4661
4662 def ln(self, a):
4663 """Returns the natural (base e) logarithm of the operand.
4664
4665 >>> c = ExtendedContext.copy()
4666 >>> c.Emin = -999
4667 >>> c.Emax = 999
4668 >>> c.ln(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004669 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004670 >>> c.ln(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004671 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004672 >>> c.ln(Decimal('2.71828183'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004673 Decimal('1.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004674 >>> c.ln(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004675 Decimal('2.30258509')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004676 >>> c.ln(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004677 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004678 >>> c.ln(1)
4679 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004680 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004681 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004682 return a.ln(context=self)
4683
4684 def log10(self, a):
4685 """Returns the base 10 logarithm of the operand.
4686
4687 >>> c = ExtendedContext.copy()
4688 >>> c.Emin = -999
4689 >>> c.Emax = 999
4690 >>> c.log10(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004691 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004692 >>> c.log10(Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004693 Decimal('-3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004694 >>> c.log10(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004695 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004696 >>> c.log10(Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004697 Decimal('0.301029996')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004698 >>> c.log10(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004699 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004700 >>> c.log10(Decimal('70'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004701 Decimal('1.84509804')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004702 >>> c.log10(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004703 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004704 >>> c.log10(0)
4705 Decimal('-Infinity')
4706 >>> c.log10(1)
4707 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004708 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004709 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004710 return a.log10(context=self)
4711
4712 def logb(self, a):
4713 """ Returns the exponent of the magnitude of the operand's MSD.
4714
4715 The result is the integer which is the exponent of the magnitude
4716 of the most significant digit of the operand (as though the
4717 operand were truncated to a single digit while maintaining the
4718 value of that digit and without limiting the resulting exponent).
4719
4720 >>> ExtendedContext.logb(Decimal('250'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004721 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004722 >>> ExtendedContext.logb(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004723 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004724 >>> ExtendedContext.logb(Decimal('0.03'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004725 Decimal('-2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004726 >>> ExtendedContext.logb(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004727 Decimal('-Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004728 >>> ExtendedContext.logb(1)
4729 Decimal('0')
4730 >>> ExtendedContext.logb(10)
4731 Decimal('1')
4732 >>> ExtendedContext.logb(100)
4733 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004734 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004735 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004736 return a.logb(context=self)
4737
4738 def logical_and(self, a, b):
4739 """Applies the logical operation 'and' between each operand's digits.
4740
4741 The operands must be both logical numbers.
4742
4743 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004744 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004745 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004746 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004747 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004748 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004749 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004750 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004751 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004752 Decimal('1000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004753 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004754 Decimal('10')
Mark Dickinson84230a12010-02-18 14:49:50 +00004755 >>> ExtendedContext.logical_and(110, 1101)
4756 Decimal('100')
4757 >>> ExtendedContext.logical_and(Decimal(110), 1101)
4758 Decimal('100')
4759 >>> ExtendedContext.logical_and(110, Decimal(1101))
4760 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004761 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004762 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004763 return a.logical_and(b, context=self)
4764
4765 def logical_invert(self, a):
4766 """Invert all the digits in the operand.
4767
4768 The operand must be a logical number.
4769
4770 >>> ExtendedContext.logical_invert(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004771 Decimal('111111111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004772 >>> ExtendedContext.logical_invert(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004773 Decimal('111111110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004774 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004775 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004776 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004777 Decimal('10101010')
Mark Dickinson84230a12010-02-18 14:49:50 +00004778 >>> ExtendedContext.logical_invert(1101)
4779 Decimal('111110010')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004780 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004781 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004782 return a.logical_invert(context=self)
4783
4784 def logical_or(self, a, b):
4785 """Applies the logical operation 'or' between each operand's digits.
4786
4787 The operands must be both logical numbers.
4788
4789 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004790 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004791 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004792 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004793 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004794 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004795 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004796 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004797 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004798 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004799 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004800 Decimal('1110')
Mark Dickinson84230a12010-02-18 14:49:50 +00004801 >>> ExtendedContext.logical_or(110, 1101)
4802 Decimal('1111')
4803 >>> ExtendedContext.logical_or(Decimal(110), 1101)
4804 Decimal('1111')
4805 >>> ExtendedContext.logical_or(110, Decimal(1101))
4806 Decimal('1111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004807 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004808 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004809 return a.logical_or(b, context=self)
4810
4811 def logical_xor(self, a, b):
4812 """Applies the logical operation 'xor' between each operand's digits.
4813
4814 The operands must be both logical numbers.
4815
4816 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004817 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004818 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004819 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004820 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004821 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004822 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004823 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004824 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004825 Decimal('110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004826 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004827 Decimal('1101')
Mark Dickinson84230a12010-02-18 14:49:50 +00004828 >>> ExtendedContext.logical_xor(110, 1101)
4829 Decimal('1011')
4830 >>> ExtendedContext.logical_xor(Decimal(110), 1101)
4831 Decimal('1011')
4832 >>> ExtendedContext.logical_xor(110, Decimal(1101))
4833 Decimal('1011')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004834 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004835 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004836 return a.logical_xor(b, context=self)
4837
Mark Dickinson84230a12010-02-18 14:49:50 +00004838 def max(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004839 """max compares two values numerically and returns the maximum.
4840
4841 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004842 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004843 operation. If they are numerically equal then the left-hand operand
4844 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004845 infinity) of the two operands is chosen as the result.
4846
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004847 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004848 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004849 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004850 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004851 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004852 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004853 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004854 Decimal('7')
Mark Dickinson84230a12010-02-18 14:49:50 +00004855 >>> ExtendedContext.max(1, 2)
4856 Decimal('2')
4857 >>> ExtendedContext.max(Decimal(1), 2)
4858 Decimal('2')
4859 >>> ExtendedContext.max(1, Decimal(2))
4860 Decimal('2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004861 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004862 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004863 return a.max(b, context=self)
4864
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004865 def max_mag(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004866 """Compares the values numerically with their sign ignored.
4867
4868 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
4869 Decimal('7')
4870 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
4871 Decimal('-10')
4872 >>> ExtendedContext.max_mag(1, -2)
4873 Decimal('-2')
4874 >>> ExtendedContext.max_mag(Decimal(1), -2)
4875 Decimal('-2')
4876 >>> ExtendedContext.max_mag(1, Decimal(-2))
4877 Decimal('-2')
4878 """
4879 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004880 return a.max_mag(b, context=self)
4881
Mark Dickinson84230a12010-02-18 14:49:50 +00004882 def min(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004883 """min compares two values numerically and returns the minimum.
4884
4885 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004886 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004887 operation. If they are numerically equal then the left-hand operand
4888 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004889 infinity) of the two operands is chosen as the result.
4890
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004891 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004892 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004893 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004894 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004895 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004896 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004897 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004898 Decimal('7')
Mark Dickinson84230a12010-02-18 14:49:50 +00004899 >>> ExtendedContext.min(1, 2)
4900 Decimal('1')
4901 >>> ExtendedContext.min(Decimal(1), 2)
4902 Decimal('1')
4903 >>> ExtendedContext.min(1, Decimal(29))
4904 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004905 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004906 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004907 return a.min(b, context=self)
4908
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004909 def min_mag(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004910 """Compares the values numerically with their sign ignored.
4911
4912 >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2'))
4913 Decimal('-2')
4914 >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN'))
4915 Decimal('-3')
4916 >>> ExtendedContext.min_mag(1, -2)
4917 Decimal('1')
4918 >>> ExtendedContext.min_mag(Decimal(1), -2)
4919 Decimal('1')
4920 >>> ExtendedContext.min_mag(1, Decimal(-2))
4921 Decimal('1')
4922 """
4923 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004924 return a.min_mag(b, context=self)
4925
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004926 def minus(self, a):
4927 """Minus corresponds to unary prefix minus in Python.
4928
4929 The operation is evaluated using the same rules as subtract; the
4930 operation minus(a) is calculated as subtract('0', a) where the '0'
4931 has the same exponent as the operand.
4932
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004933 >>> ExtendedContext.minus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004934 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004935 >>> ExtendedContext.minus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004936 Decimal('1.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004937 >>> ExtendedContext.minus(1)
4938 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004939 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004940 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004941 return a.__neg__(context=self)
4942
4943 def multiply(self, a, b):
4944 """multiply multiplies two operands.
4945
4946 If either operand is a special value then the general rules apply.
Mark Dickinson84230a12010-02-18 14:49:50 +00004947 Otherwise, the operands are multiplied together
4948 ('long multiplication'), resulting in a number which may be as long as
4949 the sum of the lengths of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004950
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004951 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004952 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004953 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004954 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004955 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004956 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004957 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004958 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004959 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004960 Decimal('4.28135971E+11')
Mark Dickinson84230a12010-02-18 14:49:50 +00004961 >>> ExtendedContext.multiply(7, 7)
4962 Decimal('49')
4963 >>> ExtendedContext.multiply(Decimal(7), 7)
4964 Decimal('49')
4965 >>> ExtendedContext.multiply(7, Decimal(7))
4966 Decimal('49')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004967 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004968 a = _convert_other(a, raiseit=True)
4969 r = a.__mul__(b, context=self)
4970 if r is NotImplemented:
4971 raise TypeError("Unable to convert %s to Decimal" % b)
4972 else:
4973 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004974
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004975 def next_minus(self, a):
4976 """Returns the largest representable number smaller than a.
4977
4978 >>> c = ExtendedContext.copy()
4979 >>> c.Emin = -999
4980 >>> c.Emax = 999
4981 >>> ExtendedContext.next_minus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004982 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004983 >>> c.next_minus(Decimal('1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004984 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004985 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004986 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004987 >>> c.next_minus(Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004988 Decimal('9.99999999E+999')
Mark Dickinson84230a12010-02-18 14:49:50 +00004989 >>> c.next_minus(1)
4990 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004991 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004992 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004993 return a.next_minus(context=self)
4994
4995 def next_plus(self, a):
4996 """Returns the smallest representable number larger than a.
4997
4998 >>> c = ExtendedContext.copy()
4999 >>> c.Emin = -999
5000 >>> c.Emax = 999
5001 >>> ExtendedContext.next_plus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005002 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005003 >>> c.next_plus(Decimal('-1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005004 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005005 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005006 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005007 >>> c.next_plus(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005008 Decimal('-9.99999999E+999')
Mark Dickinson84230a12010-02-18 14:49:50 +00005009 >>> c.next_plus(1)
5010 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005011 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005012 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005013 return a.next_plus(context=self)
5014
5015 def next_toward(self, a, b):
5016 """Returns the number closest to a, in direction towards b.
5017
5018 The result is the closest representable number from the first
5019 operand (but not the first operand) that is in the direction
5020 towards the second operand, unless the operands have the same
5021 value.
5022
5023 >>> c = ExtendedContext.copy()
5024 >>> c.Emin = -999
5025 >>> c.Emax = 999
5026 >>> c.next_toward(Decimal('1'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005027 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005028 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005029 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005030 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005031 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005032 >>> c.next_toward(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005033 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005034 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005035 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005036 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005037 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005038 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005039 Decimal('-0.00')
Mark Dickinson84230a12010-02-18 14:49:50 +00005040 >>> c.next_toward(0, 1)
5041 Decimal('1E-1007')
5042 >>> c.next_toward(Decimal(0), 1)
5043 Decimal('1E-1007')
5044 >>> c.next_toward(0, Decimal(1))
5045 Decimal('1E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005046 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005047 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005048 return a.next_toward(b, context=self)
5049
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005050 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00005051 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005052
5053 Essentially a plus operation with all trailing zeros removed from the
5054 result.
5055
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005056 >>> ExtendedContext.normalize(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005057 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005058 >>> ExtendedContext.normalize(Decimal('-2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005059 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005060 >>> ExtendedContext.normalize(Decimal('1.200'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005061 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005062 >>> ExtendedContext.normalize(Decimal('-120'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005063 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005064 >>> ExtendedContext.normalize(Decimal('120.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005065 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005066 >>> ExtendedContext.normalize(Decimal('0.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005067 Decimal('0')
Mark Dickinson84230a12010-02-18 14:49:50 +00005068 >>> ExtendedContext.normalize(6)
5069 Decimal('6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005070 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005071 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005072 return a.normalize(context=self)
5073
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005074 def number_class(self, a):
5075 """Returns an indication of the class of the operand.
5076
5077 The class is one of the following strings:
5078 -sNaN
5079 -NaN
5080 -Infinity
5081 -Normal
5082 -Subnormal
5083 -Zero
5084 +Zero
5085 +Subnormal
5086 +Normal
5087 +Infinity
5088
Stefan Krah1919b7e2012-03-21 18:25:23 +01005089 >>> c = ExtendedContext.copy()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005090 >>> c.Emin = -999
5091 >>> c.Emax = 999
5092 >>> c.number_class(Decimal('Infinity'))
5093 '+Infinity'
5094 >>> c.number_class(Decimal('1E-10'))
5095 '+Normal'
5096 >>> c.number_class(Decimal('2.50'))
5097 '+Normal'
5098 >>> c.number_class(Decimal('0.1E-999'))
5099 '+Subnormal'
5100 >>> c.number_class(Decimal('0'))
5101 '+Zero'
5102 >>> c.number_class(Decimal('-0'))
5103 '-Zero'
5104 >>> c.number_class(Decimal('-0.1E-999'))
5105 '-Subnormal'
5106 >>> c.number_class(Decimal('-1E-10'))
5107 '-Normal'
5108 >>> c.number_class(Decimal('-2.50'))
5109 '-Normal'
5110 >>> c.number_class(Decimal('-Infinity'))
5111 '-Infinity'
5112 >>> c.number_class(Decimal('NaN'))
5113 'NaN'
5114 >>> c.number_class(Decimal('-NaN'))
5115 'NaN'
5116 >>> c.number_class(Decimal('sNaN'))
5117 'sNaN'
Mark Dickinson84230a12010-02-18 14:49:50 +00005118 >>> c.number_class(123)
5119 '+Normal'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005120 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005121 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005122 return a.number_class(context=self)
5123
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005124 def plus(self, a):
5125 """Plus corresponds to unary prefix plus in Python.
5126
5127 The operation is evaluated using the same rules as add; the
5128 operation plus(a) is calculated as add('0', a) where the '0'
5129 has the same exponent as the operand.
5130
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005131 >>> ExtendedContext.plus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005132 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005133 >>> ExtendedContext.plus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005134 Decimal('-1.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005135 >>> ExtendedContext.plus(-1)
5136 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005137 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005138 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005139 return a.__pos__(context=self)
5140
5141 def power(self, a, b, modulo=None):
5142 """Raises a to the power of b, to modulo if given.
5143
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005144 With two arguments, compute a**b. If a is negative then b
5145 must be integral. The result will be inexact unless b is
5146 integral and the result is finite and can be expressed exactly
5147 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005148
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005149 With three arguments, compute (a**b) % modulo. For the
5150 three argument form, the following restrictions on the
5151 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005152
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005153 - all three arguments must be integral
5154 - b must be nonnegative
5155 - at least one of a or b must be nonzero
5156 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005157
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005158 The result of pow(a, b, modulo) is identical to the result
5159 that would be obtained by computing (a**b) % modulo with
5160 unbounded precision, but is computed more efficiently. It is
5161 always exact.
5162
5163 >>> c = ExtendedContext.copy()
5164 >>> c.Emin = -999
5165 >>> c.Emax = 999
5166 >>> c.power(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005167 Decimal('8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005168 >>> c.power(Decimal('-2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005169 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005170 >>> c.power(Decimal('2'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005171 Decimal('0.125')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005172 >>> c.power(Decimal('1.7'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005173 Decimal('69.7575744')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005174 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005175 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005176 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005177 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005178 >>> c.power(Decimal('Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005179 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005180 >>> c.power(Decimal('Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005181 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005182 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005183 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005184 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005185 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005186 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005187 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005188 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005189 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005190 >>> c.power(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005191 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005192
5193 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005194 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005195 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005196 Decimal('-11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005197 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005198 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005199 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005200 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005201 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005202 Decimal('11729830')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005203 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005204 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005205 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005206 Decimal('1')
Mark Dickinson84230a12010-02-18 14:49:50 +00005207 >>> ExtendedContext.power(7, 7)
5208 Decimal('823543')
5209 >>> ExtendedContext.power(Decimal(7), 7)
5210 Decimal('823543')
5211 >>> ExtendedContext.power(7, Decimal(7), 2)
5212 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005213 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005214 a = _convert_other(a, raiseit=True)
5215 r = a.__pow__(b, modulo, context=self)
5216 if r is NotImplemented:
5217 raise TypeError("Unable to convert %s to Decimal" % b)
5218 else:
5219 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005220
5221 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005222 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005223
5224 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00005225 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005226 exponent is being increased), multiplied by a positive power of ten (if
5227 the exponent is being decreased), or is unchanged (if the exponent is
5228 already equal to that of the right-hand operand).
5229
5230 Unlike other operations, if the length of the coefficient after the
5231 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00005232 operation condition is raised. This guarantees that, unless there is
5233 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005234 equal to that of the right-hand operand.
5235
5236 Also unlike other operations, quantize will never raise Underflow, even
5237 if the result is subnormal and inexact.
5238
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005239 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005240 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005241 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005242 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005243 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005244 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005245 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005246 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005247 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005248 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005249 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005250 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005251 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005252 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005253 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005254 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005255 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005256 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005257 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005258 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005259 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005260 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005261 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005262 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005263 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005264 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005265 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005266 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005267 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005268 Decimal('2E+2')
Mark Dickinson84230a12010-02-18 14:49:50 +00005269 >>> ExtendedContext.quantize(1, 2)
5270 Decimal('1')
5271 >>> ExtendedContext.quantize(Decimal(1), 2)
5272 Decimal('1')
5273 >>> ExtendedContext.quantize(1, Decimal(2))
5274 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005275 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005276 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005277 return a.quantize(b, context=self)
5278
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005279 def radix(self):
5280 """Just returns 10, as this is Decimal, :)
5281
5282 >>> ExtendedContext.radix()
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005283 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005284 """
5285 return Decimal(10)
5286
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005287 def remainder(self, a, b):
5288 """Returns the remainder from integer division.
5289
5290 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00005291 calculating integer division as described for divide-integer, rounded
5292 to precision digits if necessary. The sign of the result, if
5293 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005294
5295 This operation will fail under the same conditions as integer division
5296 (that is, if integer division on the same two operands would fail, the
5297 remainder cannot be calculated).
5298
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005299 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005300 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005301 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005302 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005303 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005304 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005305 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005306 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005307 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005308 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005309 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005310 Decimal('1.0')
Mark Dickinson84230a12010-02-18 14:49:50 +00005311 >>> ExtendedContext.remainder(22, 6)
5312 Decimal('4')
5313 >>> ExtendedContext.remainder(Decimal(22), 6)
5314 Decimal('4')
5315 >>> ExtendedContext.remainder(22, Decimal(6))
5316 Decimal('4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005317 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005318 a = _convert_other(a, raiseit=True)
5319 r = a.__mod__(b, context=self)
5320 if r is NotImplemented:
5321 raise TypeError("Unable to convert %s to Decimal" % b)
5322 else:
5323 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005324
5325 def remainder_near(self, a, b):
5326 """Returns to be "a - b * n", where n is the integer nearest the exact
5327 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00005328 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005329 sign of a.
5330
5331 This operation will fail under the same conditions as integer division
5332 (that is, if integer division on the same two operands would fail, the
5333 remainder cannot be calculated).
5334
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005335 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005336 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005337 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005338 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005339 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005340 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005341 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005342 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005343 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005344 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005345 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005346 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005347 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005348 Decimal('-0.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005349 >>> ExtendedContext.remainder_near(3, 11)
5350 Decimal('3')
5351 >>> ExtendedContext.remainder_near(Decimal(3), 11)
5352 Decimal('3')
5353 >>> ExtendedContext.remainder_near(3, Decimal(11))
5354 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005355 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005356 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005357 return a.remainder_near(b, context=self)
5358
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005359 def rotate(self, a, b):
5360 """Returns a rotated copy of a, b times.
5361
5362 The coefficient of the result is a rotated copy of the digits in
5363 the coefficient of the first operand. The number of places of
5364 rotation is taken from the absolute value of the second operand,
5365 with the rotation being to the left if the second operand is
5366 positive or to the right otherwise.
5367
5368 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005369 Decimal('400000003')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005370 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005371 Decimal('12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005372 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005373 Decimal('891234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005374 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005375 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005376 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005377 Decimal('345678912')
Mark Dickinson84230a12010-02-18 14:49:50 +00005378 >>> ExtendedContext.rotate(1333333, 1)
5379 Decimal('13333330')
5380 >>> ExtendedContext.rotate(Decimal(1333333), 1)
5381 Decimal('13333330')
5382 >>> ExtendedContext.rotate(1333333, Decimal(1))
5383 Decimal('13333330')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005384 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005385 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005386 return a.rotate(b, context=self)
5387
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005388 def same_quantum(self, a, b):
5389 """Returns True if the two operands have the same exponent.
5390
5391 The result is never affected by either the sign or the coefficient of
5392 either operand.
5393
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005394 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005395 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005396 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005397 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005398 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005399 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005400 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005401 True
Mark Dickinson84230a12010-02-18 14:49:50 +00005402 >>> ExtendedContext.same_quantum(10000, -1)
5403 True
5404 >>> ExtendedContext.same_quantum(Decimal(10000), -1)
5405 True
5406 >>> ExtendedContext.same_quantum(10000, Decimal(-1))
5407 True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005408 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005409 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005410 return a.same_quantum(b)
5411
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005412 def scaleb (self, a, b):
5413 """Returns the first operand after adding the second value its exp.
5414
5415 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005416 Decimal('0.0750')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005417 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005418 Decimal('7.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005419 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005420 Decimal('7.50E+3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005421 >>> ExtendedContext.scaleb(1, 4)
5422 Decimal('1E+4')
5423 >>> ExtendedContext.scaleb(Decimal(1), 4)
5424 Decimal('1E+4')
5425 >>> ExtendedContext.scaleb(1, Decimal(4))
5426 Decimal('1E+4')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005427 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005428 a = _convert_other(a, raiseit=True)
5429 return a.scaleb(b, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005430
5431 def shift(self, a, b):
5432 """Returns a shifted copy of a, b times.
5433
5434 The coefficient of the result is a shifted copy of the digits
5435 in the coefficient of the first operand. The number of places
5436 to shift is taken from the absolute value of the second operand,
5437 with the shift being to the left if the second operand is
5438 positive or to the right otherwise. Digits shifted into the
5439 coefficient are zeros.
5440
5441 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005442 Decimal('400000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005443 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005444 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005445 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005446 Decimal('1234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005447 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005448 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005449 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005450 Decimal('345678900')
Mark Dickinson84230a12010-02-18 14:49:50 +00005451 >>> ExtendedContext.shift(88888888, 2)
5452 Decimal('888888800')
5453 >>> ExtendedContext.shift(Decimal(88888888), 2)
5454 Decimal('888888800')
5455 >>> ExtendedContext.shift(88888888, Decimal(2))
5456 Decimal('888888800')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005457 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005458 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005459 return a.shift(b, context=self)
5460
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005461 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005462 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005463
5464 If the result must be inexact, it is rounded using the round-half-even
5465 algorithm.
5466
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005467 >>> ExtendedContext.sqrt(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005468 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005469 >>> ExtendedContext.sqrt(Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005470 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005471 >>> ExtendedContext.sqrt(Decimal('0.39'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005472 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005473 >>> ExtendedContext.sqrt(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005474 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005475 >>> ExtendedContext.sqrt(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005476 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005477 >>> ExtendedContext.sqrt(Decimal('1.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005478 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005479 >>> ExtendedContext.sqrt(Decimal('1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005480 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005481 >>> ExtendedContext.sqrt(Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005482 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005483 >>> ExtendedContext.sqrt(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005484 Decimal('3.16227766')
Mark Dickinson84230a12010-02-18 14:49:50 +00005485 >>> ExtendedContext.sqrt(2)
5486 Decimal('1.41421356')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005487 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005488 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005489 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005490 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005491 return a.sqrt(context=self)
5492
5493 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00005494 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005495
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005496 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005497 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005498 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005499 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005500 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005501 Decimal('-0.77')
Mark Dickinson84230a12010-02-18 14:49:50 +00005502 >>> ExtendedContext.subtract(8, 5)
5503 Decimal('3')
5504 >>> ExtendedContext.subtract(Decimal(8), 5)
5505 Decimal('3')
5506 >>> ExtendedContext.subtract(8, Decimal(5))
5507 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005508 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005509 a = _convert_other(a, raiseit=True)
5510 r = a.__sub__(b, context=self)
5511 if r is NotImplemented:
5512 raise TypeError("Unable to convert %s to Decimal" % b)
5513 else:
5514 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005515
5516 def to_eng_string(self, a):
5517 """Converts a number to a string, using scientific notation.
5518
5519 The operation is not affected by the context.
5520 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005521 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005522 return a.to_eng_string(context=self)
5523
5524 def to_sci_string(self, a):
5525 """Converts a number to a string, using scientific notation.
5526
5527 The operation is not affected by the context.
5528 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005529 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005530 return a.__str__(context=self)
5531
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005532 def to_integral_exact(self, a):
5533 """Rounds to an integer.
5534
5535 When the operand has a negative exponent, the result is the same
5536 as using the quantize() operation using the given operand as the
5537 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5538 of the operand as the precision setting; Inexact and Rounded flags
5539 are allowed in this operation. The rounding mode is taken from the
5540 context.
5541
5542 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005543 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005544 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005545 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005546 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005547 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005548 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005549 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005550 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005551 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005552 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005553 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005554 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005555 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005556 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005557 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005558 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005559 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005560 return a.to_integral_exact(context=self)
5561
5562 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005563 """Rounds to an integer.
5564
5565 When the operand has a negative exponent, the result is the same
5566 as using the quantize() operation using the given operand as the
5567 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5568 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00005569 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005570
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005571 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005572 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005573 >>> ExtendedContext.to_integral_value(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005574 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005575 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005576 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005577 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005578 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005579 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005580 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005581 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005582 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005583 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005584 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005585 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005586 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005587 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005588 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005589 return a.to_integral_value(context=self)
5590
5591 # the method name changed, but we provide also the old one, for compatibility
5592 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005593
5594class _WorkRep(object):
5595 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00005596 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005597 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005598 # exp: None, int, or string
5599
5600 def __init__(self, value=None):
5601 if value is None:
5602 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005603 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005604 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00005605 elif isinstance(value, Decimal):
5606 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005607 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005608 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00005609 else:
5610 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005611 self.sign = value[0]
5612 self.int = value[1]
5613 self.exp = value[2]
5614
5615 def __repr__(self):
5616 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5617
5618 __str__ = __repr__
5619
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005620
5621
Christian Heimes2c181612007-12-17 20:04:13 +00005622def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005623 """Normalizes op1, op2 to have the same exp and length of coefficient.
5624
5625 Done during addition.
5626 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005627 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005628 tmp = op2
5629 other = op1
5630 else:
5631 tmp = op1
5632 other = op2
5633
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005634 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5635 # Then adding 10**exp to tmp has the same effect (after rounding)
5636 # as adding any positive quantity smaller than 10**exp; similarly
5637 # for subtraction. So if other is smaller than 10**exp we replace
5638 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00005639 tmp_len = len(str(tmp.int))
5640 other_len = len(str(other.int))
5641 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5642 if other_len + other.exp - 1 < exp:
5643 other.int = 1
5644 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005645
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005646 tmp.int *= 10 ** (tmp.exp - other.exp)
5647 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005648 return op1, op2
5649
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005650##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005651
Raymond Hettingerdb213a22010-11-27 08:09:40 +00005652_nbits = int.bit_length
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005653
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01005654def _decimal_lshift_exact(n, e):
5655 """ Given integers n and e, return n * 10**e if it's an integer, else None.
5656
5657 The computation is designed to avoid computing large powers of 10
5658 unnecessarily.
5659
5660 >>> _decimal_lshift_exact(3, 4)
5661 30000
5662 >>> _decimal_lshift_exact(300, -999999999) # returns None
5663
5664 """
5665 if n == 0:
5666 return 0
5667 elif e >= 0:
5668 return n * 10**e
5669 else:
5670 # val_n = largest power of 10 dividing n.
5671 str_n = str(abs(n))
5672 val_n = len(str_n) - len(str_n.rstrip('0'))
5673 return None if val_n < -e else n // 10**-e
5674
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005675def _sqrt_nearest(n, a):
5676 """Closest integer to the square root of the positive integer n. a is
5677 an initial approximation to the square root. Any positive integer
5678 will do for a, but the closer a is to the square root of n the
5679 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005680
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005681 """
5682 if n <= 0 or a <= 0:
5683 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5684
5685 b=0
5686 while a != b:
5687 b, a = a, a--n//a>>1
5688 return a
5689
5690def _rshift_nearest(x, shift):
5691 """Given an integer x and a nonnegative integer shift, return closest
5692 integer to x / 2**shift; use round-to-even in case of a tie.
5693
5694 """
5695 b, q = 1 << shift, x >> shift
5696 return q + (2*(x & (b-1)) + (q&1) > b)
5697
5698def _div_nearest(a, b):
5699 """Closest integer to a/b, a and b positive integers; rounds to even
5700 in the case of a tie.
5701
5702 """
5703 q, r = divmod(a, b)
5704 return q + (2*r + (q&1) > b)
5705
5706def _ilog(x, M, L = 8):
5707 """Integer approximation to M*log(x/M), with absolute error boundable
5708 in terms only of x/M.
5709
5710 Given positive integers x and M, return an integer approximation to
5711 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5712 between the approximation and the exact result is at most 22. For
5713 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5714 both cases these are upper bounds on the error; it will usually be
5715 much smaller."""
5716
5717 # The basic algorithm is the following: let log1p be the function
5718 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5719 # the reduction
5720 #
5721 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5722 #
5723 # repeatedly until the argument to log1p is small (< 2**-L in
5724 # absolute value). For small y we can use the Taylor series
5725 # expansion
5726 #
5727 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5728 #
5729 # truncating at T such that y**T is small enough. The whole
5730 # computation is carried out in a form of fixed-point arithmetic,
5731 # with a real number z being represented by an integer
5732 # approximation to z*M. To avoid loss of precision, the y below
5733 # is actually an integer approximation to 2**R*y*M, where R is the
5734 # number of reductions performed so far.
5735
5736 y = x-M
5737 # argument reduction; R = number of reductions performed
5738 R = 0
5739 while (R <= L and abs(y) << L-R >= M or
5740 R > L and abs(y) >> R-L >= M):
5741 y = _div_nearest((M*y) << 1,
5742 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5743 R += 1
5744
5745 # Taylor series with T terms
5746 T = -int(-10*len(str(M))//(3*L))
5747 yshift = _rshift_nearest(y, R)
5748 w = _div_nearest(M, T)
5749 for k in range(T-1, 0, -1):
5750 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5751
5752 return _div_nearest(w*y, M)
5753
5754def _dlog10(c, e, p):
5755 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5756 approximation to 10**p * log10(c*10**e), with an absolute error of
5757 at most 1. Assumes that c*10**e is not exactly 1."""
5758
5759 # increase precision by 2; compensate for this by dividing
5760 # final result by 100
5761 p += 2
5762
5763 # write c*10**e as d*10**f with either:
5764 # f >= 0 and 1 <= d <= 10, or
5765 # f <= 0 and 0.1 <= d <= 1.
5766 # Thus for c*10**e close to 1, f = 0
5767 l = len(str(c))
5768 f = e+l - (e+l >= 1)
5769
5770 if p > 0:
5771 M = 10**p
5772 k = e+p-f
5773 if k >= 0:
5774 c *= 10**k
5775 else:
5776 c = _div_nearest(c, 10**-k)
5777
5778 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005779 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005780 log_d = _div_nearest(log_d*M, log_10)
5781 log_tenpower = f*M # exact
5782 else:
5783 log_d = 0 # error < 2.31
Neal Norwitz2f99b242008-08-24 05:48:10 +00005784 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005785
5786 return _div_nearest(log_tenpower+log_d, 100)
5787
5788def _dlog(c, e, p):
5789 """Given integers c, e and p with c > 0, compute an integer
5790 approximation to 10**p * log(c*10**e), with an absolute error of
5791 at most 1. Assumes that c*10**e is not exactly 1."""
5792
5793 # Increase precision by 2. The precision increase is compensated
5794 # for at the end with a division by 100.
5795 p += 2
5796
5797 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5798 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5799 # as 10**p * log(d) + 10**p*f * log(10).
5800 l = len(str(c))
5801 f = e+l - (e+l >= 1)
5802
5803 # compute approximation to 10**p*log(d), with error < 27
5804 if p > 0:
5805 k = e+p-f
5806 if k >= 0:
5807 c *= 10**k
5808 else:
5809 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5810
5811 # _ilog magnifies existing error in c by a factor of at most 10
5812 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5813 else:
5814 # p <= 0: just approximate the whole thing by 0; error < 2.31
5815 log_d = 0
5816
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005817 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005818 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005819 extra = len(str(abs(f)))-1
5820 if p + extra >= 0:
5821 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5822 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5823 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005824 else:
5825 f_log_ten = 0
5826 else:
5827 f_log_ten = 0
5828
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005829 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005830 return _div_nearest(f_log_ten + log_d, 100)
5831
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005832class _Log10Memoize(object):
5833 """Class to compute, store, and allow retrieval of, digits of the
5834 constant log(10) = 2.302585.... This constant is needed by
5835 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5836 def __init__(self):
5837 self.digits = "23025850929940456840179914546843642076011014886"
5838
5839 def getdigits(self, p):
5840 """Given an integer p >= 0, return floor(10**p)*log(10).
5841
5842 For example, self.getdigits(3) returns 2302.
5843 """
5844 # digits are stored as a string, for quick conversion to
5845 # integer in the case that we've already computed enough
5846 # digits; the stored digits should always be correct
5847 # (truncated, not rounded to nearest).
5848 if p < 0:
5849 raise ValueError("p should be nonnegative")
5850
5851 if p >= len(self.digits):
5852 # compute p+3, p+6, p+9, ... digits; continue until at
5853 # least one of the extra digits is nonzero
5854 extra = 3
5855 while True:
5856 # compute p+extra digits, correct to within 1ulp
5857 M = 10**(p+extra+2)
5858 digits = str(_div_nearest(_ilog(10*M, M), 100))
5859 if digits[-extra:] != '0'*extra:
5860 break
5861 extra += 3
5862 # keep all reliable digits so far; remove trailing zeros
5863 # and next nonzero digit
5864 self.digits = digits.rstrip('0')[:-1]
5865 return int(self.digits[:p+1])
5866
5867_log10_digits = _Log10Memoize().getdigits
5868
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005869def _iexp(x, M, L=8):
5870 """Given integers x and M, M > 0, such that x/M is small in absolute
5871 value, compute an integer approximation to M*exp(x/M). For 0 <=
5872 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5873 is usually much smaller)."""
5874
5875 # Algorithm: to compute exp(z) for a real number z, first divide z
5876 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5877 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5878 # series
5879 #
5880 # expm1(x) = x + x**2/2! + x**3/3! + ...
5881 #
5882 # Now use the identity
5883 #
5884 # expm1(2x) = expm1(x)*(expm1(x)+2)
5885 #
5886 # R times to compute the sequence expm1(z/2**R),
5887 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5888
5889 # Find R such that x/2**R/M <= 2**-L
5890 R = _nbits((x<<L)//M)
5891
5892 # Taylor series. (2**L)**T > M
5893 T = -int(-10*len(str(M))//(3*L))
5894 y = _div_nearest(x, T)
5895 Mshift = M<<R
5896 for i in range(T-1, 0, -1):
5897 y = _div_nearest(x*(Mshift + y), Mshift * i)
5898
5899 # Expansion
5900 for k in range(R-1, -1, -1):
5901 Mshift = M<<(k+2)
5902 y = _div_nearest(y*(y+Mshift), Mshift)
5903
5904 return M+y
5905
5906def _dexp(c, e, p):
5907 """Compute an approximation to exp(c*10**e), with p decimal places of
5908 precision.
5909
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005910 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005911
5912 10**(p-1) <= d <= 10**p, and
5913 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5914
5915 In other words, d*10**f is an approximation to exp(c*10**e) with p
5916 digits of precision, and with an error in d of at most 1. This is
5917 almost, but not quite, the same as the error being < 1ulp: when d
5918 = 10**(p-1) the error could be up to 10 ulp."""
5919
5920 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5921 p += 2
5922
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005923 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005924 extra = max(0, e + len(str(c)) - 1)
5925 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005926
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005927 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005928 # rounding down
5929 shift = e+q
5930 if shift >= 0:
5931 cshift = c*10**shift
5932 else:
5933 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005934 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005935
5936 # reduce remainder back to original precision
5937 rem = _div_nearest(rem, 10**extra)
5938
5939 # error in result of _iexp < 120; error after division < 0.62
5940 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5941
5942def _dpower(xc, xe, yc, ye, p):
5943 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5944 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5945
5946 10**(p-1) <= c <= 10**p, and
5947 (c-1)*10**e < x**y < (c+1)*10**e
5948
5949 in other words, c*10**e is an approximation to x**y with p digits
5950 of precision, and with an error in c of at most 1. (This is
5951 almost, but not quite, the same as the error being < 1ulp: when c
5952 == 10**(p-1) we can only guarantee error < 10ulp.)
5953
5954 We assume that: x is positive and not equal to 1, and y is nonzero.
5955 """
5956
5957 # Find b such that 10**(b-1) <= |y| <= 10**b
5958 b = len(str(abs(yc))) + ye
5959
5960 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5961 lxc = _dlog(xc, xe, p+b+1)
5962
5963 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5964 shift = ye-b
5965 if shift >= 0:
5966 pc = lxc*yc*10**shift
5967 else:
5968 pc = _div_nearest(lxc*yc, 10**-shift)
5969
5970 if pc == 0:
5971 # we prefer a result that isn't exactly 1; this makes it
5972 # easier to compute a correctly rounded result in __pow__
5973 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5974 coeff, exp = 10**(p-1)+1, 1-p
5975 else:
5976 coeff, exp = 10**p-1, -p
5977 else:
5978 coeff, exp = _dexp(pc, -(p+1), p+1)
5979 coeff = _div_nearest(coeff, 10)
5980 exp += 1
5981
5982 return coeff, exp
5983
5984def _log10_lb(c, correction = {
5985 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5986 '6': 23, '7': 16, '8': 10, '9': 5}):
5987 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5988 if c <= 0:
5989 raise ValueError("The argument to _log10_lb should be nonnegative.")
5990 str_c = str(c)
5991 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005992
Guido van Rossumd8faa362007-04-27 19:54:29 +00005993##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005994
Mark Dickinsonac256ab2010-04-03 11:08:14 +00005995def _convert_other(other, raiseit=False, allow_float=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005996 """Convert other to Decimal.
5997
5998 Verifies that it's ok to use in an implicit construction.
Mark Dickinsonac256ab2010-04-03 11:08:14 +00005999 If allow_float is true, allow conversion from float; this
6000 is used in the comparison methods (__eq__ and friends).
6001
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006002 """
6003 if isinstance(other, Decimal):
6004 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00006005 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006006 return Decimal(other)
Mark Dickinsonac256ab2010-04-03 11:08:14 +00006007 if allow_float and isinstance(other, float):
6008 return Decimal.from_float(other)
6009
Thomas Wouters1b7f8912007-09-19 03:06:30 +00006010 if raiseit:
6011 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00006012 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006013
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006014def _convert_for_comparison(self, other, equality_op=False):
6015 """Given a Decimal instance self and a Python object other, return
Mark Dickinson1c164a62010-06-11 16:49:20 +00006016 a pair (s, o) of Decimal instances such that "s op o" is
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006017 equivalent to "self op other" for any of the 6 comparison
6018 operators "op".
6019
6020 """
6021 if isinstance(other, Decimal):
6022 return self, other
6023
6024 # Comparison with a Rational instance (also includes integers):
6025 # self op n/d <=> self*d op n (for n and d integers, d positive).
6026 # A NaN or infinity can be left unchanged without affecting the
6027 # comparison result.
6028 if isinstance(other, _numbers.Rational):
6029 if not self._is_special:
6030 self = _dec_from_triple(self._sign,
6031 str(int(self._int) * other.denominator),
6032 self._exp)
6033 return self, Decimal(other.numerator)
6034
6035 # Comparisons with float and complex types. == and != comparisons
6036 # with complex numbers should succeed, returning either True or False
6037 # as appropriate. Other comparisons return NotImplemented.
6038 if equality_op and isinstance(other, _numbers.Complex) and other.imag == 0:
6039 other = other.real
6040 if isinstance(other, float):
Stefan Krah1919b7e2012-03-21 18:25:23 +01006041 context = getcontext()
6042 if equality_op:
6043 context.flags[FloatOperation] = 1
6044 else:
6045 context._raise_error(FloatOperation,
6046 "strict semantics for mixing floats and Decimals are enabled")
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006047 return self, Decimal.from_float(other)
6048 return NotImplemented, NotImplemented
6049
6050
Guido van Rossumd8faa362007-04-27 19:54:29 +00006051##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006052
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006053# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00006054# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006055
6056DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00006057 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006058 traps=[DivisionByZero, Overflow, InvalidOperation],
6059 flags=[],
Stefan Krah1919b7e2012-03-21 18:25:23 +01006060 Emax=999999,
6061 Emin=-999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00006062 capitals=1,
6063 clamp=0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006064)
6065
6066# Pre-made alternate contexts offered by the specification
6067# Don't change these; the user should be able to select these
6068# contexts and be able to reproduce results from other implementations
6069# of the spec.
6070
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00006071BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006072 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006073 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
6074 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006075)
6076
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00006077ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00006078 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006079 traps=[],
6080 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006081)
6082
6083
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006084##### crud for parsing strings #############################################
Christian Heimes23daade02008-02-25 12:39:23 +00006085#
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006086# Regular expression used for parsing numeric strings. Additional
6087# comments:
6088#
6089# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
6090# whitespace. But note that the specification disallows whitespace in
6091# a numeric string.
6092#
6093# 2. For finite numbers (not infinities and NaNs) the body of the
6094# number between the optional sign and the optional exponent must have
6095# at least one decimal digit, possibly after the decimal point. The
Mark Dickinson345adc42009-08-02 10:14:23 +00006096# lookahead expression '(?=\d|\.\d)' checks this.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006097
6098import re
Benjamin Peterson41181742008-07-02 20:22:54 +00006099_parser = re.compile(r""" # A numeric string consists of:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006100# \s*
Benjamin Peterson41181742008-07-02 20:22:54 +00006101 (?P<sign>[-+])? # an optional sign, followed by either...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006102 (
Mark Dickinson345adc42009-08-02 10:14:23 +00006103 (?=\d|\.\d) # ...a number (with at least one digit)
6104 (?P<int>\d*) # having a (possibly empty) integer part
6105 (\.(?P<frac>\d*))? # followed by an optional fractional part
6106 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006107 |
Benjamin Peterson41181742008-07-02 20:22:54 +00006108 Inf(inity)? # ...an infinity, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006109 |
Benjamin Peterson41181742008-07-02 20:22:54 +00006110 (?P<signal>s)? # ...an (optionally signaling)
6111 NaN # NaN
Mark Dickinson345adc42009-08-02 10:14:23 +00006112 (?P<diag>\d*) # with (possibly empty) diagnostic info.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006113 )
6114# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00006115 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006116""", re.VERBOSE | re.IGNORECASE).match
6117
Christian Heimescbf3b5c2007-12-03 21:02:03 +00006118_all_zeros = re.compile('0*$').match
6119_exact_half = re.compile('50*$').match
Christian Heimesf16baeb2008-02-29 14:57:44 +00006120
6121##### PEP3101 support functions ##############################################
Mark Dickinson79f52032009-03-17 23:12:51 +00006122# The functions in this section have little to do with the Decimal
6123# class, and could potentially be reused or adapted for other pure
Christian Heimesf16baeb2008-02-29 14:57:44 +00006124# Python numeric classes that want to implement __format__
6125#
6126# A format specifier for Decimal looks like:
6127#
Eric Smith984bb582010-11-25 16:08:06 +00006128# [[fill]align][sign][#][0][minimumwidth][,][.precision][type]
Christian Heimesf16baeb2008-02-29 14:57:44 +00006129
6130_parse_format_specifier_regex = re.compile(r"""\A
6131(?:
6132 (?P<fill>.)?
6133 (?P<align>[<>=^])
6134)?
6135(?P<sign>[-+ ])?
Eric Smith984bb582010-11-25 16:08:06 +00006136(?P<alt>\#)?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006137(?P<zeropad>0)?
6138(?P<minimumwidth>(?!0)\d+)?
Mark Dickinson79f52032009-03-17 23:12:51 +00006139(?P<thousands_sep>,)?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006140(?:\.(?P<precision>0|(?!0)\d+))?
Mark Dickinson79f52032009-03-17 23:12:51 +00006141(?P<type>[eEfFgGn%])?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006142\Z
6143""", re.VERBOSE)
6144
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006145del re
6146
Mark Dickinson79f52032009-03-17 23:12:51 +00006147# The locale module is only needed for the 'n' format specifier. The
6148# rest of the PEP 3101 code functions quite happily without it, so we
6149# don't care too much if locale isn't present.
6150try:
6151 import locale as _locale
6152except ImportError:
6153 pass
6154
6155def _parse_format_specifier(format_spec, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00006156 """Parse and validate a format specifier.
6157
6158 Turns a standard numeric format specifier into a dict, with the
6159 following entries:
6160
6161 fill: fill character to pad field to minimum width
6162 align: alignment type, either '<', '>', '=' or '^'
6163 sign: either '+', '-' or ' '
6164 minimumwidth: nonnegative integer giving minimum width
Mark Dickinson79f52032009-03-17 23:12:51 +00006165 zeropad: boolean, indicating whether to pad with zeros
6166 thousands_sep: string to use as thousands separator, or ''
6167 grouping: grouping for thousands separators, in format
6168 used by localeconv
6169 decimal_point: string to use for decimal point
Christian Heimesf16baeb2008-02-29 14:57:44 +00006170 precision: nonnegative integer giving precision, or None
6171 type: one of the characters 'eEfFgG%', or None
Christian Heimesf16baeb2008-02-29 14:57:44 +00006172
6173 """
6174 m = _parse_format_specifier_regex.match(format_spec)
6175 if m is None:
6176 raise ValueError("Invalid format specifier: " + format_spec)
6177
6178 # get the dictionary
6179 format_dict = m.groupdict()
6180
Mark Dickinson79f52032009-03-17 23:12:51 +00006181 # zeropad; defaults for fill and alignment. If zero padding
6182 # is requested, the fill and align fields should be absent.
Christian Heimesf16baeb2008-02-29 14:57:44 +00006183 fill = format_dict['fill']
6184 align = format_dict['align']
Mark Dickinson79f52032009-03-17 23:12:51 +00006185 format_dict['zeropad'] = (format_dict['zeropad'] is not None)
6186 if format_dict['zeropad']:
6187 if fill is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00006188 raise ValueError("Fill character conflicts with '0'"
6189 " in format specifier: " + format_spec)
Mark Dickinson79f52032009-03-17 23:12:51 +00006190 if align is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00006191 raise ValueError("Alignment conflicts with '0' in "
6192 "format specifier: " + format_spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00006193 format_dict['fill'] = fill or ' '
Mark Dickinson46ab5d02009-09-08 20:22:46 +00006194 # PEP 3101 originally specified that the default alignment should
6195 # be left; it was later agreed that right-aligned makes more sense
6196 # for numeric types. See http://bugs.python.org/issue6857.
6197 format_dict['align'] = align or '>'
Christian Heimesf16baeb2008-02-29 14:57:44 +00006198
Mark Dickinson79f52032009-03-17 23:12:51 +00006199 # default sign handling: '-' for negative, '' for positive
Christian Heimesf16baeb2008-02-29 14:57:44 +00006200 if format_dict['sign'] is None:
6201 format_dict['sign'] = '-'
6202
Christian Heimesf16baeb2008-02-29 14:57:44 +00006203 # minimumwidth defaults to 0; precision remains None if not given
6204 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
6205 if format_dict['precision'] is not None:
6206 format_dict['precision'] = int(format_dict['precision'])
6207
6208 # if format type is 'g' or 'G' then a precision of 0 makes little
6209 # sense; convert it to 1. Same if format type is unspecified.
6210 if format_dict['precision'] == 0:
Stefan Krah1919b7e2012-03-21 18:25:23 +01006211 if format_dict['type'] is None or format_dict['type'] in 'gGn':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006212 format_dict['precision'] = 1
6213
Mark Dickinson79f52032009-03-17 23:12:51 +00006214 # determine thousands separator, grouping, and decimal separator, and
6215 # add appropriate entries to format_dict
6216 if format_dict['type'] == 'n':
6217 # apart from separators, 'n' behaves just like 'g'
6218 format_dict['type'] = 'g'
6219 if _localeconv is None:
6220 _localeconv = _locale.localeconv()
6221 if format_dict['thousands_sep'] is not None:
6222 raise ValueError("Explicit thousands separator conflicts with "
6223 "'n' type in format specifier: " + format_spec)
6224 format_dict['thousands_sep'] = _localeconv['thousands_sep']
6225 format_dict['grouping'] = _localeconv['grouping']
6226 format_dict['decimal_point'] = _localeconv['decimal_point']
6227 else:
6228 if format_dict['thousands_sep'] is None:
6229 format_dict['thousands_sep'] = ''
6230 format_dict['grouping'] = [3, 0]
6231 format_dict['decimal_point'] = '.'
Christian Heimesf16baeb2008-02-29 14:57:44 +00006232
6233 return format_dict
6234
Mark Dickinson79f52032009-03-17 23:12:51 +00006235def _format_align(sign, body, spec):
6236 """Given an unpadded, non-aligned numeric string 'body' and sign
Ezio Melotti42da6632011-03-15 05:18:48 +02006237 string 'sign', add padding and alignment conforming to the given
Mark Dickinson79f52032009-03-17 23:12:51 +00006238 format specifier dictionary 'spec' (as produced by
6239 parse_format_specifier).
Christian Heimesf16baeb2008-02-29 14:57:44 +00006240
6241 """
Christian Heimesf16baeb2008-02-29 14:57:44 +00006242 # how much extra space do we have to play with?
Mark Dickinson79f52032009-03-17 23:12:51 +00006243 minimumwidth = spec['minimumwidth']
6244 fill = spec['fill']
6245 padding = fill*(minimumwidth - len(sign) - len(body))
Christian Heimesf16baeb2008-02-29 14:57:44 +00006246
Mark Dickinson79f52032009-03-17 23:12:51 +00006247 align = spec['align']
Christian Heimesf16baeb2008-02-29 14:57:44 +00006248 if align == '<':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006249 result = sign + body + padding
Mark Dickinsonad416342009-03-17 18:10:15 +00006250 elif align == '>':
6251 result = padding + sign + body
Christian Heimesf16baeb2008-02-29 14:57:44 +00006252 elif align == '=':
6253 result = sign + padding + body
Mark Dickinson79f52032009-03-17 23:12:51 +00006254 elif align == '^':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006255 half = len(padding)//2
6256 result = padding[:half] + sign + body + padding[half:]
Mark Dickinson79f52032009-03-17 23:12:51 +00006257 else:
6258 raise ValueError('Unrecognised alignment field')
Christian Heimesf16baeb2008-02-29 14:57:44 +00006259
Christian Heimesf16baeb2008-02-29 14:57:44 +00006260 return result
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006261
Mark Dickinson79f52032009-03-17 23:12:51 +00006262def _group_lengths(grouping):
6263 """Convert a localeconv-style grouping into a (possibly infinite)
6264 iterable of integers representing group lengths.
6265
6266 """
6267 # The result from localeconv()['grouping'], and the input to this
6268 # function, should be a list of integers in one of the
6269 # following three forms:
6270 #
6271 # (1) an empty list, or
6272 # (2) nonempty list of positive integers + [0]
6273 # (3) list of positive integers + [locale.CHAR_MAX], or
6274
6275 from itertools import chain, repeat
6276 if not grouping:
6277 return []
6278 elif grouping[-1] == 0 and len(grouping) >= 2:
6279 return chain(grouping[:-1], repeat(grouping[-2]))
6280 elif grouping[-1] == _locale.CHAR_MAX:
6281 return grouping[:-1]
6282 else:
6283 raise ValueError('unrecognised format for grouping')
6284
6285def _insert_thousands_sep(digits, spec, min_width=1):
6286 """Insert thousands separators into a digit string.
6287
6288 spec is a dictionary whose keys should include 'thousands_sep' and
6289 'grouping'; typically it's the result of parsing the format
6290 specifier using _parse_format_specifier.
6291
6292 The min_width keyword argument gives the minimum length of the
6293 result, which will be padded on the left with zeros if necessary.
6294
6295 If necessary, the zero padding adds an extra '0' on the left to
6296 avoid a leading thousands separator. For example, inserting
6297 commas every three digits in '123456', with min_width=8, gives
6298 '0,123,456', even though that has length 9.
6299
6300 """
6301
6302 sep = spec['thousands_sep']
6303 grouping = spec['grouping']
6304
6305 groups = []
6306 for l in _group_lengths(grouping):
Mark Dickinson79f52032009-03-17 23:12:51 +00006307 if l <= 0:
6308 raise ValueError("group length should be positive")
6309 # max(..., 1) forces at least 1 digit to the left of a separator
6310 l = min(max(len(digits), min_width, 1), l)
6311 groups.append('0'*(l - len(digits)) + digits[-l:])
6312 digits = digits[:-l]
6313 min_width -= l
6314 if not digits and min_width <= 0:
6315 break
Mark Dickinson7303b592009-03-18 08:25:36 +00006316 min_width -= len(sep)
Mark Dickinson79f52032009-03-17 23:12:51 +00006317 else:
6318 l = max(len(digits), min_width, 1)
6319 groups.append('0'*(l - len(digits)) + digits[-l:])
6320 return sep.join(reversed(groups))
6321
6322def _format_sign(is_negative, spec):
6323 """Determine sign character."""
6324
6325 if is_negative:
6326 return '-'
6327 elif spec['sign'] in ' +':
6328 return spec['sign']
6329 else:
6330 return ''
6331
6332def _format_number(is_negative, intpart, fracpart, exp, spec):
6333 """Format a number, given the following data:
6334
6335 is_negative: true if the number is negative, else false
6336 intpart: string of digits that must appear before the decimal point
6337 fracpart: string of digits that must come after the point
6338 exp: exponent, as an integer
6339 spec: dictionary resulting from parsing the format specifier
6340
6341 This function uses the information in spec to:
6342 insert separators (decimal separator and thousands separators)
6343 format the sign
6344 format the exponent
6345 add trailing '%' for the '%' type
6346 zero-pad if necessary
6347 fill and align if necessary
6348 """
6349
6350 sign = _format_sign(is_negative, spec)
6351
Eric Smith984bb582010-11-25 16:08:06 +00006352 if fracpart or spec['alt']:
Mark Dickinson79f52032009-03-17 23:12:51 +00006353 fracpart = spec['decimal_point'] + fracpart
6354
6355 if exp != 0 or spec['type'] in 'eE':
6356 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
6357 fracpart += "{0}{1:+}".format(echar, exp)
6358 if spec['type'] == '%':
6359 fracpart += '%'
6360
6361 if spec['zeropad']:
6362 min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
6363 else:
6364 min_width = 0
6365 intpart = _insert_thousands_sep(intpart, spec, min_width)
6366
6367 return _format_align(sign, intpart+fracpart, spec)
6368
6369
Guido van Rossumd8faa362007-04-27 19:54:29 +00006370##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006371
Guido van Rossumd8faa362007-04-27 19:54:29 +00006372# Reusable defaults
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006373_Infinity = Decimal('Inf')
6374_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonf9236412009-01-02 23:23:21 +00006375_NaN = Decimal('NaN')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006376_Zero = Decimal(0)
6377_One = Decimal(1)
6378_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006379
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006380# _SignedInfinity[sign] is infinity w/ that sign
6381_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006382
Mark Dickinsondc787d22010-05-23 13:33:13 +00006383# Constants related to the hash implementation; hash(x) is based
6384# on the reduction of x modulo _PyHASH_MODULUS
Mark Dickinsondc787d22010-05-23 13:33:13 +00006385_PyHASH_MODULUS = sys.hash_info.modulus
6386# hash values to use for positive and negative infinities, and nans
6387_PyHASH_INF = sys.hash_info.inf
6388_PyHASH_NAN = sys.hash_info.nan
Mark Dickinsondc787d22010-05-23 13:33:13 +00006389
6390# _PyHASH_10INV is the inverse of 10 modulo the prime _PyHASH_MODULUS
6391_PyHASH_10INV = pow(10, _PyHASH_MODULUS - 2, _PyHASH_MODULUS)
Stefan Krah1919b7e2012-03-21 18:25:23 +01006392del sys
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006393
Stefan Krah1919b7e2012-03-21 18:25:23 +01006394try:
6395 import _decimal
6396except ImportError:
6397 pass
6398else:
6399 s1 = set(dir())
6400 s2 = set(dir(_decimal))
6401 for name in s1 - s2:
6402 del globals()[name]
6403 del s1, s2, name
6404 from _decimal import *
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006405
6406if __name__ == '__main__':
Raymond Hettinger6d7e26e2011-02-01 23:54:43 +00006407 import doctest, decimal
6408 doctest.testmod(decimal)