blob: 25f8fbc13303bd6c600ad41ad1cf43a729c61d29 [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 Dickinson9c3f5032012-10-31 17:53:27 +0000706 @classmethod
Raymond Hettinger771ed762009-01-03 19:20:32 +0000707 def from_float(cls, f):
708 """Converts a float to a decimal number, exactly.
709
710 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
711 Since 0.1 is not exactly representable in binary floating point, the
712 value is stored as the nearest representable value which is
713 0x1.999999999999ap-4. The exact equivalent of the value in decimal
714 is 0.1000000000000000055511151231257827021181583404541015625.
715
716 >>> Decimal.from_float(0.1)
717 Decimal('0.1000000000000000055511151231257827021181583404541015625')
718 >>> Decimal.from_float(float('nan'))
719 Decimal('NaN')
720 >>> Decimal.from_float(float('inf'))
721 Decimal('Infinity')
722 >>> Decimal.from_float(-float('inf'))
723 Decimal('-Infinity')
724 >>> Decimal.from_float(-0.0)
725 Decimal('-0')
726
727 """
728 if isinstance(f, int): # handle integer inputs
729 return cls(f)
Stefan Krah1919b7e2012-03-21 18:25:23 +0100730 if not isinstance(f, float):
731 raise TypeError("argument must be int or float.")
732 if _math.isinf(f) or _math.isnan(f):
Raymond Hettinger771ed762009-01-03 19:20:32 +0000733 return cls(repr(f))
Mark Dickinsonba298e42009-01-04 21:17:43 +0000734 if _math.copysign(1.0, f) == 1.0:
735 sign = 0
736 else:
737 sign = 1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000738 n, d = abs(f).as_integer_ratio()
739 k = d.bit_length() - 1
740 result = _dec_from_triple(sign, str(n*5**k), -k)
Mark Dickinsonba298e42009-01-04 21:17:43 +0000741 if cls is Decimal:
742 return result
743 else:
744 return cls(result)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000745
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000746 def _isnan(self):
747 """Returns whether the number is not actually one.
748
749 0 if a number
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000750 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000751 2 if sNaN
752 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000753 if self._is_special:
754 exp = self._exp
755 if exp == 'n':
756 return 1
757 elif exp == 'N':
758 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000759 return 0
760
761 def _isinfinity(self):
762 """Returns whether the number is infinite
763
764 0 if finite or not a number
765 1 if +INF
766 -1 if -INF
767 """
768 if self._exp == 'F':
769 if self._sign:
770 return -1
771 return 1
772 return 0
773
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000774 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000775 """Returns whether the number is not actually one.
776
777 if self, other are sNaN, signal
778 if self, other are NaN return nan
779 return 0
780
781 Done before operations.
782 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000783
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000784 self_is_nan = self._isnan()
785 if other is None:
786 other_is_nan = False
787 else:
788 other_is_nan = other._isnan()
789
790 if self_is_nan or other_is_nan:
791 if context is None:
792 context = getcontext()
793
794 if self_is_nan == 2:
795 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000796 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000797 if other_is_nan == 2:
798 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000799 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000800 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000801 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000802
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000803 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000804 return 0
805
Christian Heimes77c02eb2008-02-09 02:18:51 +0000806 def _compare_check_nans(self, other, context):
807 """Version of _check_nans used for the signaling comparisons
808 compare_signal, __le__, __lt__, __ge__, __gt__.
809
810 Signal InvalidOperation if either self or other is a (quiet
811 or signaling) NaN. Signaling NaNs take precedence over quiet
812 NaNs.
813
814 Return 0 if neither operand is a NaN.
815
816 """
817 if context is None:
818 context = getcontext()
819
820 if self._is_special or other._is_special:
821 if self.is_snan():
822 return context._raise_error(InvalidOperation,
823 'comparison involving sNaN',
824 self)
825 elif other.is_snan():
826 return context._raise_error(InvalidOperation,
827 'comparison involving sNaN',
828 other)
829 elif self.is_qnan():
830 return context._raise_error(InvalidOperation,
831 'comparison involving NaN',
832 self)
833 elif other.is_qnan():
834 return context._raise_error(InvalidOperation,
835 'comparison involving NaN',
836 other)
837 return 0
838
Jack Diederich4dafcc42006-11-28 19:15:13 +0000839 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000840 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000841
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000842 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000843 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000844 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000845
Christian Heimes77c02eb2008-02-09 02:18:51 +0000846 def _cmp(self, other):
847 """Compare the two non-NaN decimal instances self and other.
848
849 Returns -1 if self < other, 0 if self == other and 1
850 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000851
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000852 if self._is_special or other._is_special:
Mark Dickinsone6aad752009-01-25 10:48:51 +0000853 self_inf = self._isinfinity()
854 other_inf = other._isinfinity()
855 if self_inf == other_inf:
856 return 0
857 elif self_inf < other_inf:
858 return -1
859 else:
860 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000861
Mark Dickinsone6aad752009-01-25 10:48:51 +0000862 # check for zeros; Decimal('0') == Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000863 if not self:
864 if not other:
865 return 0
866 else:
867 return -((-1)**other._sign)
868 if not other:
869 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000870
Guido van Rossumd8faa362007-04-27 19:54:29 +0000871 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000872 if other._sign < self._sign:
873 return -1
874 if self._sign < other._sign:
875 return 1
876
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000877 self_adjusted = self.adjusted()
878 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000879 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000880 self_padded = self._int + '0'*(self._exp - other._exp)
881 other_padded = other._int + '0'*(other._exp - self._exp)
Mark Dickinsone6aad752009-01-25 10:48:51 +0000882 if self_padded == other_padded:
883 return 0
884 elif self_padded < other_padded:
885 return -(-1)**self._sign
886 else:
887 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000888 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000889 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000891 return -((-1)**self._sign)
892
Christian Heimes77c02eb2008-02-09 02:18:51 +0000893 # Note: The Decimal standard doesn't cover rich comparisons for
894 # Decimals. In particular, the specification is silent on the
895 # subject of what should happen for a comparison involving a NaN.
896 # We take the following approach:
897 #
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000898 # == comparisons involving a quiet NaN always return False
899 # != comparisons involving a quiet NaN always return True
900 # == or != comparisons involving a signaling NaN signal
901 # InvalidOperation, and return False or True as above if the
902 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000903 # <, >, <= and >= comparisons involving a (quiet or signaling)
904 # NaN signal InvalidOperation, and return False if the
Christian Heimes3feef612008-02-11 06:19:17 +0000905 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000906 #
907 # This behavior is designed to conform as closely as possible to
908 # that specified by IEEE 754.
909
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000910 def __eq__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000911 self, other = _convert_for_comparison(self, other, equality_op=True)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000912 if other is NotImplemented:
913 return other
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000914 if self._check_nans(other, context):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000915 return False
916 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000917
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000918 def __ne__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000919 self, other = _convert_for_comparison(self, other, equality_op=True)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000920 if other is NotImplemented:
921 return other
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000922 if self._check_nans(other, context):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000923 return True
924 return self._cmp(other) != 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000925
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000926
Christian Heimes77c02eb2008-02-09 02:18:51 +0000927 def __lt__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000928 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000929 if other is NotImplemented:
930 return other
931 ans = self._compare_check_nans(other, context)
932 if ans:
933 return False
934 return self._cmp(other) < 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000935
Christian Heimes77c02eb2008-02-09 02:18:51 +0000936 def __le__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000937 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000938 if other is NotImplemented:
939 return other
940 ans = self._compare_check_nans(other, context)
941 if ans:
942 return False
943 return self._cmp(other) <= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000944
Christian Heimes77c02eb2008-02-09 02:18:51 +0000945 def __gt__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000946 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000947 if other is NotImplemented:
948 return other
949 ans = self._compare_check_nans(other, context)
950 if ans:
951 return False
952 return self._cmp(other) > 0
953
954 def __ge__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000955 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000956 if other is NotImplemented:
957 return other
958 ans = self._compare_check_nans(other, context)
959 if ans:
960 return False
961 return self._cmp(other) >= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000962
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000963 def compare(self, other, context=None):
964 """Compares one to another.
965
966 -1 => a < b
967 0 => a = b
968 1 => a > b
969 NaN => one is NaN
970 Like __cmp__, but returns Decimal instances.
971 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000972 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000973
Guido van Rossumd8faa362007-04-27 19:54:29 +0000974 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000975 if (self._is_special or other and other._is_special):
976 ans = self._check_nans(other, context)
977 if ans:
978 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000979
Christian Heimes77c02eb2008-02-09 02:18:51 +0000980 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000981
982 def __hash__(self):
983 """x.__hash__() <==> hash(x)"""
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000984
Mark Dickinsondc787d22010-05-23 13:33:13 +0000985 # In order to make sure that the hash of a Decimal instance
986 # agrees with the hash of a numerically equal integer, float
987 # or Fraction, we follow the rules for numeric hashes outlined
988 # in the documentation. (See library docs, 'Built-in Types').
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000989 if self._is_special:
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000990 if self.is_snan():
Raymond Hettingerd325c4b2010-11-21 04:08:28 +0000991 raise TypeError('Cannot hash a signaling NaN value.')
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000992 elif self.is_nan():
Mark Dickinsondc787d22010-05-23 13:33:13 +0000993 return _PyHASH_NAN
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000994 else:
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000995 if self._sign:
Mark Dickinsondc787d22010-05-23 13:33:13 +0000996 return -_PyHASH_INF
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000997 else:
Mark Dickinsondc787d22010-05-23 13:33:13 +0000998 return _PyHASH_INF
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000999
Mark Dickinsondc787d22010-05-23 13:33:13 +00001000 if self._exp >= 0:
1001 exp_hash = pow(10, self._exp, _PyHASH_MODULUS)
1002 else:
1003 exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS)
1004 hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS
Stefan Krahdc817b22010-11-17 11:16:34 +00001005 ans = hash_ if self >= 0 else -hash_
1006 return -2 if ans == -1 else ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001007
1008 def as_tuple(self):
1009 """Represents the number as a triple tuple.
1010
1011 To show the internals exactly as they are.
1012 """
Christian Heimes25bb7832008-01-11 16:17:00 +00001013 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001014
1015 def __repr__(self):
1016 """Represents the number as an instance of Decimal."""
1017 # Invariant: eval(repr(d)) == d
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001018 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001019
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001020 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001021 """Return string representation of the number in scientific notation.
1022
1023 Captures all of the information in the underlying representation.
1024 """
1025
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001026 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +00001027 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001028 if self._exp == 'F':
1029 return sign + 'Infinity'
1030 elif self._exp == 'n':
1031 return sign + 'NaN' + self._int
1032 else: # self._exp == 'N'
1033 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001034
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001035 # number of digits of self._int to left of decimal point
1036 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001037
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001038 # dotplace is number of digits of self._int to the left of the
1039 # decimal point in the mantissa of the output string (that is,
1040 # after adjusting the exponent)
1041 if self._exp <= 0 and leftdigits > -6:
1042 # no exponent required
1043 dotplace = leftdigits
1044 elif not eng:
1045 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001046 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001047 elif self._int == '0':
1048 # engineering notation, zero
1049 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001050 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001051 # engineering notation, nonzero
1052 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001053
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001054 if dotplace <= 0:
1055 intpart = '0'
1056 fracpart = '.' + '0'*(-dotplace) + self._int
1057 elif dotplace >= len(self._int):
1058 intpart = self._int+'0'*(dotplace-len(self._int))
1059 fracpart = ''
1060 else:
1061 intpart = self._int[:dotplace]
1062 fracpart = '.' + self._int[dotplace:]
1063 if leftdigits == dotplace:
1064 exp = ''
1065 else:
1066 if context is None:
1067 context = getcontext()
1068 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1069
1070 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001071
1072 def to_eng_string(self, context=None):
1073 """Convert to engineering-type string.
1074
1075 Engineering notation has an exponent which is a multiple of 3, so there
1076 are up to 3 digits left of the decimal place.
1077
1078 Same rules for when in exponential and when as a value as in __str__.
1079 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001080 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081
1082 def __neg__(self, context=None):
1083 """Returns a copy with the sign switched.
1084
1085 Rounds, if it has reason.
1086 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001087 if self._is_special:
1088 ans = self._check_nans(context=context)
1089 if ans:
1090 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001091
Mark Dickinson37a79fb2011-03-12 11:12:52 +00001092 if context is None:
1093 context = getcontext()
1094
1095 if not self and context.rounding != ROUND_FLOOR:
1096 # -Decimal('0') is Decimal('0'), not Decimal('-0'), except
1097 # in ROUND_FLOOR rounding mode.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001098 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001099 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001100 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001101
Christian Heimes2c181612007-12-17 20:04:13 +00001102 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001103
1104 def __pos__(self, context=None):
1105 """Returns a copy, unless it is a sNaN.
1106
1107 Rounds the number (if more then precision digits)
1108 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001109 if self._is_special:
1110 ans = self._check_nans(context=context)
1111 if ans:
1112 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001113
Mark Dickinson37a79fb2011-03-12 11:12:52 +00001114 if context is None:
1115 context = getcontext()
1116
1117 if not self and context.rounding != ROUND_FLOOR:
1118 # + (-0) = 0, except in ROUND_FLOOR rounding mode.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001119 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001120 else:
1121 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001122
Christian Heimes2c181612007-12-17 20:04:13 +00001123 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001124
Christian Heimes2c181612007-12-17 20:04:13 +00001125 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001126 """Returns the absolute value of self.
1127
Christian Heimes2c181612007-12-17 20:04:13 +00001128 If the keyword argument 'round' is false, do not round. The
1129 expression self.__abs__(round=False) is equivalent to
1130 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001131 """
Christian Heimes2c181612007-12-17 20:04:13 +00001132 if not round:
1133 return self.copy_abs()
1134
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001135 if self._is_special:
1136 ans = self._check_nans(context=context)
1137 if ans:
1138 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001139
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001140 if self._sign:
1141 ans = self.__neg__(context=context)
1142 else:
1143 ans = self.__pos__(context=context)
1144
1145 return ans
1146
1147 def __add__(self, other, context=None):
1148 """Returns self + other.
1149
1150 -INF + INF (or the reverse) cause InvalidOperation errors.
1151 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001152 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001153 if other is NotImplemented:
1154 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001155
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001156 if context is None:
1157 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001158
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001159 if self._is_special or other._is_special:
1160 ans = self._check_nans(other, context)
1161 if ans:
1162 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001163
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001164 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001165 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001166 if self._sign != other._sign and other._isinfinity():
1167 return context._raise_error(InvalidOperation, '-INF + INF')
1168 return Decimal(self)
1169 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001170 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001171
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001172 exp = min(self._exp, other._exp)
1173 negativezero = 0
1174 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001175 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001176 negativezero = 1
1177
1178 if not self and not other:
1179 sign = min(self._sign, other._sign)
1180 if negativezero:
1181 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001182 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001183 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001184 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001185 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001186 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001187 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001188 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001189 return ans
1190 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001191 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001192 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001193 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001194 return ans
1195
1196 op1 = _WorkRep(self)
1197 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001198 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001199
1200 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001201 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001202 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001203 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001204 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001205 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001206 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001207 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001208 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001209 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001210 if op1.sign == 1:
1211 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001212 op1.sign, op2.sign = op2.sign, op1.sign
1213 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001214 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001215 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001216 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001217 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001218 op1.sign, op2.sign = (0, 0)
1219 else:
1220 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001221 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001222
Raymond Hettinger17931de2004-10-27 06:21:46 +00001223 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001224 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001225 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001226 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001227
1228 result.exp = op1.exp
1229 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001230 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001231 return ans
1232
1233 __radd__ = __add__
1234
1235 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001236 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001237 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001238 if other is NotImplemented:
1239 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001240
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001241 if self._is_special or other._is_special:
1242 ans = self._check_nans(other, context=context)
1243 if ans:
1244 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001245
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001246 # self - other is computed as self + other.copy_negate()
1247 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001248
1249 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001250 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001251 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001252 if other is NotImplemented:
1253 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001254
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001255 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001256
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001257 def __mul__(self, other, context=None):
1258 """Return self * other.
1259
1260 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1261 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001262 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001263 if other is NotImplemented:
1264 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001265
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001266 if context is None:
1267 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001268
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001269 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001270
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001271 if self._is_special or other._is_special:
1272 ans = self._check_nans(other, context)
1273 if ans:
1274 return ans
1275
1276 if self._isinfinity():
1277 if not other:
1278 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001279 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001280
1281 if other._isinfinity():
1282 if not self:
1283 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001284 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001285
1286 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001287
1288 # Special case for multiplying by zero
1289 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001290 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001291 # Fixing in case the exponent is out of bounds
1292 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001293 return ans
1294
1295 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001296 if self._int == '1':
1297 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001298 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001299 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001300 if other._int == '1':
1301 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001302 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001303 return ans
1304
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001305 op1 = _WorkRep(self)
1306 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001307
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001308 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001309 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001310
1311 return ans
1312 __rmul__ = __mul__
1313
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001314 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001315 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001316 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001317 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001318 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001319
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001320 if context is None:
1321 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001322
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001323 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001324
1325 if self._is_special or other._is_special:
1326 ans = self._check_nans(other, context)
1327 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001328 return ans
1329
1330 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001331 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001332
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001333 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001334 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001335
1336 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001337 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001338 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001339
1340 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001341 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001342 if not self:
1343 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001344 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001345
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001346 if not self:
1347 exp = self._exp - other._exp
1348 coeff = 0
1349 else:
1350 # OK, so neither = 0, INF or NaN
1351 shift = len(other._int) - len(self._int) + context.prec + 1
1352 exp = self._exp - other._exp - shift
1353 op1 = _WorkRep(self)
1354 op2 = _WorkRep(other)
1355 if shift >= 0:
1356 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1357 else:
1358 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1359 if remainder:
1360 # result is not exact; adjust to ensure correct rounding
1361 if coeff % 5 == 0:
1362 coeff += 1
1363 else:
1364 # result is exact; get as close to ideal exponent as possible
1365 ideal_exp = self._exp - other._exp
1366 while exp < ideal_exp and coeff % 10 == 0:
1367 coeff //= 10
1368 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001369
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001370 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001371 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001372
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001373 def _divide(self, other, context):
1374 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001375
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001376 Assumes that neither self nor other is a NaN, that self is not
1377 infinite and that other is nonzero.
1378 """
1379 sign = self._sign ^ other._sign
1380 if other._isinfinity():
1381 ideal_exp = self._exp
1382 else:
1383 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001384
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001385 expdiff = self.adjusted() - other.adjusted()
1386 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001387 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001388 self._rescale(ideal_exp, context.rounding))
1389 if expdiff <= context.prec:
1390 op1 = _WorkRep(self)
1391 op2 = _WorkRep(other)
1392 if op1.exp >= op2.exp:
1393 op1.int *= 10**(op1.exp - op2.exp)
1394 else:
1395 op2.int *= 10**(op2.exp - op1.exp)
1396 q, r = divmod(op1.int, op2.int)
1397 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001398 return (_dec_from_triple(sign, str(q), 0),
1399 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001400
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001401 # Here the quotient is too large to be representable
1402 ans = context._raise_error(DivisionImpossible,
1403 'quotient too large in //, % or divmod')
1404 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001405
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001406 def __rtruediv__(self, other, context=None):
1407 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001408 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001409 if other is NotImplemented:
1410 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001411 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001412
1413 def __divmod__(self, other, context=None):
1414 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001415 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001416 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001417 other = _convert_other(other)
1418 if other is NotImplemented:
1419 return other
1420
1421 if context is None:
1422 context = getcontext()
1423
1424 ans = self._check_nans(other, context)
1425 if ans:
1426 return (ans, ans)
1427
1428 sign = self._sign ^ other._sign
1429 if self._isinfinity():
1430 if other._isinfinity():
1431 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1432 return ans, ans
1433 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001434 return (_SignedInfinity[sign],
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001435 context._raise_error(InvalidOperation, 'INF % x'))
1436
1437 if not other:
1438 if not self:
1439 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1440 return ans, ans
1441 else:
1442 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1443 context._raise_error(InvalidOperation, 'x % 0'))
1444
1445 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001446 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001447 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001448
1449 def __rdivmod__(self, other, context=None):
1450 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001451 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001452 if other is NotImplemented:
1453 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001454 return other.__divmod__(self, context=context)
1455
1456 def __mod__(self, other, context=None):
1457 """
1458 self % other
1459 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001460 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001461 if other is NotImplemented:
1462 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001463
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001464 if context is None:
1465 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001466
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001467 ans = self._check_nans(other, context)
1468 if ans:
1469 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001470
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001471 if self._isinfinity():
1472 return context._raise_error(InvalidOperation, 'INF % x')
1473 elif not other:
1474 if self:
1475 return context._raise_error(InvalidOperation, 'x % 0')
1476 else:
1477 return context._raise_error(DivisionUndefined, '0 % 0')
1478
1479 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001480 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001481 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001482
1483 def __rmod__(self, other, context=None):
1484 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001485 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001486 if other is NotImplemented:
1487 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001488 return other.__mod__(self, context=context)
1489
1490 def remainder_near(self, other, context=None):
1491 """
1492 Remainder nearest to 0- abs(remainder-near) <= other/2
1493 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001494 if context is None:
1495 context = getcontext()
1496
1497 other = _convert_other(other, raiseit=True)
1498
1499 ans = self._check_nans(other, context)
1500 if ans:
1501 return ans
1502
1503 # self == +/-infinity -> InvalidOperation
1504 if self._isinfinity():
1505 return context._raise_error(InvalidOperation,
1506 'remainder_near(infinity, x)')
1507
1508 # other == 0 -> either InvalidOperation or DivisionUndefined
1509 if not other:
1510 if self:
1511 return context._raise_error(InvalidOperation,
1512 'remainder_near(x, 0)')
1513 else:
1514 return context._raise_error(DivisionUndefined,
1515 'remainder_near(0, 0)')
1516
1517 # other = +/-infinity -> remainder = self
1518 if other._isinfinity():
1519 ans = Decimal(self)
1520 return ans._fix(context)
1521
1522 # self = 0 -> remainder = self, with ideal exponent
1523 ideal_exponent = min(self._exp, other._exp)
1524 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001525 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001526 return ans._fix(context)
1527
1528 # catch most cases of large or small quotient
1529 expdiff = self.adjusted() - other.adjusted()
1530 if expdiff >= context.prec + 1:
1531 # expdiff >= prec+1 => abs(self/other) > 10**prec
1532 return context._raise_error(DivisionImpossible)
1533 if expdiff <= -2:
1534 # expdiff <= -2 => abs(self/other) < 0.1
1535 ans = self._rescale(ideal_exponent, context.rounding)
1536 return ans._fix(context)
1537
1538 # adjust both arguments to have the same exponent, then divide
1539 op1 = _WorkRep(self)
1540 op2 = _WorkRep(other)
1541 if op1.exp >= op2.exp:
1542 op1.int *= 10**(op1.exp - op2.exp)
1543 else:
1544 op2.int *= 10**(op2.exp - op1.exp)
1545 q, r = divmod(op1.int, op2.int)
1546 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1547 # 10**ideal_exponent. Apply correction to ensure that
1548 # abs(remainder) <= abs(other)/2
1549 if 2*r + (q&1) > op2.int:
1550 r -= op2.int
1551 q += 1
1552
1553 if q >= 10**context.prec:
1554 return context._raise_error(DivisionImpossible)
1555
1556 # result has same sign as self unless r is negative
1557 sign = self._sign
1558 if r < 0:
1559 sign = 1-sign
1560 r = -r
1561
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001562 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001563 return ans._fix(context)
1564
1565 def __floordiv__(self, other, context=None):
1566 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001567 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001568 if other is NotImplemented:
1569 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001570
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001571 if context is None:
1572 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001573
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001574 ans = self._check_nans(other, context)
1575 if ans:
1576 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001577
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001578 if self._isinfinity():
1579 if other._isinfinity():
1580 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001581 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001582 return _SignedInfinity[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001583
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001584 if not other:
1585 if self:
1586 return context._raise_error(DivisionByZero, 'x // 0',
1587 self._sign ^ other._sign)
1588 else:
1589 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001590
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001591 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001592
1593 def __rfloordiv__(self, other, context=None):
1594 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001595 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001596 if other is NotImplemented:
1597 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001598 return other.__floordiv__(self, context=context)
1599
1600 def __float__(self):
1601 """Float representation."""
Mark Dickinsonfc33d4c2012-08-24 18:53:10 +01001602 if self._isnan():
1603 if self.is_snan():
1604 raise ValueError("Cannot convert signaling NaN to float")
1605 s = "-nan" if self._sign else "nan"
1606 else:
1607 s = str(self)
1608 return float(s)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001609
1610 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001611 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001612 if self._is_special:
1613 if self._isnan():
Mark Dickinson825fce32009-09-07 18:08:12 +00001614 raise ValueError("Cannot convert NaN to integer")
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001615 elif self._isinfinity():
Mark Dickinson825fce32009-09-07 18:08:12 +00001616 raise OverflowError("Cannot convert infinity to integer")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001617 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001618 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001619 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001620 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001621 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001622
Christian Heimes969fe572008-01-25 11:23:10 +00001623 __trunc__ = __int__
1624
Christian Heimes0bd4e112008-02-12 22:59:25 +00001625 def real(self):
1626 return self
Mark Dickinson315a20a2009-01-04 21:34:18 +00001627 real = property(real)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001628
Christian Heimes0bd4e112008-02-12 22:59:25 +00001629 def imag(self):
1630 return Decimal(0)
Mark Dickinson315a20a2009-01-04 21:34:18 +00001631 imag = property(imag)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001632
1633 def conjugate(self):
1634 return self
1635
1636 def __complex__(self):
1637 return complex(float(self))
1638
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001639 def _fix_nan(self, context):
1640 """Decapitate the payload of a NaN to fit the context"""
1641 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001642
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001643 # maximum length of payload is precision if clamp=0,
1644 # precision-1 if clamp=1.
1645 max_payload_len = context.prec - context.clamp
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001646 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001647 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1648 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001649 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001650
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001651 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001652 """Round if it is necessary to keep self within prec precision.
1653
1654 Rounds and fixes the exponent. Does not raise on a sNaN.
1655
1656 Arguments:
1657 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001658 context - context used.
1659 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001660
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001661 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001662 if self._isnan():
1663 # decapitate payload if necessary
1664 return self._fix_nan(context)
1665 else:
1666 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001667 return Decimal(self)
1668
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001669 # if self is zero then exponent should be between Etiny and
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001670 # Emax if clamp==0, and between Etiny and Etop if clamp==1.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001671 Etiny = context.Etiny()
1672 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001673 if not self:
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001674 exp_max = [context.Emax, Etop][context.clamp]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001675 new_exp = min(max(self._exp, Etiny), exp_max)
1676 if new_exp != self._exp:
1677 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001678 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001679 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001680 return Decimal(self)
1681
1682 # exp_min is the smallest allowable exponent of the result,
1683 # equal to max(self.adjusted()-context.prec+1, Etiny)
1684 exp_min = len(self._int) + self._exp - context.prec
1685 if exp_min > Etop:
1686 # overflow: exp_min > Etop iff self.adjusted() > Emax
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001687 ans = context._raise_error(Overflow, 'above Emax', self._sign)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001688 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001689 context._raise_error(Rounded)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001690 return ans
1691
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001692 self_is_subnormal = exp_min < Etiny
1693 if self_is_subnormal:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001694 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001695
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001696 # round if self has too many digits
1697 if self._exp < exp_min:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001698 digits = len(self._int) + self._exp - exp_min
1699 if digits < 0:
1700 self = _dec_from_triple(self._sign, '1', exp_min-1)
1701 digits = 0
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001702 rounding_method = self._pick_rounding_function[context.rounding]
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04001703 changed = rounding_method(self, digits)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001704 coeff = self._int[:digits] or '0'
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001705 if changed > 0:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001706 coeff = str(int(coeff)+1)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001707 if len(coeff) > context.prec:
1708 coeff = coeff[:-1]
1709 exp_min += 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001710
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001711 # check whether the rounding pushed the exponent out of range
1712 if exp_min > Etop:
1713 ans = context._raise_error(Overflow, 'above Emax', self._sign)
1714 else:
1715 ans = _dec_from_triple(self._sign, coeff, exp_min)
1716
1717 # raise the appropriate signals, taking care to respect
1718 # the precedence described in the specification
1719 if changed and self_is_subnormal:
1720 context._raise_error(Underflow)
1721 if self_is_subnormal:
1722 context._raise_error(Subnormal)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001723 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001724 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001725 context._raise_error(Rounded)
1726 if not ans:
1727 # raise Clamped on underflow to 0
1728 context._raise_error(Clamped)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001729 return ans
1730
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001731 if self_is_subnormal:
1732 context._raise_error(Subnormal)
1733
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001734 # fold down if clamp == 1 and self has too few digits
1735 if context.clamp == 1 and self._exp > Etop:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001736 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001737 self_padded = self._int + '0'*(self._exp - Etop)
1738 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001739
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001740 # here self was representable to begin with; return unchanged
1741 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001742
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001743 # for each of the rounding functions below:
1744 # self is a finite, nonzero Decimal
1745 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001746 #
1747 # each function returns either -1, 0, or 1, as follows:
1748 # 1 indicates that self should be rounded up (away from zero)
1749 # 0 indicates that self should be truncated, and that all the
1750 # digits to be truncated are zeros (so the value is unchanged)
1751 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001752
1753 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001754 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001755 if _all_zeros(self._int, prec):
1756 return 0
1757 else:
1758 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001759
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001760 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001761 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001762 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001763
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001764 def _round_half_up(self, prec):
1765 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001766 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001767 return 1
1768 elif _all_zeros(self._int, prec):
1769 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001770 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001771 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001772
1773 def _round_half_down(self, prec):
1774 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001775 if _exact_half(self._int, prec):
1776 return -1
1777 else:
1778 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001779
1780 def _round_half_even(self, prec):
1781 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001782 if _exact_half(self._int, prec) and \
1783 (prec == 0 or self._int[prec-1] in '02468'):
1784 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001785 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001786 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001787
1788 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001789 """Rounds up (not away from 0 if negative.)"""
1790 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001791 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001792 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001793 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001794
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001795 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001796 """Rounds down (not towards 0 if negative)"""
1797 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001798 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001799 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001800 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001801
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001802 def _round_05up(self, prec):
1803 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001804 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001805 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001806 else:
1807 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001808
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04001809 _pick_rounding_function = dict(
1810 ROUND_DOWN = _round_down,
1811 ROUND_UP = _round_up,
1812 ROUND_HALF_UP = _round_half_up,
1813 ROUND_HALF_DOWN = _round_half_down,
1814 ROUND_HALF_EVEN = _round_half_even,
1815 ROUND_CEILING = _round_ceiling,
1816 ROUND_FLOOR = _round_floor,
1817 ROUND_05UP = _round_05up,
1818 )
1819
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001820 def __round__(self, n=None):
1821 """Round self to the nearest integer, or to a given precision.
1822
1823 If only one argument is supplied, round a finite Decimal
1824 instance self to the nearest integer. If self is infinite or
1825 a NaN then a Python exception is raised. If self is finite
1826 and lies exactly halfway between two integers then it is
1827 rounded to the integer with even last digit.
1828
1829 >>> round(Decimal('123.456'))
1830 123
1831 >>> round(Decimal('-456.789'))
1832 -457
1833 >>> round(Decimal('-3.0'))
1834 -3
1835 >>> round(Decimal('2.5'))
1836 2
1837 >>> round(Decimal('3.5'))
1838 4
1839 >>> round(Decimal('Inf'))
1840 Traceback (most recent call last):
1841 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001842 OverflowError: cannot round an infinity
1843 >>> round(Decimal('NaN'))
1844 Traceback (most recent call last):
1845 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001846 ValueError: cannot round a NaN
1847
1848 If a second argument n is supplied, self is rounded to n
1849 decimal places using the rounding mode for the current
1850 context.
1851
1852 For an integer n, round(self, -n) is exactly equivalent to
1853 self.quantize(Decimal('1En')).
1854
1855 >>> round(Decimal('123.456'), 0)
1856 Decimal('123')
1857 >>> round(Decimal('123.456'), 2)
1858 Decimal('123.46')
1859 >>> round(Decimal('123.456'), -2)
1860 Decimal('1E+2')
1861 >>> round(Decimal('-Infinity'), 37)
1862 Decimal('NaN')
1863 >>> round(Decimal('sNaN123'), 0)
1864 Decimal('NaN123')
1865
1866 """
1867 if n is not None:
1868 # two-argument form: use the equivalent quantize call
1869 if not isinstance(n, int):
1870 raise TypeError('Second argument to round should be integral')
1871 exp = _dec_from_triple(0, '1', -n)
1872 return self.quantize(exp)
1873
1874 # one-argument form
1875 if self._is_special:
1876 if self.is_nan():
1877 raise ValueError("cannot round a NaN")
1878 else:
1879 raise OverflowError("cannot round an infinity")
1880 return int(self._rescale(0, ROUND_HALF_EVEN))
1881
1882 def __floor__(self):
1883 """Return the floor of self, as an integer.
1884
1885 For a finite Decimal instance self, return the greatest
1886 integer n such that n <= self. If self is infinite or a NaN
1887 then a Python exception is raised.
1888
1889 """
1890 if self._is_special:
1891 if self.is_nan():
1892 raise ValueError("cannot round a NaN")
1893 else:
1894 raise OverflowError("cannot round an infinity")
1895 return int(self._rescale(0, ROUND_FLOOR))
1896
1897 def __ceil__(self):
1898 """Return the ceiling of self, as an integer.
1899
1900 For a finite Decimal instance self, return the least integer n
1901 such that n >= self. If self is infinite or a NaN then a
1902 Python exception is raised.
1903
1904 """
1905 if self._is_special:
1906 if self.is_nan():
1907 raise ValueError("cannot round a NaN")
1908 else:
1909 raise OverflowError("cannot round an infinity")
1910 return int(self._rescale(0, ROUND_CEILING))
1911
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001912 def fma(self, other, third, context=None):
1913 """Fused multiply-add.
1914
1915 Returns self*other+third with no rounding of the intermediate
1916 product self*other.
1917
1918 self and other are multiplied together, with no rounding of
1919 the result. The third operand is then added to the result,
1920 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001921 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001922
1923 other = _convert_other(other, raiseit=True)
Mark Dickinsonb455e582011-05-22 12:53:18 +01001924 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001925
1926 # compute product; raise InvalidOperation if either operand is
1927 # a signaling NaN or if the product is zero times infinity.
1928 if self._is_special or other._is_special:
1929 if context is None:
1930 context = getcontext()
1931 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001932 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001933 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001934 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001935 if self._exp == 'n':
1936 product = self
1937 elif other._exp == 'n':
1938 product = other
1939 elif self._exp == 'F':
1940 if not other:
1941 return context._raise_error(InvalidOperation,
1942 'INF * 0 in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001943 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001944 elif other._exp == 'F':
1945 if not self:
1946 return context._raise_error(InvalidOperation,
1947 '0 * INF in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001948 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001949 else:
1950 product = _dec_from_triple(self._sign ^ other._sign,
1951 str(int(self._int) * int(other._int)),
1952 self._exp + other._exp)
1953
Christian Heimes8b0facf2007-12-04 19:30:01 +00001954 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001955
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001956 def _power_modulo(self, other, modulo, context=None):
1957 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001958
Stefan Krah1919b7e2012-03-21 18:25:23 +01001959 other = _convert_other(other)
1960 if other is NotImplemented:
1961 return other
1962 modulo = _convert_other(modulo)
1963 if modulo is NotImplemented:
1964 return modulo
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001965
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001966 if context is None:
1967 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001968
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001969 # deal with NaNs: if there are any sNaNs then first one wins,
1970 # (i.e. behaviour for NaNs is identical to that of fma)
1971 self_is_nan = self._isnan()
1972 other_is_nan = other._isnan()
1973 modulo_is_nan = modulo._isnan()
1974 if self_is_nan or other_is_nan or modulo_is_nan:
1975 if self_is_nan == 2:
1976 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001977 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001978 if other_is_nan == 2:
1979 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001980 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001981 if modulo_is_nan == 2:
1982 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001983 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001984 if self_is_nan:
1985 return self._fix_nan(context)
1986 if other_is_nan:
1987 return other._fix_nan(context)
1988 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001989
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001990 # check inputs: we apply same restrictions as Python's pow()
1991 if not (self._isinteger() and
1992 other._isinteger() and
1993 modulo._isinteger()):
1994 return context._raise_error(InvalidOperation,
1995 'pow() 3rd argument not allowed '
1996 'unless all arguments are integers')
1997 if other < 0:
1998 return context._raise_error(InvalidOperation,
1999 'pow() 2nd argument cannot be '
2000 'negative when 3rd argument specified')
2001 if not modulo:
2002 return context._raise_error(InvalidOperation,
2003 'pow() 3rd argument cannot be 0')
2004
2005 # additional restriction for decimal: the modulus must be less
2006 # than 10**prec in absolute value
2007 if modulo.adjusted() >= context.prec:
2008 return context._raise_error(InvalidOperation,
2009 'insufficient precision: pow() 3rd '
2010 'argument must not have more than '
2011 'precision digits')
2012
2013 # define 0**0 == NaN, for consistency with two-argument pow
2014 # (even though it hurts!)
2015 if not other and not self:
2016 return context._raise_error(InvalidOperation,
2017 'at least one of pow() 1st argument '
2018 'and 2nd argument must be nonzero ;'
2019 '0**0 is not defined')
2020
2021 # compute sign of result
2022 if other._iseven():
2023 sign = 0
2024 else:
2025 sign = self._sign
2026
2027 # convert modulo to a Python integer, and self and other to
2028 # Decimal integers (i.e. force their exponents to be >= 0)
2029 modulo = abs(int(modulo))
2030 base = _WorkRep(self.to_integral_value())
2031 exponent = _WorkRep(other.to_integral_value())
2032
2033 # compute result using integer pow()
2034 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
2035 for i in range(exponent.exp):
2036 base = pow(base, 10, modulo)
2037 base = pow(base, exponent.int, modulo)
2038
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002039 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002040
2041 def _power_exact(self, other, p):
2042 """Attempt to compute self**other exactly.
2043
2044 Given Decimals self and other and an integer p, attempt to
2045 compute an exact result for the power self**other, with p
2046 digits of precision. Return None if self**other is not
2047 exactly representable in p digits.
2048
2049 Assumes that elimination of special cases has already been
2050 performed: self and other must both be nonspecial; self must
2051 be positive and not numerically equal to 1; other must be
2052 nonzero. For efficiency, other._exp should not be too large,
2053 so that 10**abs(other._exp) is a feasible calculation."""
2054
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002055 # In the comments below, we write x for the value of self and y for the
2056 # value of other. Write x = xc*10**xe and abs(y) = yc*10**ye, with xc
2057 # and yc positive integers not divisible by 10.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002058
2059 # The main purpose of this method is to identify the *failure*
2060 # of x**y to be exactly representable with as little effort as
2061 # possible. So we look for cheap and easy tests that
2062 # eliminate the possibility of x**y being exact. Only if all
2063 # these tests are passed do we go on to actually compute x**y.
2064
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002065 # Here's the main idea. Express y as a rational number m/n, with m and
2066 # n relatively prime and n>0. Then for x**y to be exactly
2067 # representable (at *any* precision), xc must be the nth power of a
2068 # positive integer and xe must be divisible by n. If y is negative
2069 # then additionally xc must be a power of either 2 or 5, hence a power
2070 # of 2**n or 5**n.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002071 #
2072 # There's a limit to how small |y| can be: if y=m/n as above
2073 # then:
2074 #
2075 # (1) if xc != 1 then for the result to be representable we
2076 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
2077 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
2078 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
2079 # representable.
2080 #
2081 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
2082 # |y| < 1/|xe| then the result is not representable.
2083 #
2084 # Note that since x is not equal to 1, at least one of (1) and
2085 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
2086 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
2087 #
2088 # There's also a limit to how large y can be, at least if it's
2089 # positive: the normalized result will have coefficient xc**y,
2090 # so if it's representable then xc**y < 10**p, and y <
2091 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
2092 # not exactly representable.
2093
2094 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
2095 # so |y| < 1/xe and the result is not representable.
2096 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
2097 # < 1/nbits(xc).
2098
2099 x = _WorkRep(self)
2100 xc, xe = x.int, x.exp
2101 while xc % 10 == 0:
2102 xc //= 10
2103 xe += 1
2104
2105 y = _WorkRep(other)
2106 yc, ye = y.int, y.exp
2107 while yc % 10 == 0:
2108 yc //= 10
2109 ye += 1
2110
2111 # case where xc == 1: result is 10**(xe*y), with xe*y
2112 # required to be an integer
2113 if xc == 1:
Mark Dickinsona1236312010-07-08 19:03:34 +00002114 xe *= yc
2115 # result is now 10**(xe * 10**ye); xe * 10**ye must be integral
2116 while xe % 10 == 0:
2117 xe //= 10
2118 ye += 1
2119 if ye < 0:
2120 return None
2121 exponent = xe * 10**ye
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002122 if y.sign == 1:
2123 exponent = -exponent
2124 # if other is a nonnegative integer, use ideal exponent
2125 if other._isinteger() and other._sign == 0:
2126 ideal_exponent = self._exp*int(other)
2127 zeros = min(exponent-ideal_exponent, p-1)
2128 else:
2129 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002130 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002131
2132 # case where y is negative: xc must be either a power
2133 # of 2 or a power of 5.
2134 if y.sign == 1:
2135 last_digit = xc % 10
2136 if last_digit in (2,4,6,8):
2137 # quick test for power of 2
2138 if xc & -xc != xc:
2139 return None
2140 # now xc is a power of 2; e is its exponent
2141 e = _nbits(xc)-1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002142
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002143 # We now have:
2144 #
2145 # x = 2**e * 10**xe, e > 0, and y < 0.
2146 #
2147 # The exact result is:
2148 #
2149 # x**y = 5**(-e*y) * 10**(e*y + xe*y)
2150 #
2151 # provided that both e*y and xe*y are integers. Note that if
2152 # 5**(-e*y) >= 10**p, then the result can't be expressed
2153 # exactly with p digits of precision.
2154 #
2155 # Using the above, we can guard against large values of ye.
2156 # 93/65 is an upper bound for log(10)/log(5), so if
2157 #
2158 # ye >= len(str(93*p//65))
2159 #
2160 # then
2161 #
2162 # -e*y >= -y >= 10**ye > 93*p/65 > p*log(10)/log(5),
2163 #
2164 # so 5**(-e*y) >= 10**p, and the coefficient of the result
2165 # can't be expressed in p digits.
2166
2167 # emax >= largest e such that 5**e < 10**p.
2168 emax = p*93//65
2169 if ye >= len(str(emax)):
2170 return None
2171
2172 # Find -e*y and -xe*y; both must be integers
2173 e = _decimal_lshift_exact(e * yc, ye)
2174 xe = _decimal_lshift_exact(xe * yc, ye)
2175 if e is None or xe is None:
2176 return None
2177
2178 if e > emax:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002179 return None
2180 xc = 5**e
2181
2182 elif last_digit == 5:
2183 # e >= log_5(xc) if xc is a power of 5; we have
2184 # equality all the way up to xc=5**2658
2185 e = _nbits(xc)*28//65
2186 xc, remainder = divmod(5**e, xc)
2187 if remainder:
2188 return None
2189 while xc % 5 == 0:
2190 xc //= 5
2191 e -= 1
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002192
2193 # Guard against large values of ye, using the same logic as in
2194 # the 'xc is a power of 2' branch. 10/3 is an upper bound for
2195 # log(10)/log(2).
2196 emax = p*10//3
2197 if ye >= len(str(emax)):
2198 return None
2199
2200 e = _decimal_lshift_exact(e * yc, ye)
2201 xe = _decimal_lshift_exact(xe * yc, ye)
2202 if e is None or xe is None:
2203 return None
2204
2205 if e > emax:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002206 return None
2207 xc = 2**e
2208 else:
2209 return None
2210
2211 if xc >= 10**p:
2212 return None
2213 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002214 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002215
2216 # now y is positive; find m and n such that y = m/n
2217 if ye >= 0:
2218 m, n = yc*10**ye, 1
2219 else:
2220 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2221 return None
2222 xc_bits = _nbits(xc)
2223 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2224 return None
2225 m, n = yc, 10**(-ye)
2226 while m % 2 == n % 2 == 0:
2227 m //= 2
2228 n //= 2
2229 while m % 5 == n % 5 == 0:
2230 m //= 5
2231 n //= 5
2232
2233 # compute nth root of xc*10**xe
2234 if n > 1:
2235 # if 1 < xc < 2**n then xc isn't an nth power
2236 if xc != 1 and xc_bits <= n:
2237 return None
2238
2239 xe, rem = divmod(xe, n)
2240 if rem != 0:
2241 return None
2242
2243 # compute nth root of xc using Newton's method
2244 a = 1 << -(-_nbits(xc)//n) # initial estimate
2245 while True:
2246 q, r = divmod(xc, a**(n-1))
2247 if a <= q:
2248 break
2249 else:
2250 a = (a*(n-1) + q)//n
2251 if not (a == q and r == 0):
2252 return None
2253 xc = a
2254
2255 # now xc*10**xe is the nth root of the original xc*10**xe
2256 # compute mth power of xc*10**xe
2257
2258 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2259 # 10**p and the result is not representable.
2260 if xc > 1 and m > p*100//_log10_lb(xc):
2261 return None
2262 xc = xc**m
2263 xe *= m
2264 if xc > 10**p:
2265 return None
2266
2267 # by this point the result *is* exactly representable
2268 # adjust the exponent to get as close as possible to the ideal
2269 # exponent, if necessary
2270 str_xc = str(xc)
2271 if other._isinteger() and other._sign == 0:
2272 ideal_exponent = self._exp*int(other)
2273 zeros = min(xe-ideal_exponent, p-len(str_xc))
2274 else:
2275 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002276 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002277
2278 def __pow__(self, other, modulo=None, context=None):
2279 """Return self ** other [ % modulo].
2280
2281 With two arguments, compute self**other.
2282
2283 With three arguments, compute (self**other) % modulo. For the
2284 three argument form, the following restrictions on the
2285 arguments hold:
2286
2287 - all three arguments must be integral
2288 - other must be nonnegative
2289 - either self or other (or both) must be nonzero
2290 - modulo must be nonzero and must have at most p digits,
2291 where p is the context precision.
2292
2293 If any of these restrictions is violated the InvalidOperation
2294 flag is raised.
2295
2296 The result of pow(self, other, modulo) is identical to the
2297 result that would be obtained by computing (self**other) %
2298 modulo with unbounded precision, but is computed more
2299 efficiently. It is always exact.
2300 """
2301
2302 if modulo is not None:
2303 return self._power_modulo(other, modulo, context)
2304
2305 other = _convert_other(other)
2306 if other is NotImplemented:
2307 return other
2308
2309 if context is None:
2310 context = getcontext()
2311
2312 # either argument is a NaN => result is NaN
2313 ans = self._check_nans(other, context)
2314 if ans:
2315 return ans
2316
2317 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2318 if not other:
2319 if not self:
2320 return context._raise_error(InvalidOperation, '0 ** 0')
2321 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002322 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002323
2324 # result has sign 1 iff self._sign is 1 and other is an odd integer
2325 result_sign = 0
2326 if self._sign == 1:
2327 if other._isinteger():
2328 if not other._iseven():
2329 result_sign = 1
2330 else:
2331 # -ve**noninteger = NaN
2332 # (-0)**noninteger = 0**noninteger
2333 if self:
2334 return context._raise_error(InvalidOperation,
2335 'x ** y with x negative and y not an integer')
2336 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002337 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002338
2339 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2340 if not self:
2341 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002342 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002343 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002344 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002345
2346 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002347 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002348 if other._sign == 0:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002349 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002350 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002351 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002352
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002353 # 1**other = 1, but the choice of exponent and the flags
2354 # depend on the exponent of self, and on whether other is a
2355 # positive integer, a negative integer, or neither
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002356 if self == _One:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002357 if other._isinteger():
2358 # exp = max(self._exp*max(int(other), 0),
2359 # 1-context.prec) but evaluating int(other) directly
2360 # is dangerous until we know other is small (other
2361 # could be 1e999999999)
2362 if other._sign == 1:
2363 multiplier = 0
2364 elif other > context.prec:
2365 multiplier = context.prec
2366 else:
2367 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002368
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002369 exp = self._exp * multiplier
2370 if exp < 1-context.prec:
2371 exp = 1-context.prec
2372 context._raise_error(Rounded)
2373 else:
2374 context._raise_error(Inexact)
2375 context._raise_error(Rounded)
2376 exp = 1-context.prec
2377
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002378 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002379
2380 # compute adjusted exponent of self
2381 self_adj = self.adjusted()
2382
2383 # self ** infinity is infinity if self > 1, 0 if self < 1
2384 # self ** -infinity is infinity if self < 1, 0 if self > 1
2385 if other._isinfinity():
2386 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002387 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002388 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002389 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002390
2391 # from here on, the result always goes through the call
2392 # to _fix at the end of this function.
2393 ans = None
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002394 exact = False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002395
2396 # crude test to catch cases of extreme overflow/underflow. If
2397 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2398 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2399 # self**other >= 10**(Emax+1), so overflow occurs. The test
2400 # for underflow is similar.
2401 bound = self._log10_exp_bound() + other.adjusted()
2402 if (self_adj >= 0) == (other._sign == 0):
2403 # self > 1 and other +ve, or self < 1 and other -ve
2404 # possibility of overflow
2405 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002406 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002407 else:
2408 # self > 1 and other -ve, or self < 1 and other +ve
2409 # possibility of underflow to 0
2410 Etiny = context.Etiny()
2411 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002412 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002413
2414 # try for an exact result with precision +1
2415 if ans is None:
2416 ans = self._power_exact(other, context.prec + 1)
Mark Dickinsone42f1bb2010-07-08 19:09:16 +00002417 if ans is not None:
2418 if result_sign == 1:
2419 ans = _dec_from_triple(1, ans._int, ans._exp)
2420 exact = True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002421
2422 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2423 if ans is None:
2424 p = context.prec
2425 x = _WorkRep(self)
2426 xc, xe = x.int, x.exp
2427 y = _WorkRep(other)
2428 yc, ye = y.int, y.exp
2429 if y.sign == 1:
2430 yc = -yc
2431
2432 # compute correctly rounded result: start with precision +3,
2433 # then increase precision until result is unambiguously roundable
2434 extra = 3
2435 while True:
2436 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2437 if coeff % (5*10**(len(str(coeff))-p-1)):
2438 break
2439 extra += 3
2440
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002441 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002442
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002443 # unlike exp, ln and log10, the power function respects the
2444 # rounding mode; no need to switch to ROUND_HALF_EVEN here
2445
2446 # There's a difficulty here when 'other' is not an integer and
2447 # the result is exact. In this case, the specification
2448 # requires that the Inexact flag be raised (in spite of
2449 # exactness), but since the result is exact _fix won't do this
2450 # for us. (Correspondingly, the Underflow signal should also
2451 # be raised for subnormal results.) We can't directly raise
2452 # these signals either before or after calling _fix, since
2453 # that would violate the precedence for signals. So we wrap
2454 # the ._fix call in a temporary context, and reraise
2455 # afterwards.
2456 if exact and not other._isinteger():
2457 # pad with zeros up to length context.prec+1 if necessary; this
2458 # ensures that the Rounded signal will be raised.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002459 if len(ans._int) <= context.prec:
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002460 expdiff = context.prec + 1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002461 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2462 ans._exp-expdiff)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002463
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002464 # create a copy of the current context, with cleared flags/traps
2465 newcontext = context.copy()
2466 newcontext.clear_flags()
2467 for exception in _signals:
2468 newcontext.traps[exception] = 0
2469
2470 # round in the new context
2471 ans = ans._fix(newcontext)
2472
2473 # raise Inexact, and if necessary, Underflow
2474 newcontext._raise_error(Inexact)
2475 if newcontext.flags[Subnormal]:
2476 newcontext._raise_error(Underflow)
2477
2478 # propagate signals to the original context; _fix could
2479 # have raised any of Overflow, Underflow, Subnormal,
2480 # Inexact, Rounded, Clamped. Overflow needs the correct
2481 # arguments. Note that the order of the exceptions is
2482 # important here.
2483 if newcontext.flags[Overflow]:
2484 context._raise_error(Overflow, 'above Emax', ans._sign)
2485 for exception in Underflow, Subnormal, Inexact, Rounded, Clamped:
2486 if newcontext.flags[exception]:
2487 context._raise_error(exception)
2488
2489 else:
2490 ans = ans._fix(context)
2491
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002492 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002493
2494 def __rpow__(self, other, context=None):
2495 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002496 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002497 if other is NotImplemented:
2498 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002499 return other.__pow__(self, context=context)
2500
2501 def normalize(self, context=None):
2502 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002503
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002504 if context is None:
2505 context = getcontext()
2506
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002507 if self._is_special:
2508 ans = self._check_nans(context=context)
2509 if ans:
2510 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002511
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002512 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002513 if dup._isinfinity():
2514 return dup
2515
2516 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002517 return _dec_from_triple(dup._sign, '0', 0)
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00002518 exp_max = [context.Emax, context.Etop()][context.clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002519 end = len(dup._int)
2520 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002521 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002522 exp += 1
2523 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002524 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002525
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002526 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002527 """Quantize self so its exponent is the same as that of exp.
2528
2529 Similar to self._rescale(exp._exp) but with error checking.
2530 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002531 exp = _convert_other(exp, raiseit=True)
2532
2533 if context is None:
2534 context = getcontext()
2535 if rounding is None:
2536 rounding = context.rounding
2537
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002538 if self._is_special or exp._is_special:
2539 ans = self._check_nans(exp, context)
2540 if ans:
2541 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002542
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002543 if exp._isinfinity() or self._isinfinity():
2544 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002545 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002546 return context._raise_error(InvalidOperation,
2547 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002548
2549 # if we're not watching exponents, do a simple rescale
2550 if not watchexp:
2551 ans = self._rescale(exp._exp, rounding)
2552 # raise Inexact and Rounded where appropriate
2553 if ans._exp > self._exp:
2554 context._raise_error(Rounded)
2555 if ans != self:
2556 context._raise_error(Inexact)
2557 return ans
2558
2559 # exp._exp should be between Etiny and Emax
2560 if not (context.Etiny() <= exp._exp <= context.Emax):
2561 return context._raise_error(InvalidOperation,
2562 'target exponent out of bounds in quantize')
2563
2564 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002565 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002566 return ans._fix(context)
2567
2568 self_adjusted = self.adjusted()
2569 if self_adjusted > context.Emax:
2570 return context._raise_error(InvalidOperation,
2571 'exponent of quantize result too large for current context')
2572 if self_adjusted - exp._exp + 1 > context.prec:
2573 return context._raise_error(InvalidOperation,
2574 'quantize result has too many digits for current context')
2575
2576 ans = self._rescale(exp._exp, rounding)
2577 if ans.adjusted() > context.Emax:
2578 return context._raise_error(InvalidOperation,
2579 'exponent of quantize result too large for current context')
2580 if len(ans._int) > context.prec:
2581 return context._raise_error(InvalidOperation,
2582 'quantize result has too many digits for current context')
2583
2584 # raise appropriate flags
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002585 if ans and ans.adjusted() < context.Emin:
2586 context._raise_error(Subnormal)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002587 if ans._exp > self._exp:
2588 if ans != self:
2589 context._raise_error(Inexact)
2590 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002591
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002592 # call to fix takes care of any necessary folddown, and
2593 # signals Clamped if necessary
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002594 ans = ans._fix(context)
2595 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002596
Stefan Krah040e3112012-12-15 22:33:33 +01002597 def same_quantum(self, other, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002598 """Return True if self and other have the same exponent; otherwise
2599 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002600
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002601 If either operand is a special value, the following rules are used:
2602 * return True if both operands are infinities
2603 * return True if both operands are NaNs
2604 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002605 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002606 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002607 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002608 return (self.is_nan() and other.is_nan() or
2609 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002610 return self._exp == other._exp
2611
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002612 def _rescale(self, exp, rounding):
2613 """Rescale self so that the exponent is exp, either by padding with zeros
2614 or by truncating digits, using the given rounding mode.
2615
2616 Specials are returned without change. This operation is
2617 quiet: it raises no flags, and uses no information from the
2618 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002619
2620 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002621 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002622 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002623 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002624 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002625 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002626 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002627
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002628 if self._exp >= exp:
2629 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002630 return _dec_from_triple(self._sign,
2631 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002632
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002633 # too many digits; round and lose data. If self.adjusted() <
2634 # exp-1, replace self by 10**(exp-1) before rounding
2635 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002636 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002637 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002638 digits = 0
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04002639 this_function = self._pick_rounding_function[rounding]
2640 changed = this_function(self, digits)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002641 coeff = self._int[:digits] or '0'
2642 if changed == 1:
2643 coeff = str(int(coeff)+1)
2644 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002645
Christian Heimesf16baeb2008-02-29 14:57:44 +00002646 def _round(self, places, rounding):
2647 """Round a nonzero, nonspecial Decimal to a fixed number of
2648 significant figures, using the given rounding mode.
2649
2650 Infinities, NaNs and zeros are returned unaltered.
2651
2652 This operation is quiet: it raises no flags, and uses no
2653 information from the context.
2654
2655 """
2656 if places <= 0:
2657 raise ValueError("argument should be at least 1 in _round")
2658 if self._is_special or not self:
2659 return Decimal(self)
2660 ans = self._rescale(self.adjusted()+1-places, rounding)
2661 # it can happen that the rescale alters the adjusted exponent;
2662 # for example when rounding 99.97 to 3 significant figures.
2663 # When this happens we end up with an extra 0 at the end of
2664 # the number; a second rescale fixes this.
2665 if ans.adjusted() != self.adjusted():
2666 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2667 return ans
2668
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002669 def to_integral_exact(self, rounding=None, context=None):
2670 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002671
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002672 If no rounding mode is specified, take the rounding mode from
2673 the context. This method raises the Rounded and Inexact flags
2674 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002675
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002676 See also: to_integral_value, which does exactly the same as
2677 this method except that it doesn't raise Inexact or Rounded.
2678 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002679 if self._is_special:
2680 ans = self._check_nans(context=context)
2681 if ans:
2682 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002683 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002684 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002685 return Decimal(self)
2686 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002687 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002688 if context is None:
2689 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002690 if rounding is None:
2691 rounding = context.rounding
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002692 ans = self._rescale(0, rounding)
2693 if ans != self:
2694 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002695 context._raise_error(Rounded)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002696 return ans
2697
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002698 def to_integral_value(self, rounding=None, context=None):
2699 """Rounds to the nearest integer, without raising inexact, rounded."""
2700 if context is None:
2701 context = getcontext()
2702 if rounding is None:
2703 rounding = context.rounding
2704 if self._is_special:
2705 ans = self._check_nans(context=context)
2706 if ans:
2707 return ans
2708 return Decimal(self)
2709 if self._exp >= 0:
2710 return Decimal(self)
2711 else:
2712 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002713
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002714 # the method name changed, but we provide also the old one, for compatibility
2715 to_integral = to_integral_value
2716
2717 def sqrt(self, context=None):
2718 """Return the square root of self."""
Christian Heimes0348fb62008-03-26 12:55:56 +00002719 if context is None:
2720 context = getcontext()
2721
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002722 if self._is_special:
2723 ans = self._check_nans(context=context)
2724 if ans:
2725 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002726
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002727 if self._isinfinity() and self._sign == 0:
2728 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002729
2730 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002731 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002732 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002733 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002734
2735 if self._sign == 1:
2736 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2737
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002738 # At this point self represents a positive number. Let p be
2739 # the desired precision and express self in the form c*100**e
2740 # with c a positive real number and e an integer, c and e
2741 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2742 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2743 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2744 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2745 # the closest integer to sqrt(c) with the even integer chosen
2746 # in the case of a tie.
2747 #
2748 # To ensure correct rounding in all cases, we use the
2749 # following trick: we compute the square root to an extra
2750 # place (precision p+1 instead of precision p), rounding down.
2751 # Then, if the result is inexact and its last digit is 0 or 5,
2752 # we increase the last digit to 1 or 6 respectively; if it's
2753 # exact we leave the last digit alone. Now the final round to
2754 # p places (or fewer in the case of underflow) will round
2755 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002756
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002757 # use an extra digit of precision
2758 prec = context.prec+1
2759
2760 # write argument in the form c*100**e where e = self._exp//2
2761 # is the 'ideal' exponent, to be used if the square root is
2762 # exactly representable. l is the number of 'digits' of c in
2763 # base 100, so that 100**(l-1) <= c < 100**l.
2764 op = _WorkRep(self)
2765 e = op.exp >> 1
2766 if op.exp & 1:
2767 c = op.int * 10
2768 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002769 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002770 c = op.int
2771 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002772
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002773 # rescale so that c has exactly prec base 100 'digits'
2774 shift = prec-l
2775 if shift >= 0:
2776 c *= 100**shift
2777 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002778 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002779 c, remainder = divmod(c, 100**-shift)
2780 exact = not remainder
2781 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002782
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002783 # find n = floor(sqrt(c)) using Newton's method
2784 n = 10**prec
2785 while True:
2786 q = c//n
2787 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002788 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002789 else:
2790 n = n + q >> 1
2791 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002792
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002793 if exact:
2794 # result is exact; rescale to use ideal exponent e
2795 if shift >= 0:
2796 # assert n % 10**shift == 0
2797 n //= 10**shift
2798 else:
2799 n *= 10**-shift
2800 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002801 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002802 # result is not exact; fix last digit as described above
2803 if n % 5 == 0:
2804 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002805
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002806 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002807
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002808 # round, and fit to current context
2809 context = context._shallow_copy()
2810 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002811 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002812 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002813
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002814 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002815
2816 def max(self, other, context=None):
2817 """Returns the larger value.
2818
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002819 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002820 NaN (and signals if one is sNaN). Also rounds.
2821 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002822 other = _convert_other(other, raiseit=True)
2823
2824 if context is None:
2825 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002826
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002827 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002828 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002829 # number is always returned
2830 sn = self._isnan()
2831 on = other._isnan()
2832 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002833 if on == 1 and sn == 0:
2834 return self._fix(context)
2835 if sn == 1 and on == 0:
2836 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002837 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002838
Christian Heimes77c02eb2008-02-09 02:18:51 +00002839 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002840 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002841 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002842 # then an ordering is applied:
2843 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002844 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002845 # positive sign and min returns the operand with the negative sign
2846 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002847 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002848 # the result. This is exactly the ordering used in compare_total.
2849 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002850
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002851 if c == -1:
2852 ans = other
2853 else:
2854 ans = self
2855
Christian Heimes2c181612007-12-17 20:04:13 +00002856 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002857
2858 def min(self, other, context=None):
2859 """Returns the smaller value.
2860
Guido van Rossumd8faa362007-04-27 19:54:29 +00002861 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002862 NaN (and signals if one is sNaN). Also rounds.
2863 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002864 other = _convert_other(other, raiseit=True)
2865
2866 if context is None:
2867 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002868
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002869 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002870 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002871 # number is always returned
2872 sn = self._isnan()
2873 on = other._isnan()
2874 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002875 if on == 1 and sn == 0:
2876 return self._fix(context)
2877 if sn == 1 and on == 0:
2878 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002879 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002880
Christian Heimes77c02eb2008-02-09 02:18:51 +00002881 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002882 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002883 c = self.compare_total(other)
2884
2885 if c == -1:
2886 ans = self
2887 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002888 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002889
Christian Heimes2c181612007-12-17 20:04:13 +00002890 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002891
2892 def _isinteger(self):
2893 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002894 if self._is_special:
2895 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002896 if self._exp >= 0:
2897 return True
2898 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002899 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002900
2901 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002902 """Returns True if self is even. Assumes self is an integer."""
2903 if not self or self._exp > 0:
2904 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002905 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002906
2907 def adjusted(self):
2908 """Return the adjusted exponent of self"""
2909 try:
2910 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002911 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002912 except TypeError:
2913 return 0
2914
Stefan Krah040e3112012-12-15 22:33:33 +01002915 def canonical(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002916 """Returns the same Decimal object.
2917
2918 As we do not have different encodings for the same number, the
2919 received object already is in its canonical form.
2920 """
2921 return self
2922
2923 def compare_signal(self, other, context=None):
2924 """Compares self to the other operand numerically.
2925
2926 It's pretty much like compare(), but all NaNs signal, with signaling
2927 NaNs taking precedence over quiet NaNs.
2928 """
Christian Heimes77c02eb2008-02-09 02:18:51 +00002929 other = _convert_other(other, raiseit = True)
2930 ans = self._compare_check_nans(other, context)
2931 if ans:
2932 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002933 return self.compare(other, context=context)
2934
Stefan Krah040e3112012-12-15 22:33:33 +01002935 def compare_total(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002936 """Compares self to other using the abstract representations.
2937
2938 This is not like the standard compare, which use their numerical
2939 value. Note that a total ordering is defined for all possible abstract
2940 representations.
2941 """
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00002942 other = _convert_other(other, raiseit=True)
2943
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002944 # if one is negative and the other is positive, it's easy
2945 if self._sign and not other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002946 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002947 if not self._sign and other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002948 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002949 sign = self._sign
2950
2951 # let's handle both NaN types
2952 self_nan = self._isnan()
2953 other_nan = other._isnan()
2954 if self_nan or other_nan:
2955 if self_nan == other_nan:
Mark Dickinsond314e1b2009-08-28 13:39:53 +00002956 # compare payloads as though they're integers
2957 self_key = len(self._int), self._int
2958 other_key = len(other._int), other._int
2959 if self_key < other_key:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002960 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002961 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002962 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002963 return _NegativeOne
Mark Dickinsond314e1b2009-08-28 13:39:53 +00002964 if self_key > other_key:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002965 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002966 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002967 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002968 return _One
2969 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002970
2971 if sign:
2972 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002973 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002974 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002975 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002976 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002977 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002978 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002979 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002980 else:
2981 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002982 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002983 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002984 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002985 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002986 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002987 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002988 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002989
2990 if self < other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002991 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002992 if self > other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002993 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002994
2995 if self._exp < other._exp:
2996 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002997 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002998 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002999 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003000 if self._exp > other._exp:
3001 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003002 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003003 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003004 return _One
3005 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003006
3007
Stefan Krah040e3112012-12-15 22:33:33 +01003008 def compare_total_mag(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003009 """Compares self to other using abstract repr., ignoring sign.
3010
3011 Like compare_total, but with operand's sign ignored and assumed to be 0.
3012 """
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003013 other = _convert_other(other, raiseit=True)
3014
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003015 s = self.copy_abs()
3016 o = other.copy_abs()
3017 return s.compare_total(o)
3018
3019 def copy_abs(self):
3020 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003021 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003022
3023 def copy_negate(self):
3024 """Returns a copy with the sign inverted."""
3025 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003026 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003027 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003028 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003029
Stefan Krah040e3112012-12-15 22:33:33 +01003030 def copy_sign(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003031 """Returns self with the sign of other."""
Mark Dickinson84230a12010-02-18 14:49:50 +00003032 other = _convert_other(other, raiseit=True)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003033 return _dec_from_triple(other._sign, self._int,
3034 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003035
3036 def exp(self, context=None):
3037 """Returns e ** self."""
3038
3039 if context is None:
3040 context = getcontext()
3041
3042 # exp(NaN) = NaN
3043 ans = self._check_nans(context=context)
3044 if ans:
3045 return ans
3046
3047 # exp(-Infinity) = 0
3048 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003049 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003050
3051 # exp(0) = 1
3052 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003053 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003054
3055 # exp(Infinity) = Infinity
3056 if self._isinfinity() == 1:
3057 return Decimal(self)
3058
3059 # the result is now guaranteed to be inexact (the true
3060 # mathematical result is transcendental). There's no need to
3061 # raise Rounded and Inexact here---they'll always be raised as
3062 # a result of the call to _fix.
3063 p = context.prec
3064 adj = self.adjusted()
3065
3066 # we only need to do any computation for quite a small range
3067 # of adjusted exponents---for example, -29 <= adj <= 10 for
3068 # the default context. For smaller exponent the result is
3069 # indistinguishable from 1 at the given precision, while for
3070 # larger exponent the result either overflows or underflows.
3071 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
3072 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003073 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003074 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
3075 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003076 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003077 elif self._sign == 0 and adj < -p:
3078 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003079 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003080 elif self._sign == 1 and adj < -p-1:
3081 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003082 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003083 # general case
3084 else:
3085 op = _WorkRep(self)
3086 c, e = op.int, op.exp
3087 if op.sign == 1:
3088 c = -c
3089
3090 # compute correctly rounded result: increase precision by
3091 # 3 digits at a time until we get an unambiguously
3092 # roundable result
3093 extra = 3
3094 while True:
3095 coeff, exp = _dexp(c, e, p+extra)
3096 if coeff % (5*10**(len(str(coeff))-p-1)):
3097 break
3098 extra += 3
3099
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003100 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003101
3102 # at this stage, ans should round correctly with *any*
3103 # rounding mode, not just with ROUND_HALF_EVEN
3104 context = context._shallow_copy()
3105 rounding = context._set_rounding(ROUND_HALF_EVEN)
3106 ans = ans._fix(context)
3107 context.rounding = rounding
3108
3109 return ans
3110
3111 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003112 """Return True if self is canonical; otherwise return False.
3113
3114 Currently, the encoding of a Decimal instance is always
3115 canonical, so this method returns True for any Decimal.
3116 """
3117 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003118
3119 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003120 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003121
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003122 A Decimal instance is considered finite if it is neither
3123 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003124 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003125 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003126
3127 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003128 """Return True if self is infinite; otherwise return False."""
3129 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003130
3131 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003132 """Return True if self is a qNaN or sNaN; otherwise return False."""
3133 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003134
3135 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003136 """Return True if self is a normal number; otherwise return False."""
3137 if self._is_special or not self:
3138 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003139 if context is None:
3140 context = getcontext()
Mark Dickinson06bb6742009-10-20 13:38:04 +00003141 return context.Emin <= self.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003142
3143 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003144 """Return True if self is a quiet NaN; otherwise return False."""
3145 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003146
3147 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003148 """Return True if self is negative; otherwise return False."""
3149 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003150
3151 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003152 """Return True if self is a signaling NaN; otherwise return False."""
3153 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003154
3155 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003156 """Return True if self is subnormal; otherwise return False."""
3157 if self._is_special or not self:
3158 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003159 if context is None:
3160 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003161 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003162
3163 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003164 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003165 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003166
3167 def _ln_exp_bound(self):
3168 """Compute a lower bound for the adjusted exponent of self.ln().
3169 In other words, compute r such that self.ln() >= 10**r. Assumes
3170 that self is finite and positive and that self != 1.
3171 """
3172
3173 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
3174 adj = self._exp + len(self._int) - 1
3175 if adj >= 1:
3176 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
3177 return len(str(adj*23//10)) - 1
3178 if adj <= -2:
3179 # argument <= 0.1
3180 return len(str((-1-adj)*23//10)) - 1
3181 op = _WorkRep(self)
3182 c, e = op.int, op.exp
3183 if adj == 0:
3184 # 1 < self < 10
3185 num = str(c-10**-e)
3186 den = str(c)
3187 return len(num) - len(den) - (num < den)
3188 # adj == -1, 0.1 <= self < 1
3189 return e + len(str(10**-e - c)) - 1
3190
3191
3192 def ln(self, context=None):
3193 """Returns the natural (base e) logarithm of self."""
3194
3195 if context is None:
3196 context = getcontext()
3197
3198 # ln(NaN) = NaN
3199 ans = self._check_nans(context=context)
3200 if ans:
3201 return ans
3202
3203 # ln(0.0) == -Infinity
3204 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003205 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003206
3207 # ln(Infinity) = Infinity
3208 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003209 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003210
3211 # ln(1.0) == 0.0
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003212 if self == _One:
3213 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003214
3215 # ln(negative) raises InvalidOperation
3216 if self._sign == 1:
3217 return context._raise_error(InvalidOperation,
3218 'ln of a negative value')
3219
3220 # result is irrational, so necessarily inexact
3221 op = _WorkRep(self)
3222 c, e = op.int, op.exp
3223 p = context.prec
3224
3225 # correctly rounded result: repeatedly increase precision by 3
3226 # until we get an unambiguously roundable result
3227 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3228 while True:
3229 coeff = _dlog(c, e, places)
3230 # assert len(str(abs(coeff)))-p >= 1
3231 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3232 break
3233 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003234 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003235
3236 context = context._shallow_copy()
3237 rounding = context._set_rounding(ROUND_HALF_EVEN)
3238 ans = ans._fix(context)
3239 context.rounding = rounding
3240 return ans
3241
3242 def _log10_exp_bound(self):
3243 """Compute a lower bound for the adjusted exponent of self.log10().
3244 In other words, find r such that self.log10() >= 10**r.
3245 Assumes that self is finite and positive and that self != 1.
3246 """
3247
3248 # For x >= 10 or x < 0.1 we only need a bound on the integer
3249 # part of log10(self), and this comes directly from the
3250 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3251 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3252 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3253
3254 adj = self._exp + len(self._int) - 1
3255 if adj >= 1:
3256 # self >= 10
3257 return len(str(adj))-1
3258 if adj <= -2:
3259 # self < 0.1
3260 return len(str(-1-adj))-1
3261 op = _WorkRep(self)
3262 c, e = op.int, op.exp
3263 if adj == 0:
3264 # 1 < self < 10
3265 num = str(c-10**-e)
3266 den = str(231*c)
3267 return len(num) - len(den) - (num < den) + 2
3268 # adj == -1, 0.1 <= self < 1
3269 num = str(10**-e-c)
3270 return len(num) + e - (num < "231") - 1
3271
3272 def log10(self, context=None):
3273 """Returns the base 10 logarithm of self."""
3274
3275 if context is None:
3276 context = getcontext()
3277
3278 # log10(NaN) = NaN
3279 ans = self._check_nans(context=context)
3280 if ans:
3281 return ans
3282
3283 # log10(0.0) == -Infinity
3284 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003285 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003286
3287 # log10(Infinity) = Infinity
3288 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003289 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003290
3291 # log10(negative or -Infinity) raises InvalidOperation
3292 if self._sign == 1:
3293 return context._raise_error(InvalidOperation,
3294 'log10 of a negative value')
3295
3296 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003297 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003298 # answer may need rounding
3299 ans = Decimal(self._exp + len(self._int) - 1)
3300 else:
3301 # result is irrational, so necessarily inexact
3302 op = _WorkRep(self)
3303 c, e = op.int, op.exp
3304 p = context.prec
3305
3306 # correctly rounded result: repeatedly increase precision
3307 # until result is unambiguously roundable
3308 places = p-self._log10_exp_bound()+2
3309 while True:
3310 coeff = _dlog10(c, e, places)
3311 # assert len(str(abs(coeff)))-p >= 1
3312 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3313 break
3314 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003315 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003316
3317 context = context._shallow_copy()
3318 rounding = context._set_rounding(ROUND_HALF_EVEN)
3319 ans = ans._fix(context)
3320 context.rounding = rounding
3321 return ans
3322
3323 def logb(self, context=None):
3324 """ Returns the exponent of the magnitude of self's MSD.
3325
3326 The result is the integer which is the exponent of the magnitude
3327 of the most significant digit of self (as though it were truncated
3328 to a single digit while maintaining the value of that digit and
3329 without limiting the resulting exponent).
3330 """
3331 # logb(NaN) = NaN
3332 ans = self._check_nans(context=context)
3333 if ans:
3334 return ans
3335
3336 if context is None:
3337 context = getcontext()
3338
3339 # logb(+/-Inf) = +Inf
3340 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003341 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003342
3343 # logb(0) = -Inf, DivisionByZero
3344 if not self:
3345 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3346
3347 # otherwise, simply return the adjusted exponent of self, as a
3348 # Decimal. Note that no attempt is made to fit the result
3349 # into the current context.
Mark Dickinson56df8872009-10-07 19:23:50 +00003350 ans = Decimal(self.adjusted())
3351 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003352
3353 def _islogical(self):
3354 """Return True if self is a logical operand.
3355
Christian Heimes679db4a2008-01-18 09:56:22 +00003356 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003357 an exponent of 0, and a coefficient whose digits must all be
3358 either 0 or 1.
3359 """
3360 if self._sign != 0 or self._exp != 0:
3361 return False
3362 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003363 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003364 return False
3365 return True
3366
3367 def _fill_logical(self, context, opa, opb):
3368 dif = context.prec - len(opa)
3369 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003370 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003371 elif dif < 0:
3372 opa = opa[-context.prec:]
3373 dif = context.prec - len(opb)
3374 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003375 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003376 elif dif < 0:
3377 opb = opb[-context.prec:]
3378 return opa, opb
3379
3380 def logical_and(self, other, context=None):
3381 """Applies an 'and' operation between self and other's digits."""
3382 if context is None:
3383 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003384
3385 other = _convert_other(other, raiseit=True)
3386
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003387 if not self._islogical() or not other._islogical():
3388 return context._raise_error(InvalidOperation)
3389
3390 # fill to context.prec
3391 (opa, opb) = self._fill_logical(context, self._int, other._int)
3392
3393 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003394 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3395 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003396
3397 def logical_invert(self, context=None):
3398 """Invert all its digits."""
3399 if context is None:
3400 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003401 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3402 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003403
3404 def logical_or(self, other, context=None):
3405 """Applies an 'or' operation between self and other's digits."""
3406 if context is None:
3407 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003408
3409 other = _convert_other(other, raiseit=True)
3410
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003411 if not self._islogical() or not other._islogical():
3412 return context._raise_error(InvalidOperation)
3413
3414 # fill to context.prec
3415 (opa, opb) = self._fill_logical(context, self._int, other._int)
3416
3417 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003418 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003419 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003420
3421 def logical_xor(self, other, context=None):
3422 """Applies an 'xor' operation between self and other's digits."""
3423 if context is None:
3424 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003425
3426 other = _convert_other(other, raiseit=True)
3427
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003428 if not self._islogical() or not other._islogical():
3429 return context._raise_error(InvalidOperation)
3430
3431 # fill to context.prec
3432 (opa, opb) = self._fill_logical(context, self._int, other._int)
3433
3434 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003435 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003436 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003437
3438 def max_mag(self, other, context=None):
3439 """Compares the values numerically with their sign ignored."""
3440 other = _convert_other(other, raiseit=True)
3441
3442 if context is None:
3443 context = getcontext()
3444
3445 if self._is_special or other._is_special:
3446 # If one operand is a quiet NaN and the other is number, then the
3447 # number is always returned
3448 sn = self._isnan()
3449 on = other._isnan()
3450 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003451 if on == 1 and sn == 0:
3452 return self._fix(context)
3453 if sn == 1 and on == 0:
3454 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003455 return self._check_nans(other, context)
3456
Christian Heimes77c02eb2008-02-09 02:18:51 +00003457 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003458 if c == 0:
3459 c = self.compare_total(other)
3460
3461 if c == -1:
3462 ans = other
3463 else:
3464 ans = self
3465
Christian Heimes2c181612007-12-17 20:04:13 +00003466 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003467
3468 def min_mag(self, other, context=None):
3469 """Compares the values numerically with their sign ignored."""
3470 other = _convert_other(other, raiseit=True)
3471
3472 if context is None:
3473 context = getcontext()
3474
3475 if self._is_special or other._is_special:
3476 # If one operand is a quiet NaN and the other is number, then the
3477 # number is always returned
3478 sn = self._isnan()
3479 on = other._isnan()
3480 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003481 if on == 1 and sn == 0:
3482 return self._fix(context)
3483 if sn == 1 and on == 0:
3484 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003485 return self._check_nans(other, context)
3486
Christian Heimes77c02eb2008-02-09 02:18:51 +00003487 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003488 if c == 0:
3489 c = self.compare_total(other)
3490
3491 if c == -1:
3492 ans = self
3493 else:
3494 ans = other
3495
Christian Heimes2c181612007-12-17 20:04:13 +00003496 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003497
3498 def next_minus(self, context=None):
3499 """Returns the largest representable number smaller than itself."""
3500 if context is None:
3501 context = getcontext()
3502
3503 ans = self._check_nans(context=context)
3504 if ans:
3505 return ans
3506
3507 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003508 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003509 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003510 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003511
3512 context = context.copy()
3513 context._set_rounding(ROUND_FLOOR)
3514 context._ignore_all_flags()
3515 new_self = self._fix(context)
3516 if new_self != self:
3517 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003518 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3519 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003520
3521 def next_plus(self, context=None):
3522 """Returns the smallest representable number larger than itself."""
3523 if context is None:
3524 context = getcontext()
3525
3526 ans = self._check_nans(context=context)
3527 if ans:
3528 return ans
3529
3530 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003531 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003532 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003533 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003534
3535 context = context.copy()
3536 context._set_rounding(ROUND_CEILING)
3537 context._ignore_all_flags()
3538 new_self = self._fix(context)
3539 if new_self != self:
3540 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003541 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3542 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003543
3544 def next_toward(self, other, context=None):
3545 """Returns the number closest to self, in the direction towards other.
3546
3547 The result is the closest representable number to self
3548 (excluding self) that is in the direction towards other,
3549 unless both have the same value. If the two operands are
3550 numerically equal, then the result is a copy of self with the
3551 sign set to be the same as the sign of other.
3552 """
3553 other = _convert_other(other, raiseit=True)
3554
3555 if context is None:
3556 context = getcontext()
3557
3558 ans = self._check_nans(other, context)
3559 if ans:
3560 return ans
3561
Christian Heimes77c02eb2008-02-09 02:18:51 +00003562 comparison = self._cmp(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003563 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003564 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003565
3566 if comparison == -1:
3567 ans = self.next_plus(context)
3568 else: # comparison == 1
3569 ans = self.next_minus(context)
3570
3571 # decide which flags to raise using value of ans
3572 if ans._isinfinity():
3573 context._raise_error(Overflow,
3574 'Infinite result from next_toward',
3575 ans._sign)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003576 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00003577 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003578 elif ans.adjusted() < context.Emin:
3579 context._raise_error(Underflow)
3580 context._raise_error(Subnormal)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003581 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00003582 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003583 # if precision == 1 then we don't raise Clamped for a
3584 # result 0E-Etiny.
3585 if not ans:
3586 context._raise_error(Clamped)
3587
3588 return ans
3589
3590 def number_class(self, context=None):
3591 """Returns an indication of the class of self.
3592
3593 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003594 sNaN
3595 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003596 -Infinity
3597 -Normal
3598 -Subnormal
3599 -Zero
3600 +Zero
3601 +Subnormal
3602 +Normal
3603 +Infinity
3604 """
3605 if self.is_snan():
3606 return "sNaN"
3607 if self.is_qnan():
3608 return "NaN"
3609 inf = self._isinfinity()
3610 if inf == 1:
3611 return "+Infinity"
3612 if inf == -1:
3613 return "-Infinity"
3614 if self.is_zero():
3615 if self._sign:
3616 return "-Zero"
3617 else:
3618 return "+Zero"
3619 if context is None:
3620 context = getcontext()
3621 if self.is_subnormal(context=context):
3622 if self._sign:
3623 return "-Subnormal"
3624 else:
3625 return "+Subnormal"
3626 # just a normal, regular, boring number, :)
3627 if self._sign:
3628 return "-Normal"
3629 else:
3630 return "+Normal"
3631
3632 def radix(self):
3633 """Just returns 10, as this is Decimal, :)"""
3634 return Decimal(10)
3635
3636 def rotate(self, other, context=None):
3637 """Returns a rotated copy of self, value-of-other times."""
3638 if context is None:
3639 context = getcontext()
3640
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003641 other = _convert_other(other, raiseit=True)
3642
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003643 ans = self._check_nans(other, context)
3644 if ans:
3645 return ans
3646
3647 if other._exp != 0:
3648 return context._raise_error(InvalidOperation)
3649 if not (-context.prec <= int(other) <= context.prec):
3650 return context._raise_error(InvalidOperation)
3651
3652 if self._isinfinity():
3653 return Decimal(self)
3654
3655 # get values, pad if necessary
3656 torot = int(other)
3657 rotdig = self._int
3658 topad = context.prec - len(rotdig)
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003659 if topad > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003660 rotdig = '0'*topad + rotdig
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003661 elif topad < 0:
3662 rotdig = rotdig[-topad:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003663
3664 # let's rotate!
3665 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003666 return _dec_from_triple(self._sign,
3667 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003668
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003669 def scaleb(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003670 """Returns self operand after adding the second value to its exp."""
3671 if context is None:
3672 context = getcontext()
3673
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003674 other = _convert_other(other, raiseit=True)
3675
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003676 ans = self._check_nans(other, context)
3677 if ans:
3678 return ans
3679
3680 if other._exp != 0:
3681 return context._raise_error(InvalidOperation)
3682 liminf = -2 * (context.Emax + context.prec)
3683 limsup = 2 * (context.Emax + context.prec)
3684 if not (liminf <= int(other) <= limsup):
3685 return context._raise_error(InvalidOperation)
3686
3687 if self._isinfinity():
3688 return Decimal(self)
3689
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003690 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003691 d = d._fix(context)
3692 return d
3693
3694 def shift(self, other, context=None):
3695 """Returns a shifted copy of self, value-of-other times."""
3696 if context is None:
3697 context = getcontext()
3698
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003699 other = _convert_other(other, raiseit=True)
3700
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003701 ans = self._check_nans(other, context)
3702 if ans:
3703 return ans
3704
3705 if other._exp != 0:
3706 return context._raise_error(InvalidOperation)
3707 if not (-context.prec <= int(other) <= context.prec):
3708 return context._raise_error(InvalidOperation)
3709
3710 if self._isinfinity():
3711 return Decimal(self)
3712
3713 # get values, pad if necessary
3714 torot = int(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003715 rotdig = self._int
3716 topad = context.prec - len(rotdig)
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003717 if topad > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003718 rotdig = '0'*topad + rotdig
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003719 elif topad < 0:
3720 rotdig = rotdig[-topad:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003721
3722 # let's shift!
3723 if torot < 0:
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003724 shifted = rotdig[:torot]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003725 else:
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003726 shifted = rotdig + '0'*torot
3727 shifted = shifted[-context.prec:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003728
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003729 return _dec_from_triple(self._sign,
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003730 shifted.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003731
Guido van Rossumd8faa362007-04-27 19:54:29 +00003732 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003733 def __reduce__(self):
3734 return (self.__class__, (str(self),))
3735
3736 def __copy__(self):
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00003737 if type(self) is Decimal:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003738 return self # I'm immutable; therefore I am my own clone
3739 return self.__class__(str(self))
3740
3741 def __deepcopy__(self, memo):
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00003742 if type(self) is Decimal:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003743 return self # My components are also immutable
3744 return self.__class__(str(self))
3745
Mark Dickinson79f52032009-03-17 23:12:51 +00003746 # PEP 3101 support. the _localeconv keyword argument should be
3747 # considered private: it's provided for ease of testing only.
3748 def __format__(self, specifier, context=None, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00003749 """Format a Decimal instance according to the given specifier.
3750
3751 The specifier should be a standard format specifier, with the
3752 form described in PEP 3101. Formatting types 'e', 'E', 'f',
Mark Dickinson79f52032009-03-17 23:12:51 +00003753 'F', 'g', 'G', 'n' and '%' are supported. If the formatting
3754 type is omitted it defaults to 'g' or 'G', depending on the
3755 value of context.capitals.
Christian Heimesf16baeb2008-02-29 14:57:44 +00003756 """
3757
3758 # Note: PEP 3101 says that if the type is not present then
3759 # there should be at least one digit after the decimal point.
3760 # We take the liberty of ignoring this requirement for
3761 # Decimal---it's presumably there to make sure that
3762 # format(float, '') behaves similarly to str(float).
3763 if context is None:
3764 context = getcontext()
3765
Mark Dickinson79f52032009-03-17 23:12:51 +00003766 spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003767
Mark Dickinson79f52032009-03-17 23:12:51 +00003768 # special values don't care about the type or precision
Christian Heimesf16baeb2008-02-29 14:57:44 +00003769 if self._is_special:
Mark Dickinson79f52032009-03-17 23:12:51 +00003770 sign = _format_sign(self._sign, spec)
3771 body = str(self.copy_abs())
3772 return _format_align(sign, body, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003773
3774 # a type of None defaults to 'g' or 'G', depending on context
Christian Heimesf16baeb2008-02-29 14:57:44 +00003775 if spec['type'] is None:
3776 spec['type'] = ['g', 'G'][context.capitals]
Mark Dickinson79f52032009-03-17 23:12:51 +00003777
3778 # if type is '%', adjust exponent of self accordingly
3779 if spec['type'] == '%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003780 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3781
3782 # round if necessary, taking rounding mode from the context
3783 rounding = context.rounding
3784 precision = spec['precision']
3785 if precision is not None:
3786 if spec['type'] in 'eE':
3787 self = self._round(precision+1, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003788 elif spec['type'] in 'fF%':
3789 self = self._rescale(-precision, rounding)
Mark Dickinson79f52032009-03-17 23:12:51 +00003790 elif spec['type'] in 'gG' and len(self._int) > precision:
3791 self = self._round(precision, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003792 # special case: zeros with a positive exponent can't be
3793 # represented in fixed point; rescale them to 0e0.
Mark Dickinson79f52032009-03-17 23:12:51 +00003794 if not self and self._exp > 0 and spec['type'] in 'fF%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003795 self = self._rescale(0, rounding)
3796
3797 # figure out placement of the decimal point
3798 leftdigits = self._exp + len(self._int)
Mark Dickinson79f52032009-03-17 23:12:51 +00003799 if spec['type'] in 'eE':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003800 if not self and precision is not None:
3801 dotplace = 1 - precision
3802 else:
3803 dotplace = 1
Mark Dickinson79f52032009-03-17 23:12:51 +00003804 elif spec['type'] in 'fF%':
3805 dotplace = leftdigits
Christian Heimesf16baeb2008-02-29 14:57:44 +00003806 elif spec['type'] in 'gG':
3807 if self._exp <= 0 and leftdigits > -6:
3808 dotplace = leftdigits
3809 else:
3810 dotplace = 1
3811
Mark Dickinson79f52032009-03-17 23:12:51 +00003812 # find digits before and after decimal point, and get exponent
3813 if dotplace < 0:
3814 intpart = '0'
3815 fracpart = '0'*(-dotplace) + self._int
3816 elif dotplace > len(self._int):
3817 intpart = self._int + '0'*(dotplace-len(self._int))
3818 fracpart = ''
Christian Heimesf16baeb2008-02-29 14:57:44 +00003819 else:
Mark Dickinson79f52032009-03-17 23:12:51 +00003820 intpart = self._int[:dotplace] or '0'
3821 fracpart = self._int[dotplace:]
3822 exp = leftdigits-dotplace
Christian Heimesf16baeb2008-02-29 14:57:44 +00003823
Mark Dickinson79f52032009-03-17 23:12:51 +00003824 # done with the decimal-specific stuff; hand over the rest
3825 # of the formatting to the _format_number function
3826 return _format_number(self._sign, intpart, fracpart, exp, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003827
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003828def _dec_from_triple(sign, coefficient, exponent, special=False):
3829 """Create a decimal instance directly, without any validation,
3830 normalization (e.g. removal of leading zeros) or argument
3831 conversion.
3832
3833 This function is for *internal use only*.
3834 """
3835
3836 self = object.__new__(Decimal)
3837 self._sign = sign
3838 self._int = coefficient
3839 self._exp = exponent
3840 self._is_special = special
3841
3842 return self
3843
Raymond Hettinger82417ca2009-02-03 03:54:28 +00003844# Register Decimal as a kind of Number (an abstract base class).
3845# However, do not register it as Real (because Decimals are not
3846# interoperable with floats).
3847_numbers.Number.register(Decimal)
3848
3849
Guido van Rossumd8faa362007-04-27 19:54:29 +00003850##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003851
Thomas Wouters89f507f2006-12-13 04:49:30 +00003852class _ContextManager(object):
3853 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003854
Thomas Wouters89f507f2006-12-13 04:49:30 +00003855 Sets a copy of the supplied context in __enter__() and restores
3856 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003857 """
3858 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003859 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003860 def __enter__(self):
3861 self.saved_context = getcontext()
3862 setcontext(self.new_context)
3863 return self.new_context
3864 def __exit__(self, t, v, tb):
3865 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003866
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003867class Context(object):
3868 """Contains the context for a Decimal instance.
3869
3870 Contains:
3871 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003872 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003873 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003874 raised when it is caused. Otherwise, a value is
3875 substituted in.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003876 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003877 (Whether or not the trap_enabler is set)
3878 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003879 Emin - Minimum exponent
3880 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003881 capitals - If 1, 1*10^1 is printed as 1E+1.
3882 If 0, printed as 1e1
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00003883 clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003884 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003885
Stefan Krah1919b7e2012-03-21 18:25:23 +01003886 def __init__(self, prec=None, rounding=None, Emin=None, Emax=None,
3887 capitals=None, clamp=None, flags=None, traps=None,
3888 _ignored_flags=None):
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003889 # Set defaults; for everything except flags and _ignored_flags,
3890 # inherit from DefaultContext.
3891 try:
3892 dc = DefaultContext
3893 except NameError:
3894 pass
3895
3896 self.prec = prec if prec is not None else dc.prec
3897 self.rounding = rounding if rounding is not None else dc.rounding
3898 self.Emin = Emin if Emin is not None else dc.Emin
3899 self.Emax = Emax if Emax is not None else dc.Emax
3900 self.capitals = capitals if capitals is not None else dc.capitals
3901 self.clamp = clamp if clamp is not None else dc.clamp
3902
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003903 if _ignored_flags is None:
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003904 self._ignored_flags = []
3905 else:
3906 self._ignored_flags = _ignored_flags
3907
3908 if traps is None:
3909 self.traps = dc.traps.copy()
3910 elif not isinstance(traps, dict):
Stefan Krah1919b7e2012-03-21 18:25:23 +01003911 self.traps = dict((s, int(s in traps)) for s in _signals + traps)
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003912 else:
3913 self.traps = traps
3914
3915 if flags is None:
3916 self.flags = dict.fromkeys(_signals, 0)
3917 elif not isinstance(flags, dict):
Stefan Krah1919b7e2012-03-21 18:25:23 +01003918 self.flags = dict((s, int(s in flags)) for s in _signals + flags)
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003919 else:
3920 self.flags = flags
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003921
Stefan Krah1919b7e2012-03-21 18:25:23 +01003922 def _set_integer_check(self, name, value, vmin, vmax):
3923 if not isinstance(value, int):
3924 raise TypeError("%s must be an integer" % name)
3925 if vmin == '-inf':
3926 if value > vmax:
3927 raise ValueError("%s must be in [%s, %d]. got: %s" % (name, vmin, vmax, value))
3928 elif vmax == 'inf':
3929 if value < vmin:
3930 raise ValueError("%s must be in [%d, %s]. got: %s" % (name, vmin, vmax, value))
3931 else:
3932 if value < vmin or value > vmax:
3933 raise ValueError("%s must be in [%d, %d]. got %s" % (name, vmin, vmax, value))
3934 return object.__setattr__(self, name, value)
3935
3936 def _set_signal_dict(self, name, d):
3937 if not isinstance(d, dict):
3938 raise TypeError("%s must be a signal dict" % d)
3939 for key in d:
3940 if not key in _signals:
3941 raise KeyError("%s is not a valid signal dict" % d)
3942 for key in _signals:
3943 if not key in d:
3944 raise KeyError("%s is not a valid signal dict" % d)
3945 return object.__setattr__(self, name, d)
3946
3947 def __setattr__(self, name, value):
3948 if name == 'prec':
3949 return self._set_integer_check(name, value, 1, 'inf')
3950 elif name == 'Emin':
3951 return self._set_integer_check(name, value, '-inf', 0)
3952 elif name == 'Emax':
3953 return self._set_integer_check(name, value, 0, 'inf')
3954 elif name == 'capitals':
3955 return self._set_integer_check(name, value, 0, 1)
3956 elif name == 'clamp':
3957 return self._set_integer_check(name, value, 0, 1)
3958 elif name == 'rounding':
3959 if not value in _rounding_modes:
3960 # raise TypeError even for strings to have consistency
3961 # among various implementations.
3962 raise TypeError("%s: invalid rounding mode" % value)
3963 return object.__setattr__(self, name, value)
3964 elif name == 'flags' or name == 'traps':
3965 return self._set_signal_dict(name, value)
3966 elif name == '_ignored_flags':
3967 return object.__setattr__(self, name, value)
3968 else:
3969 raise AttributeError(
3970 "'decimal.Context' object has no attribute '%s'" % name)
3971
3972 def __delattr__(self, name):
3973 raise AttributeError("%s cannot be deleted" % name)
3974
3975 # Support for pickling, copy, and deepcopy
3976 def __reduce__(self):
3977 flags = [sig for sig, v in self.flags.items() if v]
3978 traps = [sig for sig, v in self.traps.items() if v]
3979 return (self.__class__,
3980 (self.prec, self.rounding, self.Emin, self.Emax,
3981 self.capitals, self.clamp, flags, traps))
3982
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003983 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003984 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003985 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003986 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00003987 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d, '
3988 'clamp=%(clamp)d'
Guido van Rossumd8faa362007-04-27 19:54:29 +00003989 % vars(self))
3990 names = [f.__name__ for f, v in self.flags.items() if v]
3991 s.append('flags=[' + ', '.join(names) + ']')
3992 names = [t.__name__ for t, v in self.traps.items() if v]
3993 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003994 return ', '.join(s) + ')'
3995
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003996 def clear_flags(self):
3997 """Reset all flags to zero"""
3998 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003999 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00004000
Stefan Krah1919b7e2012-03-21 18:25:23 +01004001 def clear_traps(self):
4002 """Reset all traps to zero"""
4003 for flag in self.traps:
4004 self.traps[flag] = 0
4005
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004006 def _shallow_copy(self):
4007 """Returns a shallow copy from self."""
Stefan Krah1919b7e2012-03-21 18:25:23 +01004008 nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
4009 self.capitals, self.clamp, self.flags, self.traps,
4010 self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004011 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004012
4013 def copy(self):
4014 """Returns a deep copy from self."""
Stefan Krah1919b7e2012-03-21 18:25:23 +01004015 nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
4016 self.capitals, self.clamp,
4017 self.flags.copy(), self.traps.copy(),
4018 self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004019 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004020 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004021
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004022 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004023 """Handles an error
4024
4025 If the flag is in _ignored_flags, returns the default response.
Raymond Hettinger86173da2008-02-01 20:38:12 +00004026 Otherwise, it sets the flag, then, if the corresponding
Stefan Krah2eb4a072010-05-19 15:52:31 +00004027 trap_enabler is set, it reraises the exception. Otherwise, it returns
Raymond Hettinger86173da2008-02-01 20:38:12 +00004028 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004029 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004030 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004031 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00004032 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004033 return error().handle(self, *args)
4034
Raymond Hettinger86173da2008-02-01 20:38:12 +00004035 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00004036 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00004037 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004038 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004039
4040 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00004041 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00004042 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004043
4044 def _ignore_all_flags(self):
4045 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00004046 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004047
4048 def _ignore_flags(self, *flags):
4049 """Ignore the flags, if they are raised"""
4050 # Do not mutate-- This way, copies of a context leave the original
4051 # alone.
4052 self._ignored_flags = (self._ignored_flags + list(flags))
4053 return list(flags)
4054
4055 def _regard_flags(self, *flags):
4056 """Stop ignoring the flags, if they are raised"""
4057 if flags and isinstance(flags[0], (tuple,list)):
4058 flags = flags[0]
4059 for flag in flags:
4060 self._ignored_flags.remove(flag)
4061
Nick Coghland1abd252008-07-15 15:46:38 +00004062 # We inherit object.__hash__, so we must deny this explicitly
4063 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004064
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004065 def Etiny(self):
4066 """Returns Etiny (= Emin - prec + 1)"""
4067 return int(self.Emin - self.prec + 1)
4068
4069 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004070 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004071 return int(self.Emax - self.prec + 1)
4072
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004073 def _set_rounding(self, type):
4074 """Sets the rounding type.
4075
4076 Sets the rounding type, and returns the current (previous)
4077 rounding type. Often used like:
4078
4079 context = context.copy()
4080 # so you don't change the calling context
4081 # if an error occurs in the middle.
4082 rounding = context._set_rounding(ROUND_UP)
4083 val = self.__sub__(other, context=context)
4084 context._set_rounding(rounding)
4085
4086 This will make it round up for that operation.
4087 """
4088 rounding = self.rounding
4089 self.rounding= type
4090 return rounding
4091
Raymond Hettingerfed52962004-07-14 15:41:57 +00004092 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00004093 """Creates a new Decimal instance but using self as context.
4094
4095 This method implements the to-number operation of the
4096 IBM Decimal specification."""
4097
4098 if isinstance(num, str) and num != num.strip():
4099 return self._raise_error(ConversionSyntax,
4100 "no trailing or leading whitespace is "
4101 "permitted.")
4102
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004103 d = Decimal(num, context=self)
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00004104 if d._isnan() and len(d._int) > self.prec - self.clamp:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004105 return self._raise_error(ConversionSyntax,
4106 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00004107 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004108
Raymond Hettinger771ed762009-01-03 19:20:32 +00004109 def create_decimal_from_float(self, f):
4110 """Creates a new Decimal instance from a float but rounding using self
4111 as the context.
4112
4113 >>> context = Context(prec=5, rounding=ROUND_DOWN)
4114 >>> context.create_decimal_from_float(3.1415926535897932)
4115 Decimal('3.1415')
4116 >>> context = Context(prec=5, traps=[Inexact])
4117 >>> context.create_decimal_from_float(3.1415926535897932)
4118 Traceback (most recent call last):
4119 ...
4120 decimal.Inexact: None
4121
4122 """
4123 d = Decimal.from_float(f) # An exact conversion
4124 return d._fix(self) # Apply the context rounding
4125
Guido van Rossumd8faa362007-04-27 19:54:29 +00004126 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004127 def abs(self, a):
4128 """Returns the absolute value of the operand.
4129
4130 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00004131 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004132 the plus operation on the operand.
4133
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004134 >>> ExtendedContext.abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004135 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004136 >>> ExtendedContext.abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004137 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004138 >>> ExtendedContext.abs(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004139 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004140 >>> ExtendedContext.abs(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004141 Decimal('101.5')
Mark Dickinson84230a12010-02-18 14:49:50 +00004142 >>> ExtendedContext.abs(-1)
4143 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004144 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004145 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004146 return a.__abs__(context=self)
4147
4148 def add(self, a, b):
4149 """Return the sum of the two operands.
4150
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004151 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004152 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004153 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004154 Decimal('1.02E+4')
Mark Dickinson84230a12010-02-18 14:49:50 +00004155 >>> ExtendedContext.add(1, Decimal(2))
4156 Decimal('3')
4157 >>> ExtendedContext.add(Decimal(8), 5)
4158 Decimal('13')
4159 >>> ExtendedContext.add(5, 5)
4160 Decimal('10')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004161 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004162 a = _convert_other(a, raiseit=True)
4163 r = a.__add__(b, context=self)
4164 if r is NotImplemented:
4165 raise TypeError("Unable to convert %s to Decimal" % b)
4166 else:
4167 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004168
4169 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00004170 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004171
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004172 def canonical(self, a):
4173 """Returns the same Decimal object.
4174
4175 As we do not have different encodings for the same number, the
4176 received object already is in its canonical form.
4177
4178 >>> ExtendedContext.canonical(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004179 Decimal('2.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004180 """
Stefan Krah1919b7e2012-03-21 18:25:23 +01004181 if not isinstance(a, Decimal):
4182 raise TypeError("canonical requires a Decimal as an argument.")
Stefan Krah040e3112012-12-15 22:33:33 +01004183 return a.canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004184
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004185 def compare(self, a, b):
4186 """Compares values numerically.
4187
4188 If the signs of the operands differ, a value representing each operand
4189 ('-1' if the operand is less than zero, '0' if the operand is zero or
4190 negative zero, or '1' if the operand is greater than zero) is used in
4191 place of that operand for the comparison instead of the actual
4192 operand.
4193
4194 The comparison is then effected by subtracting the second operand from
4195 the first and then returning a value according to the result of the
4196 subtraction: '-1' if the result is less than zero, '0' if the result is
4197 zero or negative zero, or '1' if the result is greater than zero.
4198
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004199 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004200 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004201 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004202 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004203 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004204 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004205 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004206 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004207 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004208 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004209 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004210 Decimal('-1')
Mark Dickinson84230a12010-02-18 14:49:50 +00004211 >>> ExtendedContext.compare(1, 2)
4212 Decimal('-1')
4213 >>> ExtendedContext.compare(Decimal(1), 2)
4214 Decimal('-1')
4215 >>> ExtendedContext.compare(1, Decimal(2))
4216 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004217 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004218 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004219 return a.compare(b, context=self)
4220
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004221 def compare_signal(self, a, b):
4222 """Compares the values of the two operands numerically.
4223
4224 It's pretty much like compare(), but all NaNs signal, with signaling
4225 NaNs taking precedence over quiet NaNs.
4226
4227 >>> c = ExtendedContext
4228 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004229 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004230 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004231 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004232 >>> c.flags[InvalidOperation] = 0
4233 >>> print(c.flags[InvalidOperation])
4234 0
4235 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004236 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004237 >>> print(c.flags[InvalidOperation])
4238 1
4239 >>> c.flags[InvalidOperation] = 0
4240 >>> print(c.flags[InvalidOperation])
4241 0
4242 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004243 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004244 >>> print(c.flags[InvalidOperation])
4245 1
Mark Dickinson84230a12010-02-18 14:49:50 +00004246 >>> c.compare_signal(-1, 2)
4247 Decimal('-1')
4248 >>> c.compare_signal(Decimal(-1), 2)
4249 Decimal('-1')
4250 >>> c.compare_signal(-1, Decimal(2))
4251 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004252 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004253 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004254 return a.compare_signal(b, context=self)
4255
4256 def compare_total(self, a, b):
4257 """Compares two operands using their abstract representation.
4258
4259 This is not like the standard compare, which use their numerical
4260 value. Note that a total ordering is defined for all possible abstract
4261 representations.
4262
4263 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004264 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004265 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004266 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004267 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
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.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004270 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004271 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004272 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004273 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004274 Decimal('-1')
Mark Dickinson84230a12010-02-18 14:49:50 +00004275 >>> ExtendedContext.compare_total(1, 2)
4276 Decimal('-1')
4277 >>> ExtendedContext.compare_total(Decimal(1), 2)
4278 Decimal('-1')
4279 >>> ExtendedContext.compare_total(1, Decimal(2))
4280 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004281 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004282 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004283 return a.compare_total(b)
4284
4285 def compare_total_mag(self, a, b):
4286 """Compares two operands using their abstract representation ignoring sign.
4287
4288 Like compare_total, but with operand's sign ignored and assumed to be 0.
4289 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004290 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004291 return a.compare_total_mag(b)
4292
4293 def copy_abs(self, a):
4294 """Returns a copy of the operand with the sign set to 0.
4295
4296 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004297 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004298 >>> ExtendedContext.copy_abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004299 Decimal('100')
Mark Dickinson84230a12010-02-18 14:49:50 +00004300 >>> ExtendedContext.copy_abs(-1)
4301 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004302 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004303 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004304 return a.copy_abs()
4305
4306 def copy_decimal(self, a):
Mark Dickinson84230a12010-02-18 14:49:50 +00004307 """Returns a copy of the decimal object.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004308
4309 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004310 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004311 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004312 Decimal('-1.00')
Mark Dickinson84230a12010-02-18 14:49:50 +00004313 >>> ExtendedContext.copy_decimal(1)
4314 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004315 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004316 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004317 return Decimal(a)
4318
4319 def copy_negate(self, a):
4320 """Returns a copy of the operand with the sign inverted.
4321
4322 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004323 Decimal('-101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004324 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004325 Decimal('101.5')
Mark Dickinson84230a12010-02-18 14:49:50 +00004326 >>> ExtendedContext.copy_negate(1)
4327 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004328 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004329 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004330 return a.copy_negate()
4331
4332 def copy_sign(self, a, b):
4333 """Copies the second operand's sign to the first one.
4334
4335 In detail, it returns a copy of the first operand with the sign
4336 equal to the sign of the second operand.
4337
4338 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004339 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004340 >>> 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')
Mark Dickinson84230a12010-02-18 14:49:50 +00004346 >>> ExtendedContext.copy_sign(1, -2)
4347 Decimal('-1')
4348 >>> ExtendedContext.copy_sign(Decimal(1), -2)
4349 Decimal('-1')
4350 >>> ExtendedContext.copy_sign(1, Decimal(-2))
4351 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004352 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004353 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004354 return a.copy_sign(b)
4355
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004356 def divide(self, a, b):
4357 """Decimal division in a specified context.
4358
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004359 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004360 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004361 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004362 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004363 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004364 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004365 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004366 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004367 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004368 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004369 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004370 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004371 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004372 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004373 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004374 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004375 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004376 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004377 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004378 Decimal('1.20E+6')
Mark Dickinson84230a12010-02-18 14:49:50 +00004379 >>> ExtendedContext.divide(5, 5)
4380 Decimal('1')
4381 >>> ExtendedContext.divide(Decimal(5), 5)
4382 Decimal('1')
4383 >>> ExtendedContext.divide(5, Decimal(5))
4384 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004385 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004386 a = _convert_other(a, raiseit=True)
4387 r = a.__truediv__(b, context=self)
4388 if r is NotImplemented:
4389 raise TypeError("Unable to convert %s to Decimal" % b)
4390 else:
4391 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004392
4393 def divide_int(self, a, b):
4394 """Divides two numbers and returns the integer part of the result.
4395
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004396 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004397 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004398 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004399 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004400 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004401 Decimal('3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004402 >>> ExtendedContext.divide_int(10, 3)
4403 Decimal('3')
4404 >>> ExtendedContext.divide_int(Decimal(10), 3)
4405 Decimal('3')
4406 >>> ExtendedContext.divide_int(10, Decimal(3))
4407 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004408 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004409 a = _convert_other(a, raiseit=True)
4410 r = a.__floordiv__(b, context=self)
4411 if r is NotImplemented:
4412 raise TypeError("Unable to convert %s to Decimal" % b)
4413 else:
4414 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004415
4416 def divmod(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004417 """Return (a // b, a % b).
Mark Dickinsonc53796e2010-01-06 16:22:15 +00004418
4419 >>> ExtendedContext.divmod(Decimal(8), Decimal(3))
4420 (Decimal('2'), Decimal('2'))
4421 >>> ExtendedContext.divmod(Decimal(8), Decimal(4))
4422 (Decimal('2'), Decimal('0'))
Mark Dickinson84230a12010-02-18 14:49:50 +00004423 >>> ExtendedContext.divmod(8, 4)
4424 (Decimal('2'), Decimal('0'))
4425 >>> ExtendedContext.divmod(Decimal(8), 4)
4426 (Decimal('2'), Decimal('0'))
4427 >>> ExtendedContext.divmod(8, Decimal(4))
4428 (Decimal('2'), Decimal('0'))
Mark Dickinsonc53796e2010-01-06 16:22:15 +00004429 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004430 a = _convert_other(a, raiseit=True)
4431 r = a.__divmod__(b, context=self)
4432 if r is NotImplemented:
4433 raise TypeError("Unable to convert %s to Decimal" % b)
4434 else:
4435 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004436
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004437 def exp(self, a):
4438 """Returns e ** a.
4439
4440 >>> c = ExtendedContext.copy()
4441 >>> c.Emin = -999
4442 >>> c.Emax = 999
4443 >>> c.exp(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004444 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004445 >>> c.exp(Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004446 Decimal('0.367879441')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004447 >>> c.exp(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004448 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004449 >>> c.exp(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004450 Decimal('2.71828183')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004451 >>> c.exp(Decimal('0.693147181'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004452 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004453 >>> c.exp(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004454 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004455 >>> c.exp(10)
4456 Decimal('22026.4658')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004457 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004458 a =_convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004459 return a.exp(context=self)
4460
4461 def fma(self, a, b, c):
4462 """Returns a multiplied by b, plus c.
4463
4464 The first two operands are multiplied together, using multiply,
4465 the third operand is then added to the result of that
4466 multiplication, using add, all with only one final rounding.
4467
4468 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004469 Decimal('22')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004470 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004471 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004472 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004473 Decimal('1.38435736E+12')
Mark Dickinson84230a12010-02-18 14:49:50 +00004474 >>> ExtendedContext.fma(1, 3, 4)
4475 Decimal('7')
4476 >>> ExtendedContext.fma(1, Decimal(3), 4)
4477 Decimal('7')
4478 >>> ExtendedContext.fma(1, 3, Decimal(4))
4479 Decimal('7')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004480 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004481 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004482 return a.fma(b, c, context=self)
4483
4484 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004485 """Return True if the operand is canonical; otherwise return False.
4486
4487 Currently, the encoding of a Decimal instance is always
4488 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004489
4490 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004491 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004492 """
Stefan Krah1919b7e2012-03-21 18:25:23 +01004493 if not isinstance(a, Decimal):
4494 raise TypeError("is_canonical requires a Decimal as an argument.")
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004495 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004496
4497 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004498 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004499
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004500 A Decimal instance is considered finite if it is neither
4501 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004502
4503 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004504 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004505 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004506 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004507 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004508 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004509 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004510 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004511 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004512 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004513 >>> ExtendedContext.is_finite(1)
4514 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004515 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004516 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004517 return a.is_finite()
4518
4519 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004520 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004521
4522 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004523 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004524 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004525 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004526 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004527 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004528 >>> ExtendedContext.is_infinite(1)
4529 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004530 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004531 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004532 return a.is_infinite()
4533
4534 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004535 """Return True if the operand is a qNaN or sNaN;
4536 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004537
4538 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004539 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004540 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004541 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004542 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004543 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004544 >>> ExtendedContext.is_nan(1)
4545 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004546 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004547 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004548 return a.is_nan()
4549
4550 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004551 """Return True if the operand is a normal number;
4552 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004553
4554 >>> c = ExtendedContext.copy()
4555 >>> c.Emin = -999
4556 >>> c.Emax = 999
4557 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004558 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004559 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004560 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004561 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004562 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004563 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004564 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004565 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004566 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004567 >>> c.is_normal(1)
4568 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004569 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004570 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004571 return a.is_normal(context=self)
4572
4573 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004574 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004575
4576 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004577 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004578 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004579 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004580 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004581 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004582 >>> ExtendedContext.is_qnan(1)
4583 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004584 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004585 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004586 return a.is_qnan()
4587
4588 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004589 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004590
4591 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004592 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004593 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004594 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004595 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004596 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004597 >>> ExtendedContext.is_signed(8)
4598 False
4599 >>> ExtendedContext.is_signed(-8)
4600 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004601 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004602 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004603 return a.is_signed()
4604
4605 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004606 """Return True if the operand is a signaling NaN;
4607 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004608
4609 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004610 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004611 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004612 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004613 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004614 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004615 >>> ExtendedContext.is_snan(1)
4616 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004617 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004618 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004619 return a.is_snan()
4620
4621 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004622 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004623
4624 >>> c = ExtendedContext.copy()
4625 >>> c.Emin = -999
4626 >>> c.Emax = 999
4627 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004628 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004629 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004630 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004631 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004632 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004633 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004634 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004635 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004636 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004637 >>> c.is_subnormal(1)
4638 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004639 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004640 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004641 return a.is_subnormal(context=self)
4642
4643 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004644 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004645
4646 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004647 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004648 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004649 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004650 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004651 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004652 >>> ExtendedContext.is_zero(1)
4653 False
4654 >>> ExtendedContext.is_zero(0)
4655 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004656 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004657 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004658 return a.is_zero()
4659
4660 def ln(self, a):
4661 """Returns the natural (base e) logarithm of the operand.
4662
4663 >>> c = ExtendedContext.copy()
4664 >>> c.Emin = -999
4665 >>> c.Emax = 999
4666 >>> c.ln(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004667 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004668 >>> c.ln(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004669 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004670 >>> c.ln(Decimal('2.71828183'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004671 Decimal('1.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004672 >>> c.ln(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004673 Decimal('2.30258509')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004674 >>> c.ln(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004675 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004676 >>> c.ln(1)
4677 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004678 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004679 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004680 return a.ln(context=self)
4681
4682 def log10(self, a):
4683 """Returns the base 10 logarithm of the operand.
4684
4685 >>> c = ExtendedContext.copy()
4686 >>> c.Emin = -999
4687 >>> c.Emax = 999
4688 >>> c.log10(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004689 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004690 >>> c.log10(Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004691 Decimal('-3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004692 >>> c.log10(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004693 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004694 >>> c.log10(Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004695 Decimal('0.301029996')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004696 >>> c.log10(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004697 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004698 >>> c.log10(Decimal('70'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004699 Decimal('1.84509804')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004700 >>> c.log10(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004701 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004702 >>> c.log10(0)
4703 Decimal('-Infinity')
4704 >>> c.log10(1)
4705 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004706 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004707 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004708 return a.log10(context=self)
4709
4710 def logb(self, a):
4711 """ Returns the exponent of the magnitude of the operand's MSD.
4712
4713 The result is the integer which is the exponent of the magnitude
4714 of the most significant digit of the operand (as though the
4715 operand were truncated to a single digit while maintaining the
4716 value of that digit and without limiting the resulting exponent).
4717
4718 >>> ExtendedContext.logb(Decimal('250'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004719 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004720 >>> ExtendedContext.logb(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004721 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004722 >>> ExtendedContext.logb(Decimal('0.03'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004723 Decimal('-2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004724 >>> ExtendedContext.logb(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004725 Decimal('-Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004726 >>> ExtendedContext.logb(1)
4727 Decimal('0')
4728 >>> ExtendedContext.logb(10)
4729 Decimal('1')
4730 >>> ExtendedContext.logb(100)
4731 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004732 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004733 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004734 return a.logb(context=self)
4735
4736 def logical_and(self, a, b):
4737 """Applies the logical operation 'and' between each operand's digits.
4738
4739 The operands must be both logical numbers.
4740
4741 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004742 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004743 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004744 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004745 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004746 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004747 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004748 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004749 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004750 Decimal('1000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004751 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004752 Decimal('10')
Mark Dickinson84230a12010-02-18 14:49:50 +00004753 >>> ExtendedContext.logical_and(110, 1101)
4754 Decimal('100')
4755 >>> ExtendedContext.logical_and(Decimal(110), 1101)
4756 Decimal('100')
4757 >>> ExtendedContext.logical_and(110, Decimal(1101))
4758 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004759 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004760 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004761 return a.logical_and(b, context=self)
4762
4763 def logical_invert(self, a):
4764 """Invert all the digits in the operand.
4765
4766 The operand must be a logical number.
4767
4768 >>> ExtendedContext.logical_invert(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004769 Decimal('111111111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004770 >>> ExtendedContext.logical_invert(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004771 Decimal('111111110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004772 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004773 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004774 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004775 Decimal('10101010')
Mark Dickinson84230a12010-02-18 14:49:50 +00004776 >>> ExtendedContext.logical_invert(1101)
4777 Decimal('111110010')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004778 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004779 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004780 return a.logical_invert(context=self)
4781
4782 def logical_or(self, a, b):
4783 """Applies the logical operation 'or' between each operand's digits.
4784
4785 The operands must be both logical numbers.
4786
4787 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004788 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004789 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004790 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004791 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004792 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004793 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004794 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004795 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004796 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004797 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004798 Decimal('1110')
Mark Dickinson84230a12010-02-18 14:49:50 +00004799 >>> ExtendedContext.logical_or(110, 1101)
4800 Decimal('1111')
4801 >>> ExtendedContext.logical_or(Decimal(110), 1101)
4802 Decimal('1111')
4803 >>> ExtendedContext.logical_or(110, Decimal(1101))
4804 Decimal('1111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004805 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004806 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004807 return a.logical_or(b, context=self)
4808
4809 def logical_xor(self, a, b):
4810 """Applies the logical operation 'xor' between each operand's digits.
4811
4812 The operands must be both logical numbers.
4813
4814 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004815 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004816 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004817 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004818 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004819 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004820 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004821 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004822 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004823 Decimal('110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004824 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004825 Decimal('1101')
Mark Dickinson84230a12010-02-18 14:49:50 +00004826 >>> ExtendedContext.logical_xor(110, 1101)
4827 Decimal('1011')
4828 >>> ExtendedContext.logical_xor(Decimal(110), 1101)
4829 Decimal('1011')
4830 >>> ExtendedContext.logical_xor(110, Decimal(1101))
4831 Decimal('1011')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004832 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004833 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004834 return a.logical_xor(b, context=self)
4835
Mark Dickinson84230a12010-02-18 14:49:50 +00004836 def max(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004837 """max compares two values numerically and returns the maximum.
4838
4839 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004840 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004841 operation. If they are numerically equal then the left-hand operand
4842 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004843 infinity) of the two operands is chosen as the result.
4844
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004845 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004846 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004847 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004848 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004849 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004850 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004851 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004852 Decimal('7')
Mark Dickinson84230a12010-02-18 14:49:50 +00004853 >>> ExtendedContext.max(1, 2)
4854 Decimal('2')
4855 >>> ExtendedContext.max(Decimal(1), 2)
4856 Decimal('2')
4857 >>> ExtendedContext.max(1, Decimal(2))
4858 Decimal('2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004859 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004860 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004861 return a.max(b, context=self)
4862
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004863 def max_mag(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004864 """Compares the values numerically with their sign ignored.
4865
4866 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
4867 Decimal('7')
4868 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
4869 Decimal('-10')
4870 >>> ExtendedContext.max_mag(1, -2)
4871 Decimal('-2')
4872 >>> ExtendedContext.max_mag(Decimal(1), -2)
4873 Decimal('-2')
4874 >>> ExtendedContext.max_mag(1, Decimal(-2))
4875 Decimal('-2')
4876 """
4877 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004878 return a.max_mag(b, context=self)
4879
Mark Dickinson84230a12010-02-18 14:49:50 +00004880 def min(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004881 """min compares two values numerically and returns the minimum.
4882
4883 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004884 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004885 operation. If they are numerically equal then the left-hand operand
4886 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004887 infinity) of the two operands is chosen as the result.
4888
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004889 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004890 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004891 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004892 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004893 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004894 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004895 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004896 Decimal('7')
Mark Dickinson84230a12010-02-18 14:49:50 +00004897 >>> ExtendedContext.min(1, 2)
4898 Decimal('1')
4899 >>> ExtendedContext.min(Decimal(1), 2)
4900 Decimal('1')
4901 >>> ExtendedContext.min(1, Decimal(29))
4902 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004903 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004904 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004905 return a.min(b, context=self)
4906
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004907 def min_mag(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004908 """Compares the values numerically with their sign ignored.
4909
4910 >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2'))
4911 Decimal('-2')
4912 >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN'))
4913 Decimal('-3')
4914 >>> ExtendedContext.min_mag(1, -2)
4915 Decimal('1')
4916 >>> ExtendedContext.min_mag(Decimal(1), -2)
4917 Decimal('1')
4918 >>> ExtendedContext.min_mag(1, Decimal(-2))
4919 Decimal('1')
4920 """
4921 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004922 return a.min_mag(b, context=self)
4923
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004924 def minus(self, a):
4925 """Minus corresponds to unary prefix minus in Python.
4926
4927 The operation is evaluated using the same rules as subtract; the
4928 operation minus(a) is calculated as subtract('0', a) where the '0'
4929 has the same exponent as the operand.
4930
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004931 >>> ExtendedContext.minus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004932 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004933 >>> ExtendedContext.minus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004934 Decimal('1.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004935 >>> ExtendedContext.minus(1)
4936 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004937 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004938 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004939 return a.__neg__(context=self)
4940
4941 def multiply(self, a, b):
4942 """multiply multiplies two operands.
4943
4944 If either operand is a special value then the general rules apply.
Mark Dickinson84230a12010-02-18 14:49:50 +00004945 Otherwise, the operands are multiplied together
4946 ('long multiplication'), resulting in a number which may be as long as
4947 the sum of the lengths of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004948
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004949 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004950 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004951 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004952 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004953 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004954 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004955 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004956 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004957 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004958 Decimal('4.28135971E+11')
Mark Dickinson84230a12010-02-18 14:49:50 +00004959 >>> ExtendedContext.multiply(7, 7)
4960 Decimal('49')
4961 >>> ExtendedContext.multiply(Decimal(7), 7)
4962 Decimal('49')
4963 >>> ExtendedContext.multiply(7, Decimal(7))
4964 Decimal('49')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004965 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004966 a = _convert_other(a, raiseit=True)
4967 r = a.__mul__(b, context=self)
4968 if r is NotImplemented:
4969 raise TypeError("Unable to convert %s to Decimal" % b)
4970 else:
4971 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004972
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004973 def next_minus(self, a):
4974 """Returns the largest representable number smaller than a.
4975
4976 >>> c = ExtendedContext.copy()
4977 >>> c.Emin = -999
4978 >>> c.Emax = 999
4979 >>> ExtendedContext.next_minus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004980 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004981 >>> c.next_minus(Decimal('1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004982 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004983 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004984 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004985 >>> c.next_minus(Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004986 Decimal('9.99999999E+999')
Mark Dickinson84230a12010-02-18 14:49:50 +00004987 >>> c.next_minus(1)
4988 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004989 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004990 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004991 return a.next_minus(context=self)
4992
4993 def next_plus(self, a):
4994 """Returns the smallest representable number larger than a.
4995
4996 >>> c = ExtendedContext.copy()
4997 >>> c.Emin = -999
4998 >>> c.Emax = 999
4999 >>> ExtendedContext.next_plus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005000 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005001 >>> c.next_plus(Decimal('-1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005002 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005003 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005004 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005005 >>> c.next_plus(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005006 Decimal('-9.99999999E+999')
Mark Dickinson84230a12010-02-18 14:49:50 +00005007 >>> c.next_plus(1)
5008 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005009 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005010 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005011 return a.next_plus(context=self)
5012
5013 def next_toward(self, a, b):
5014 """Returns the number closest to a, in direction towards b.
5015
5016 The result is the closest representable number from the first
5017 operand (but not the first operand) that is in the direction
5018 towards the second operand, unless the operands have the same
5019 value.
5020
5021 >>> c = ExtendedContext.copy()
5022 >>> c.Emin = -999
5023 >>> c.Emax = 999
5024 >>> c.next_toward(Decimal('1'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005025 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005026 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005027 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005028 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005029 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005030 >>> c.next_toward(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005031 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005032 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005033 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005034 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005035 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005036 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005037 Decimal('-0.00')
Mark Dickinson84230a12010-02-18 14:49:50 +00005038 >>> c.next_toward(0, 1)
5039 Decimal('1E-1007')
5040 >>> c.next_toward(Decimal(0), 1)
5041 Decimal('1E-1007')
5042 >>> c.next_toward(0, Decimal(1))
5043 Decimal('1E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005044 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005045 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005046 return a.next_toward(b, context=self)
5047
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005048 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00005049 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005050
5051 Essentially a plus operation with all trailing zeros removed from the
5052 result.
5053
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005054 >>> ExtendedContext.normalize(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005055 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005056 >>> ExtendedContext.normalize(Decimal('-2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005057 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005058 >>> ExtendedContext.normalize(Decimal('1.200'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005059 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005060 >>> ExtendedContext.normalize(Decimal('-120'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005061 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005062 >>> ExtendedContext.normalize(Decimal('120.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005063 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005064 >>> ExtendedContext.normalize(Decimal('0.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005065 Decimal('0')
Mark Dickinson84230a12010-02-18 14:49:50 +00005066 >>> ExtendedContext.normalize(6)
5067 Decimal('6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005068 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005069 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005070 return a.normalize(context=self)
5071
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005072 def number_class(self, a):
5073 """Returns an indication of the class of the operand.
5074
5075 The class is one of the following strings:
5076 -sNaN
5077 -NaN
5078 -Infinity
5079 -Normal
5080 -Subnormal
5081 -Zero
5082 +Zero
5083 +Subnormal
5084 +Normal
5085 +Infinity
5086
Stefan Krah1919b7e2012-03-21 18:25:23 +01005087 >>> c = ExtendedContext.copy()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005088 >>> c.Emin = -999
5089 >>> c.Emax = 999
5090 >>> c.number_class(Decimal('Infinity'))
5091 '+Infinity'
5092 >>> c.number_class(Decimal('1E-10'))
5093 '+Normal'
5094 >>> c.number_class(Decimal('2.50'))
5095 '+Normal'
5096 >>> c.number_class(Decimal('0.1E-999'))
5097 '+Subnormal'
5098 >>> c.number_class(Decimal('0'))
5099 '+Zero'
5100 >>> c.number_class(Decimal('-0'))
5101 '-Zero'
5102 >>> c.number_class(Decimal('-0.1E-999'))
5103 '-Subnormal'
5104 >>> c.number_class(Decimal('-1E-10'))
5105 '-Normal'
5106 >>> c.number_class(Decimal('-2.50'))
5107 '-Normal'
5108 >>> c.number_class(Decimal('-Infinity'))
5109 '-Infinity'
5110 >>> c.number_class(Decimal('NaN'))
5111 'NaN'
5112 >>> c.number_class(Decimal('-NaN'))
5113 'NaN'
5114 >>> c.number_class(Decimal('sNaN'))
5115 'sNaN'
Mark Dickinson84230a12010-02-18 14:49:50 +00005116 >>> c.number_class(123)
5117 '+Normal'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005118 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005119 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005120 return a.number_class(context=self)
5121
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005122 def plus(self, a):
5123 """Plus corresponds to unary prefix plus in Python.
5124
5125 The operation is evaluated using the same rules as add; the
5126 operation plus(a) is calculated as add('0', a) where the '0'
5127 has the same exponent as the operand.
5128
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005129 >>> ExtendedContext.plus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005130 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005131 >>> ExtendedContext.plus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005132 Decimal('-1.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005133 >>> ExtendedContext.plus(-1)
5134 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005135 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005136 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005137 return a.__pos__(context=self)
5138
5139 def power(self, a, b, modulo=None):
5140 """Raises a to the power of b, to modulo if given.
5141
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005142 With two arguments, compute a**b. If a is negative then b
5143 must be integral. The result will be inexact unless b is
5144 integral and the result is finite and can be expressed exactly
5145 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005146
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005147 With three arguments, compute (a**b) % modulo. For the
5148 three argument form, the following restrictions on the
5149 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005150
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005151 - all three arguments must be integral
5152 - b must be nonnegative
5153 - at least one of a or b must be nonzero
5154 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005155
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005156 The result of pow(a, b, modulo) is identical to the result
5157 that would be obtained by computing (a**b) % modulo with
5158 unbounded precision, but is computed more efficiently. It is
5159 always exact.
5160
5161 >>> c = ExtendedContext.copy()
5162 >>> c.Emin = -999
5163 >>> c.Emax = 999
5164 >>> c.power(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005165 Decimal('8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005166 >>> 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('0.125')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005170 >>> c.power(Decimal('1.7'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005171 Decimal('69.7575744')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005172 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005173 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005174 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005175 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005176 >>> c.power(Decimal('Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005177 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005178 >>> c.power(Decimal('Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005179 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005180 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005181 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005182 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005183 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005184 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005185 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005186 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005187 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005188 >>> c.power(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005189 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005190
5191 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005192 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005193 >>> 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('8'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005196 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005197 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005198 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005199 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005200 Decimal('11729830')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005201 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005202 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005203 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005204 Decimal('1')
Mark Dickinson84230a12010-02-18 14:49:50 +00005205 >>> ExtendedContext.power(7, 7)
5206 Decimal('823543')
5207 >>> ExtendedContext.power(Decimal(7), 7)
5208 Decimal('823543')
5209 >>> ExtendedContext.power(7, Decimal(7), 2)
5210 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005211 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005212 a = _convert_other(a, raiseit=True)
5213 r = a.__pow__(b, modulo, context=self)
5214 if r is NotImplemented:
5215 raise TypeError("Unable to convert %s to Decimal" % b)
5216 else:
5217 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005218
5219 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005220 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005221
5222 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00005223 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005224 exponent is being increased), multiplied by a positive power of ten (if
5225 the exponent is being decreased), or is unchanged (if the exponent is
5226 already equal to that of the right-hand operand).
5227
5228 Unlike other operations, if the length of the coefficient after the
5229 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00005230 operation condition is raised. This guarantees that, unless there is
5231 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005232 equal to that of the right-hand operand.
5233
5234 Also unlike other operations, quantize will never raise Underflow, even
5235 if the result is subnormal and inexact.
5236
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005237 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005238 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005239 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005240 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005241 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005242 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005243 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005244 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005245 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005246 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005247 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005248 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005249 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005250 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005251 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005252 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005253 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005254 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005255 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005256 Decimal('NaN')
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('217'), Decimal('1e-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005260 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005261 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005262 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005263 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005264 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005265 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005266 Decimal('2E+2')
Mark Dickinson84230a12010-02-18 14:49:50 +00005267 >>> ExtendedContext.quantize(1, 2)
5268 Decimal('1')
5269 >>> ExtendedContext.quantize(Decimal(1), 2)
5270 Decimal('1')
5271 >>> ExtendedContext.quantize(1, Decimal(2))
5272 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005273 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005274 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005275 return a.quantize(b, context=self)
5276
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005277 def radix(self):
5278 """Just returns 10, as this is Decimal, :)
5279
5280 >>> ExtendedContext.radix()
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005281 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005282 """
5283 return Decimal(10)
5284
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005285 def remainder(self, a, b):
5286 """Returns the remainder from integer division.
5287
5288 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00005289 calculating integer division as described for divide-integer, rounded
5290 to precision digits if necessary. The sign of the result, if
5291 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005292
5293 This operation will fail under the same conditions as integer division
5294 (that is, if integer division on the same two operands would fail, the
5295 remainder cannot be calculated).
5296
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005297 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005298 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005299 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005300 Decimal('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.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005304 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005305 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005306 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005307 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005308 Decimal('1.0')
Mark Dickinson84230a12010-02-18 14:49:50 +00005309 >>> ExtendedContext.remainder(22, 6)
5310 Decimal('4')
5311 >>> ExtendedContext.remainder(Decimal(22), 6)
5312 Decimal('4')
5313 >>> ExtendedContext.remainder(22, Decimal(6))
5314 Decimal('4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005315 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005316 a = _convert_other(a, raiseit=True)
5317 r = a.__mod__(b, context=self)
5318 if r is NotImplemented:
5319 raise TypeError("Unable to convert %s to Decimal" % b)
5320 else:
5321 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005322
5323 def remainder_near(self, a, b):
5324 """Returns to be "a - b * n", where n is the integer nearest the exact
5325 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00005326 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005327 sign of a.
5328
5329 This operation will fail under the same conditions as integer division
5330 (that is, if integer division on the same two operands would fail, the
5331 remainder cannot be calculated).
5332
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005333 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005334 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005335 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005336 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005337 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005338 Decimal('1')
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.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005342 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005343 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005344 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005345 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005346 Decimal('-0.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005347 >>> ExtendedContext.remainder_near(3, 11)
5348 Decimal('3')
5349 >>> ExtendedContext.remainder_near(Decimal(3), 11)
5350 Decimal('3')
5351 >>> ExtendedContext.remainder_near(3, Decimal(11))
5352 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005353 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005354 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005355 return a.remainder_near(b, context=self)
5356
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005357 def rotate(self, a, b):
5358 """Returns a rotated copy of a, b times.
5359
5360 The coefficient of the result is a rotated copy of the digits in
5361 the coefficient of the first operand. The number of places of
5362 rotation is taken from the absolute value of the second operand,
5363 with the rotation being to the left if the second operand is
5364 positive or to the right otherwise.
5365
5366 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005367 Decimal('400000003')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005368 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005369 Decimal('12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005370 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005371 Decimal('891234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005372 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005373 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005374 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005375 Decimal('345678912')
Mark Dickinson84230a12010-02-18 14:49:50 +00005376 >>> ExtendedContext.rotate(1333333, 1)
5377 Decimal('13333330')
5378 >>> ExtendedContext.rotate(Decimal(1333333), 1)
5379 Decimal('13333330')
5380 >>> ExtendedContext.rotate(1333333, Decimal(1))
5381 Decimal('13333330')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005382 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005383 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005384 return a.rotate(b, context=self)
5385
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005386 def same_quantum(self, a, b):
5387 """Returns True if the two operands have the same exponent.
5388
5389 The result is never affected by either the sign or the coefficient of
5390 either operand.
5391
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005392 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005393 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005394 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005395 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005396 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005397 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005398 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005399 True
Mark Dickinson84230a12010-02-18 14:49:50 +00005400 >>> ExtendedContext.same_quantum(10000, -1)
5401 True
5402 >>> ExtendedContext.same_quantum(Decimal(10000), -1)
5403 True
5404 >>> ExtendedContext.same_quantum(10000, Decimal(-1))
5405 True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005406 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005407 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005408 return a.same_quantum(b)
5409
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005410 def scaleb (self, a, b):
5411 """Returns the first operand after adding the second value its exp.
5412
5413 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005414 Decimal('0.0750')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005415 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005416 Decimal('7.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005417 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005418 Decimal('7.50E+3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005419 >>> ExtendedContext.scaleb(1, 4)
5420 Decimal('1E+4')
5421 >>> ExtendedContext.scaleb(Decimal(1), 4)
5422 Decimal('1E+4')
5423 >>> ExtendedContext.scaleb(1, Decimal(4))
5424 Decimal('1E+4')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005425 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005426 a = _convert_other(a, raiseit=True)
5427 return a.scaleb(b, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005428
5429 def shift(self, a, b):
5430 """Returns a shifted copy of a, b times.
5431
5432 The coefficient of the result is a shifted copy of the digits
5433 in the coefficient of the first operand. The number of places
5434 to shift is taken from the absolute value of the second operand,
5435 with the shift being to the left if the second operand is
5436 positive or to the right otherwise. Digits shifted into the
5437 coefficient are zeros.
5438
5439 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005440 Decimal('400000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005441 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005442 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005443 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005444 Decimal('1234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005445 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005446 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005447 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005448 Decimal('345678900')
Mark Dickinson84230a12010-02-18 14:49:50 +00005449 >>> ExtendedContext.shift(88888888, 2)
5450 Decimal('888888800')
5451 >>> ExtendedContext.shift(Decimal(88888888), 2)
5452 Decimal('888888800')
5453 >>> ExtendedContext.shift(88888888, Decimal(2))
5454 Decimal('888888800')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005455 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005456 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005457 return a.shift(b, context=self)
5458
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005459 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005460 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005461
5462 If the result must be inexact, it is rounded using the round-half-even
5463 algorithm.
5464
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005465 >>> ExtendedContext.sqrt(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005466 Decimal('0')
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.39'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005470 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005471 >>> ExtendedContext.sqrt(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005472 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005473 >>> ExtendedContext.sqrt(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005474 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005475 >>> ExtendedContext.sqrt(Decimal('1.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005476 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005477 >>> ExtendedContext.sqrt(Decimal('1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005478 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005479 >>> ExtendedContext.sqrt(Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005480 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005481 >>> ExtendedContext.sqrt(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005482 Decimal('3.16227766')
Mark Dickinson84230a12010-02-18 14:49:50 +00005483 >>> ExtendedContext.sqrt(2)
5484 Decimal('1.41421356')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005485 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005486 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005487 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005488 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005489 return a.sqrt(context=self)
5490
5491 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00005492 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005493
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005494 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005495 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005496 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005497 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005498 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005499 Decimal('-0.77')
Mark Dickinson84230a12010-02-18 14:49:50 +00005500 >>> ExtendedContext.subtract(8, 5)
5501 Decimal('3')
5502 >>> ExtendedContext.subtract(Decimal(8), 5)
5503 Decimal('3')
5504 >>> ExtendedContext.subtract(8, Decimal(5))
5505 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005506 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005507 a = _convert_other(a, raiseit=True)
5508 r = a.__sub__(b, context=self)
5509 if r is NotImplemented:
5510 raise TypeError("Unable to convert %s to Decimal" % b)
5511 else:
5512 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005513
5514 def to_eng_string(self, a):
5515 """Converts a number to a string, using scientific notation.
5516
5517 The operation is not affected by the context.
5518 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005519 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005520 return a.to_eng_string(context=self)
5521
5522 def to_sci_string(self, a):
5523 """Converts a number to a string, using scientific notation.
5524
5525 The operation is not affected by the context.
5526 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005527 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005528 return a.__str__(context=self)
5529
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005530 def to_integral_exact(self, a):
5531 """Rounds to an integer.
5532
5533 When the operand has a negative exponent, the result is the same
5534 as using the quantize() operation using the given operand as the
5535 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5536 of the operand as the precision setting; Inexact and Rounded flags
5537 are allowed in this operation. The rounding mode is taken from the
5538 context.
5539
5540 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005541 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005542 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005543 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005544 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005545 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005546 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005547 Decimal('102')
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('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005551 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005552 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005553 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005554 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005555 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005556 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005557 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005558 return a.to_integral_exact(context=self)
5559
5560 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005561 """Rounds to an integer.
5562
5563 When the operand has a negative exponent, the result is the same
5564 as using the quantize() operation using the given operand as the
5565 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5566 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00005567 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005568
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005569 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005570 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005571 >>> ExtendedContext.to_integral_value(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005572 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005573 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005574 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005575 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005576 Decimal('102')
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('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005580 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005581 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005582 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005583 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005584 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005585 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005586 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005587 return a.to_integral_value(context=self)
5588
5589 # the method name changed, but we provide also the old one, for compatibility
5590 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005591
5592class _WorkRep(object):
5593 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00005594 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005595 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005596 # exp: None, int, or string
5597
5598 def __init__(self, value=None):
5599 if value is None:
5600 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005601 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005602 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00005603 elif isinstance(value, Decimal):
5604 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005605 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005606 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00005607 else:
5608 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005609 self.sign = value[0]
5610 self.int = value[1]
5611 self.exp = value[2]
5612
5613 def __repr__(self):
5614 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5615
5616 __str__ = __repr__
5617
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005618
5619
Christian Heimes2c181612007-12-17 20:04:13 +00005620def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005621 """Normalizes op1, op2 to have the same exp and length of coefficient.
5622
5623 Done during addition.
5624 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005625 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005626 tmp = op2
5627 other = op1
5628 else:
5629 tmp = op1
5630 other = op2
5631
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005632 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5633 # Then adding 10**exp to tmp has the same effect (after rounding)
5634 # as adding any positive quantity smaller than 10**exp; similarly
5635 # for subtraction. So if other is smaller than 10**exp we replace
5636 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00005637 tmp_len = len(str(tmp.int))
5638 other_len = len(str(other.int))
5639 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5640 if other_len + other.exp - 1 < exp:
5641 other.int = 1
5642 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005643
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005644 tmp.int *= 10 ** (tmp.exp - other.exp)
5645 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005646 return op1, op2
5647
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005648##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005649
Raymond Hettingerdb213a22010-11-27 08:09:40 +00005650_nbits = int.bit_length
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005651
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01005652def _decimal_lshift_exact(n, e):
5653 """ Given integers n and e, return n * 10**e if it's an integer, else None.
5654
5655 The computation is designed to avoid computing large powers of 10
5656 unnecessarily.
5657
5658 >>> _decimal_lshift_exact(3, 4)
5659 30000
5660 >>> _decimal_lshift_exact(300, -999999999) # returns None
5661
5662 """
5663 if n == 0:
5664 return 0
5665 elif e >= 0:
5666 return n * 10**e
5667 else:
5668 # val_n = largest power of 10 dividing n.
5669 str_n = str(abs(n))
5670 val_n = len(str_n) - len(str_n.rstrip('0'))
5671 return None if val_n < -e else n // 10**-e
5672
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005673def _sqrt_nearest(n, a):
5674 """Closest integer to the square root of the positive integer n. a is
5675 an initial approximation to the square root. Any positive integer
5676 will do for a, but the closer a is to the square root of n the
5677 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005678
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005679 """
5680 if n <= 0 or a <= 0:
5681 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5682
5683 b=0
5684 while a != b:
5685 b, a = a, a--n//a>>1
5686 return a
5687
5688def _rshift_nearest(x, shift):
5689 """Given an integer x and a nonnegative integer shift, return closest
5690 integer to x / 2**shift; use round-to-even in case of a tie.
5691
5692 """
5693 b, q = 1 << shift, x >> shift
5694 return q + (2*(x & (b-1)) + (q&1) > b)
5695
5696def _div_nearest(a, b):
5697 """Closest integer to a/b, a and b positive integers; rounds to even
5698 in the case of a tie.
5699
5700 """
5701 q, r = divmod(a, b)
5702 return q + (2*r + (q&1) > b)
5703
5704def _ilog(x, M, L = 8):
5705 """Integer approximation to M*log(x/M), with absolute error boundable
5706 in terms only of x/M.
5707
5708 Given positive integers x and M, return an integer approximation to
5709 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5710 between the approximation and the exact result is at most 22. For
5711 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5712 both cases these are upper bounds on the error; it will usually be
5713 much smaller."""
5714
5715 # The basic algorithm is the following: let log1p be the function
5716 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5717 # the reduction
5718 #
5719 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5720 #
5721 # repeatedly until the argument to log1p is small (< 2**-L in
5722 # absolute value). For small y we can use the Taylor series
5723 # expansion
5724 #
5725 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5726 #
5727 # truncating at T such that y**T is small enough. The whole
5728 # computation is carried out in a form of fixed-point arithmetic,
5729 # with a real number z being represented by an integer
5730 # approximation to z*M. To avoid loss of precision, the y below
5731 # is actually an integer approximation to 2**R*y*M, where R is the
5732 # number of reductions performed so far.
5733
5734 y = x-M
5735 # argument reduction; R = number of reductions performed
5736 R = 0
5737 while (R <= L and abs(y) << L-R >= M or
5738 R > L and abs(y) >> R-L >= M):
5739 y = _div_nearest((M*y) << 1,
5740 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5741 R += 1
5742
5743 # Taylor series with T terms
5744 T = -int(-10*len(str(M))//(3*L))
5745 yshift = _rshift_nearest(y, R)
5746 w = _div_nearest(M, T)
5747 for k in range(T-1, 0, -1):
5748 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5749
5750 return _div_nearest(w*y, M)
5751
5752def _dlog10(c, e, p):
5753 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5754 approximation to 10**p * log10(c*10**e), with an absolute error of
5755 at most 1. Assumes that c*10**e is not exactly 1."""
5756
5757 # increase precision by 2; compensate for this by dividing
5758 # final result by 100
5759 p += 2
5760
5761 # write c*10**e as d*10**f with either:
5762 # f >= 0 and 1 <= d <= 10, or
5763 # f <= 0 and 0.1 <= d <= 1.
5764 # Thus for c*10**e close to 1, f = 0
5765 l = len(str(c))
5766 f = e+l - (e+l >= 1)
5767
5768 if p > 0:
5769 M = 10**p
5770 k = e+p-f
5771 if k >= 0:
5772 c *= 10**k
5773 else:
5774 c = _div_nearest(c, 10**-k)
5775
5776 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005777 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005778 log_d = _div_nearest(log_d*M, log_10)
5779 log_tenpower = f*M # exact
5780 else:
5781 log_d = 0 # error < 2.31
Neal Norwitz2f99b242008-08-24 05:48:10 +00005782 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005783
5784 return _div_nearest(log_tenpower+log_d, 100)
5785
5786def _dlog(c, e, p):
5787 """Given integers c, e and p with c > 0, compute an integer
5788 approximation to 10**p * log(c*10**e), with an absolute error of
5789 at most 1. Assumes that c*10**e is not exactly 1."""
5790
5791 # Increase precision by 2. The precision increase is compensated
5792 # for at the end with a division by 100.
5793 p += 2
5794
5795 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5796 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5797 # as 10**p * log(d) + 10**p*f * log(10).
5798 l = len(str(c))
5799 f = e+l - (e+l >= 1)
5800
5801 # compute approximation to 10**p*log(d), with error < 27
5802 if p > 0:
5803 k = e+p-f
5804 if k >= 0:
5805 c *= 10**k
5806 else:
5807 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5808
5809 # _ilog magnifies existing error in c by a factor of at most 10
5810 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5811 else:
5812 # p <= 0: just approximate the whole thing by 0; error < 2.31
5813 log_d = 0
5814
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005815 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005816 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005817 extra = len(str(abs(f)))-1
5818 if p + extra >= 0:
5819 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5820 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5821 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005822 else:
5823 f_log_ten = 0
5824 else:
5825 f_log_ten = 0
5826
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005827 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005828 return _div_nearest(f_log_ten + log_d, 100)
5829
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005830class _Log10Memoize(object):
5831 """Class to compute, store, and allow retrieval of, digits of the
5832 constant log(10) = 2.302585.... This constant is needed by
5833 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5834 def __init__(self):
5835 self.digits = "23025850929940456840179914546843642076011014886"
5836
5837 def getdigits(self, p):
5838 """Given an integer p >= 0, return floor(10**p)*log(10).
5839
5840 For example, self.getdigits(3) returns 2302.
5841 """
5842 # digits are stored as a string, for quick conversion to
5843 # integer in the case that we've already computed enough
5844 # digits; the stored digits should always be correct
5845 # (truncated, not rounded to nearest).
5846 if p < 0:
5847 raise ValueError("p should be nonnegative")
5848
5849 if p >= len(self.digits):
5850 # compute p+3, p+6, p+9, ... digits; continue until at
5851 # least one of the extra digits is nonzero
5852 extra = 3
5853 while True:
5854 # compute p+extra digits, correct to within 1ulp
5855 M = 10**(p+extra+2)
5856 digits = str(_div_nearest(_ilog(10*M, M), 100))
5857 if digits[-extra:] != '0'*extra:
5858 break
5859 extra += 3
5860 # keep all reliable digits so far; remove trailing zeros
5861 # and next nonzero digit
5862 self.digits = digits.rstrip('0')[:-1]
5863 return int(self.digits[:p+1])
5864
5865_log10_digits = _Log10Memoize().getdigits
5866
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005867def _iexp(x, M, L=8):
5868 """Given integers x and M, M > 0, such that x/M is small in absolute
5869 value, compute an integer approximation to M*exp(x/M). For 0 <=
5870 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5871 is usually much smaller)."""
5872
5873 # Algorithm: to compute exp(z) for a real number z, first divide z
5874 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5875 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5876 # series
5877 #
5878 # expm1(x) = x + x**2/2! + x**3/3! + ...
5879 #
5880 # Now use the identity
5881 #
5882 # expm1(2x) = expm1(x)*(expm1(x)+2)
5883 #
5884 # R times to compute the sequence expm1(z/2**R),
5885 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5886
5887 # Find R such that x/2**R/M <= 2**-L
5888 R = _nbits((x<<L)//M)
5889
5890 # Taylor series. (2**L)**T > M
5891 T = -int(-10*len(str(M))//(3*L))
5892 y = _div_nearest(x, T)
5893 Mshift = M<<R
5894 for i in range(T-1, 0, -1):
5895 y = _div_nearest(x*(Mshift + y), Mshift * i)
5896
5897 # Expansion
5898 for k in range(R-1, -1, -1):
5899 Mshift = M<<(k+2)
5900 y = _div_nearest(y*(y+Mshift), Mshift)
5901
5902 return M+y
5903
5904def _dexp(c, e, p):
5905 """Compute an approximation to exp(c*10**e), with p decimal places of
5906 precision.
5907
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005908 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005909
5910 10**(p-1) <= d <= 10**p, and
5911 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5912
5913 In other words, d*10**f is an approximation to exp(c*10**e) with p
5914 digits of precision, and with an error in d of at most 1. This is
5915 almost, but not quite, the same as the error being < 1ulp: when d
5916 = 10**(p-1) the error could be up to 10 ulp."""
5917
5918 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5919 p += 2
5920
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005921 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005922 extra = max(0, e + len(str(c)) - 1)
5923 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005924
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005925 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005926 # rounding down
5927 shift = e+q
5928 if shift >= 0:
5929 cshift = c*10**shift
5930 else:
5931 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005932 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005933
5934 # reduce remainder back to original precision
5935 rem = _div_nearest(rem, 10**extra)
5936
5937 # error in result of _iexp < 120; error after division < 0.62
5938 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5939
5940def _dpower(xc, xe, yc, ye, p):
5941 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5942 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5943
5944 10**(p-1) <= c <= 10**p, and
5945 (c-1)*10**e < x**y < (c+1)*10**e
5946
5947 in other words, c*10**e is an approximation to x**y with p digits
5948 of precision, and with an error in c of at most 1. (This is
5949 almost, but not quite, the same as the error being < 1ulp: when c
5950 == 10**(p-1) we can only guarantee error < 10ulp.)
5951
5952 We assume that: x is positive and not equal to 1, and y is nonzero.
5953 """
5954
5955 # Find b such that 10**(b-1) <= |y| <= 10**b
5956 b = len(str(abs(yc))) + ye
5957
5958 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5959 lxc = _dlog(xc, xe, p+b+1)
5960
5961 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5962 shift = ye-b
5963 if shift >= 0:
5964 pc = lxc*yc*10**shift
5965 else:
5966 pc = _div_nearest(lxc*yc, 10**-shift)
5967
5968 if pc == 0:
5969 # we prefer a result that isn't exactly 1; this makes it
5970 # easier to compute a correctly rounded result in __pow__
5971 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5972 coeff, exp = 10**(p-1)+1, 1-p
5973 else:
5974 coeff, exp = 10**p-1, -p
5975 else:
5976 coeff, exp = _dexp(pc, -(p+1), p+1)
5977 coeff = _div_nearest(coeff, 10)
5978 exp += 1
5979
5980 return coeff, exp
5981
5982def _log10_lb(c, correction = {
5983 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5984 '6': 23, '7': 16, '8': 10, '9': 5}):
5985 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5986 if c <= 0:
5987 raise ValueError("The argument to _log10_lb should be nonnegative.")
5988 str_c = str(c)
5989 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005990
Guido van Rossumd8faa362007-04-27 19:54:29 +00005991##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005992
Mark Dickinsonac256ab2010-04-03 11:08:14 +00005993def _convert_other(other, raiseit=False, allow_float=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005994 """Convert other to Decimal.
5995
5996 Verifies that it's ok to use in an implicit construction.
Mark Dickinsonac256ab2010-04-03 11:08:14 +00005997 If allow_float is true, allow conversion from float; this
5998 is used in the comparison methods (__eq__ and friends).
5999
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006000 """
6001 if isinstance(other, Decimal):
6002 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00006003 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006004 return Decimal(other)
Mark Dickinsonac256ab2010-04-03 11:08:14 +00006005 if allow_float and isinstance(other, float):
6006 return Decimal.from_float(other)
6007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00006008 if raiseit:
6009 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00006010 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006011
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006012def _convert_for_comparison(self, other, equality_op=False):
6013 """Given a Decimal instance self and a Python object other, return
Mark Dickinson1c164a62010-06-11 16:49:20 +00006014 a pair (s, o) of Decimal instances such that "s op o" is
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006015 equivalent to "self op other" for any of the 6 comparison
6016 operators "op".
6017
6018 """
6019 if isinstance(other, Decimal):
6020 return self, other
6021
6022 # Comparison with a Rational instance (also includes integers):
6023 # self op n/d <=> self*d op n (for n and d integers, d positive).
6024 # A NaN or infinity can be left unchanged without affecting the
6025 # comparison result.
6026 if isinstance(other, _numbers.Rational):
6027 if not self._is_special:
6028 self = _dec_from_triple(self._sign,
6029 str(int(self._int) * other.denominator),
6030 self._exp)
6031 return self, Decimal(other.numerator)
6032
6033 # Comparisons with float and complex types. == and != comparisons
6034 # with complex numbers should succeed, returning either True or False
6035 # as appropriate. Other comparisons return NotImplemented.
6036 if equality_op and isinstance(other, _numbers.Complex) and other.imag == 0:
6037 other = other.real
6038 if isinstance(other, float):
Stefan Krah1919b7e2012-03-21 18:25:23 +01006039 context = getcontext()
6040 if equality_op:
6041 context.flags[FloatOperation] = 1
6042 else:
6043 context._raise_error(FloatOperation,
6044 "strict semantics for mixing floats and Decimals are enabled")
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006045 return self, Decimal.from_float(other)
6046 return NotImplemented, NotImplemented
6047
6048
Guido van Rossumd8faa362007-04-27 19:54:29 +00006049##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006050
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006051# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00006052# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006053
6054DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00006055 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006056 traps=[DivisionByZero, Overflow, InvalidOperation],
6057 flags=[],
Stefan Krah1919b7e2012-03-21 18:25:23 +01006058 Emax=999999,
6059 Emin=-999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00006060 capitals=1,
6061 clamp=0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006062)
6063
6064# Pre-made alternate contexts offered by the specification
6065# Don't change these; the user should be able to select these
6066# contexts and be able to reproduce results from other implementations
6067# of the spec.
6068
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00006069BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006070 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006071 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
6072 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006073)
6074
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00006075ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00006076 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006077 traps=[],
6078 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006079)
6080
6081
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006082##### crud for parsing strings #############################################
Christian Heimes23daade02008-02-25 12:39:23 +00006083#
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006084# Regular expression used for parsing numeric strings. Additional
6085# comments:
6086#
6087# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
6088# whitespace. But note that the specification disallows whitespace in
6089# a numeric string.
6090#
6091# 2. For finite numbers (not infinities and NaNs) the body of the
6092# number between the optional sign and the optional exponent must have
6093# at least one decimal digit, possibly after the decimal point. The
Mark Dickinson345adc42009-08-02 10:14:23 +00006094# lookahead expression '(?=\d|\.\d)' checks this.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006095
6096import re
Benjamin Peterson41181742008-07-02 20:22:54 +00006097_parser = re.compile(r""" # A numeric string consists of:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006098# \s*
Benjamin Peterson41181742008-07-02 20:22:54 +00006099 (?P<sign>[-+])? # an optional sign, followed by either...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006100 (
Mark Dickinson345adc42009-08-02 10:14:23 +00006101 (?=\d|\.\d) # ...a number (with at least one digit)
6102 (?P<int>\d*) # having a (possibly empty) integer part
6103 (\.(?P<frac>\d*))? # followed by an optional fractional part
6104 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006105 |
Benjamin Peterson41181742008-07-02 20:22:54 +00006106 Inf(inity)? # ...an infinity, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006107 |
Benjamin Peterson41181742008-07-02 20:22:54 +00006108 (?P<signal>s)? # ...an (optionally signaling)
6109 NaN # NaN
Mark Dickinson345adc42009-08-02 10:14:23 +00006110 (?P<diag>\d*) # with (possibly empty) diagnostic info.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006111 )
6112# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00006113 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006114""", re.VERBOSE | re.IGNORECASE).match
6115
Christian Heimescbf3b5c2007-12-03 21:02:03 +00006116_all_zeros = re.compile('0*$').match
6117_exact_half = re.compile('50*$').match
Christian Heimesf16baeb2008-02-29 14:57:44 +00006118
6119##### PEP3101 support functions ##############################################
Mark Dickinson79f52032009-03-17 23:12:51 +00006120# The functions in this section have little to do with the Decimal
6121# class, and could potentially be reused or adapted for other pure
Christian Heimesf16baeb2008-02-29 14:57:44 +00006122# Python numeric classes that want to implement __format__
6123#
6124# A format specifier for Decimal looks like:
6125#
Eric Smith984bb582010-11-25 16:08:06 +00006126# [[fill]align][sign][#][0][minimumwidth][,][.precision][type]
Christian Heimesf16baeb2008-02-29 14:57:44 +00006127
6128_parse_format_specifier_regex = re.compile(r"""\A
6129(?:
6130 (?P<fill>.)?
6131 (?P<align>[<>=^])
6132)?
6133(?P<sign>[-+ ])?
Eric Smith984bb582010-11-25 16:08:06 +00006134(?P<alt>\#)?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006135(?P<zeropad>0)?
6136(?P<minimumwidth>(?!0)\d+)?
Mark Dickinson79f52032009-03-17 23:12:51 +00006137(?P<thousands_sep>,)?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006138(?:\.(?P<precision>0|(?!0)\d+))?
Mark Dickinson79f52032009-03-17 23:12:51 +00006139(?P<type>[eEfFgGn%])?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006140\Z
6141""", re.VERBOSE)
6142
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006143del re
6144
Mark Dickinson79f52032009-03-17 23:12:51 +00006145# The locale module is only needed for the 'n' format specifier. The
6146# rest of the PEP 3101 code functions quite happily without it, so we
6147# don't care too much if locale isn't present.
6148try:
6149 import locale as _locale
6150except ImportError:
6151 pass
6152
6153def _parse_format_specifier(format_spec, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00006154 """Parse and validate a format specifier.
6155
6156 Turns a standard numeric format specifier into a dict, with the
6157 following entries:
6158
6159 fill: fill character to pad field to minimum width
6160 align: alignment type, either '<', '>', '=' or '^'
6161 sign: either '+', '-' or ' '
6162 minimumwidth: nonnegative integer giving minimum width
Mark Dickinson79f52032009-03-17 23:12:51 +00006163 zeropad: boolean, indicating whether to pad with zeros
6164 thousands_sep: string to use as thousands separator, or ''
6165 grouping: grouping for thousands separators, in format
6166 used by localeconv
6167 decimal_point: string to use for decimal point
Christian Heimesf16baeb2008-02-29 14:57:44 +00006168 precision: nonnegative integer giving precision, or None
6169 type: one of the characters 'eEfFgG%', or None
Christian Heimesf16baeb2008-02-29 14:57:44 +00006170
6171 """
6172 m = _parse_format_specifier_regex.match(format_spec)
6173 if m is None:
6174 raise ValueError("Invalid format specifier: " + format_spec)
6175
6176 # get the dictionary
6177 format_dict = m.groupdict()
6178
Mark Dickinson79f52032009-03-17 23:12:51 +00006179 # zeropad; defaults for fill and alignment. If zero padding
6180 # is requested, the fill and align fields should be absent.
Christian Heimesf16baeb2008-02-29 14:57:44 +00006181 fill = format_dict['fill']
6182 align = format_dict['align']
Mark Dickinson79f52032009-03-17 23:12:51 +00006183 format_dict['zeropad'] = (format_dict['zeropad'] is not None)
6184 if format_dict['zeropad']:
6185 if fill is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00006186 raise ValueError("Fill character conflicts with '0'"
6187 " in format specifier: " + format_spec)
Mark Dickinson79f52032009-03-17 23:12:51 +00006188 if align is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00006189 raise ValueError("Alignment conflicts with '0' in "
6190 "format specifier: " + format_spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00006191 format_dict['fill'] = fill or ' '
Mark Dickinson46ab5d02009-09-08 20:22:46 +00006192 # PEP 3101 originally specified that the default alignment should
6193 # be left; it was later agreed that right-aligned makes more sense
6194 # for numeric types. See http://bugs.python.org/issue6857.
6195 format_dict['align'] = align or '>'
Christian Heimesf16baeb2008-02-29 14:57:44 +00006196
Mark Dickinson79f52032009-03-17 23:12:51 +00006197 # default sign handling: '-' for negative, '' for positive
Christian Heimesf16baeb2008-02-29 14:57:44 +00006198 if format_dict['sign'] is None:
6199 format_dict['sign'] = '-'
6200
Christian Heimesf16baeb2008-02-29 14:57:44 +00006201 # minimumwidth defaults to 0; precision remains None if not given
6202 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
6203 if format_dict['precision'] is not None:
6204 format_dict['precision'] = int(format_dict['precision'])
6205
6206 # if format type is 'g' or 'G' then a precision of 0 makes little
6207 # sense; convert it to 1. Same if format type is unspecified.
6208 if format_dict['precision'] == 0:
Stefan Krah1919b7e2012-03-21 18:25:23 +01006209 if format_dict['type'] is None or format_dict['type'] in 'gGn':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006210 format_dict['precision'] = 1
6211
Mark Dickinson79f52032009-03-17 23:12:51 +00006212 # determine thousands separator, grouping, and decimal separator, and
6213 # add appropriate entries to format_dict
6214 if format_dict['type'] == 'n':
6215 # apart from separators, 'n' behaves just like 'g'
6216 format_dict['type'] = 'g'
6217 if _localeconv is None:
6218 _localeconv = _locale.localeconv()
6219 if format_dict['thousands_sep'] is not None:
6220 raise ValueError("Explicit thousands separator conflicts with "
6221 "'n' type in format specifier: " + format_spec)
6222 format_dict['thousands_sep'] = _localeconv['thousands_sep']
6223 format_dict['grouping'] = _localeconv['grouping']
6224 format_dict['decimal_point'] = _localeconv['decimal_point']
6225 else:
6226 if format_dict['thousands_sep'] is None:
6227 format_dict['thousands_sep'] = ''
6228 format_dict['grouping'] = [3, 0]
6229 format_dict['decimal_point'] = '.'
Christian Heimesf16baeb2008-02-29 14:57:44 +00006230
6231 return format_dict
6232
Mark Dickinson79f52032009-03-17 23:12:51 +00006233def _format_align(sign, body, spec):
6234 """Given an unpadded, non-aligned numeric string 'body' and sign
Ezio Melotti42da6632011-03-15 05:18:48 +02006235 string 'sign', add padding and alignment conforming to the given
Mark Dickinson79f52032009-03-17 23:12:51 +00006236 format specifier dictionary 'spec' (as produced by
6237 parse_format_specifier).
Christian Heimesf16baeb2008-02-29 14:57:44 +00006238
6239 """
Christian Heimesf16baeb2008-02-29 14:57:44 +00006240 # how much extra space do we have to play with?
Mark Dickinson79f52032009-03-17 23:12:51 +00006241 minimumwidth = spec['minimumwidth']
6242 fill = spec['fill']
6243 padding = fill*(minimumwidth - len(sign) - len(body))
Christian Heimesf16baeb2008-02-29 14:57:44 +00006244
Mark Dickinson79f52032009-03-17 23:12:51 +00006245 align = spec['align']
Christian Heimesf16baeb2008-02-29 14:57:44 +00006246 if align == '<':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006247 result = sign + body + padding
Mark Dickinsonad416342009-03-17 18:10:15 +00006248 elif align == '>':
6249 result = padding + sign + body
Christian Heimesf16baeb2008-02-29 14:57:44 +00006250 elif align == '=':
6251 result = sign + padding + body
Mark Dickinson79f52032009-03-17 23:12:51 +00006252 elif align == '^':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006253 half = len(padding)//2
6254 result = padding[:half] + sign + body + padding[half:]
Mark Dickinson79f52032009-03-17 23:12:51 +00006255 else:
6256 raise ValueError('Unrecognised alignment field')
Christian Heimesf16baeb2008-02-29 14:57:44 +00006257
Christian Heimesf16baeb2008-02-29 14:57:44 +00006258 return result
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006259
Mark Dickinson79f52032009-03-17 23:12:51 +00006260def _group_lengths(grouping):
6261 """Convert a localeconv-style grouping into a (possibly infinite)
6262 iterable of integers representing group lengths.
6263
6264 """
6265 # The result from localeconv()['grouping'], and the input to this
6266 # function, should be a list of integers in one of the
6267 # following three forms:
6268 #
6269 # (1) an empty list, or
6270 # (2) nonempty list of positive integers + [0]
6271 # (3) list of positive integers + [locale.CHAR_MAX], or
6272
6273 from itertools import chain, repeat
6274 if not grouping:
6275 return []
6276 elif grouping[-1] == 0 and len(grouping) >= 2:
6277 return chain(grouping[:-1], repeat(grouping[-2]))
6278 elif grouping[-1] == _locale.CHAR_MAX:
6279 return grouping[:-1]
6280 else:
6281 raise ValueError('unrecognised format for grouping')
6282
6283def _insert_thousands_sep(digits, spec, min_width=1):
6284 """Insert thousands separators into a digit string.
6285
6286 spec is a dictionary whose keys should include 'thousands_sep' and
6287 'grouping'; typically it's the result of parsing the format
6288 specifier using _parse_format_specifier.
6289
6290 The min_width keyword argument gives the minimum length of the
6291 result, which will be padded on the left with zeros if necessary.
6292
6293 If necessary, the zero padding adds an extra '0' on the left to
6294 avoid a leading thousands separator. For example, inserting
6295 commas every three digits in '123456', with min_width=8, gives
6296 '0,123,456', even though that has length 9.
6297
6298 """
6299
6300 sep = spec['thousands_sep']
6301 grouping = spec['grouping']
6302
6303 groups = []
6304 for l in _group_lengths(grouping):
Mark Dickinson79f52032009-03-17 23:12:51 +00006305 if l <= 0:
6306 raise ValueError("group length should be positive")
6307 # max(..., 1) forces at least 1 digit to the left of a separator
6308 l = min(max(len(digits), min_width, 1), l)
6309 groups.append('0'*(l - len(digits)) + digits[-l:])
6310 digits = digits[:-l]
6311 min_width -= l
6312 if not digits and min_width <= 0:
6313 break
Mark Dickinson7303b592009-03-18 08:25:36 +00006314 min_width -= len(sep)
Mark Dickinson79f52032009-03-17 23:12:51 +00006315 else:
6316 l = max(len(digits), min_width, 1)
6317 groups.append('0'*(l - len(digits)) + digits[-l:])
6318 return sep.join(reversed(groups))
6319
6320def _format_sign(is_negative, spec):
6321 """Determine sign character."""
6322
6323 if is_negative:
6324 return '-'
6325 elif spec['sign'] in ' +':
6326 return spec['sign']
6327 else:
6328 return ''
6329
6330def _format_number(is_negative, intpart, fracpart, exp, spec):
6331 """Format a number, given the following data:
6332
6333 is_negative: true if the number is negative, else false
6334 intpart: string of digits that must appear before the decimal point
6335 fracpart: string of digits that must come after the point
6336 exp: exponent, as an integer
6337 spec: dictionary resulting from parsing the format specifier
6338
6339 This function uses the information in spec to:
6340 insert separators (decimal separator and thousands separators)
6341 format the sign
6342 format the exponent
6343 add trailing '%' for the '%' type
6344 zero-pad if necessary
6345 fill and align if necessary
6346 """
6347
6348 sign = _format_sign(is_negative, spec)
6349
Eric Smith984bb582010-11-25 16:08:06 +00006350 if fracpart or spec['alt']:
Mark Dickinson79f52032009-03-17 23:12:51 +00006351 fracpart = spec['decimal_point'] + fracpart
6352
6353 if exp != 0 or spec['type'] in 'eE':
6354 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
6355 fracpart += "{0}{1:+}".format(echar, exp)
6356 if spec['type'] == '%':
6357 fracpart += '%'
6358
6359 if spec['zeropad']:
6360 min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
6361 else:
6362 min_width = 0
6363 intpart = _insert_thousands_sep(intpart, spec, min_width)
6364
6365 return _format_align(sign, intpart+fracpart, spec)
6366
6367
Guido van Rossumd8faa362007-04-27 19:54:29 +00006368##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006369
Guido van Rossumd8faa362007-04-27 19:54:29 +00006370# Reusable defaults
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006371_Infinity = Decimal('Inf')
6372_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonf9236412009-01-02 23:23:21 +00006373_NaN = Decimal('NaN')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006374_Zero = Decimal(0)
6375_One = Decimal(1)
6376_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006377
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006378# _SignedInfinity[sign] is infinity w/ that sign
6379_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006380
Mark Dickinsondc787d22010-05-23 13:33:13 +00006381# Constants related to the hash implementation; hash(x) is based
6382# on the reduction of x modulo _PyHASH_MODULUS
Mark Dickinsondc787d22010-05-23 13:33:13 +00006383_PyHASH_MODULUS = sys.hash_info.modulus
6384# hash values to use for positive and negative infinities, and nans
6385_PyHASH_INF = sys.hash_info.inf
6386_PyHASH_NAN = sys.hash_info.nan
Mark Dickinsondc787d22010-05-23 13:33:13 +00006387
6388# _PyHASH_10INV is the inverse of 10 modulo the prime _PyHASH_MODULUS
6389_PyHASH_10INV = pow(10, _PyHASH_MODULUS - 2, _PyHASH_MODULUS)
Stefan Krah1919b7e2012-03-21 18:25:23 +01006390del sys
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006391
Stefan Krah1919b7e2012-03-21 18:25:23 +01006392try:
6393 import _decimal
6394except ImportError:
6395 pass
6396else:
6397 s1 = set(dir())
6398 s2 = set(dir(_decimal))
6399 for name in s1 - s2:
6400 del globals()[name]
6401 del s1, s2, name
6402 from _decimal import *
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006403
6404if __name__ == '__main__':
Raymond Hettinger6d7e26e2011-02-01 23:54:43 +00006405 import doctest, decimal
6406 doctest.testmod(decimal)