blob: 6bd655bdb75097813e8cd547ce5720a664db9b94 [file] [log] [blame]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001# Copyright (c) 2004 Python Software Foundation.
2# All rights reserved.
3
4# Written by Eric Price <eprice at tjhsst.edu>
5# and Facundo Batista <facundo at taniquetil.com.ar>
6# and Raymond Hettinger <python at rcn.com>
Fred Drake1f34eb12004-07-01 14:28:36 +00007# and Aahz <aahz at pobox.com>
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00008# and Tim Peters
9
Facundo Batista6ab24792009-02-16 15:41:37 +000010# This module should be kept in sync with the latest updates of the
11# IBM specification as it evolves. Those updates will be treated
Raymond Hettinger27dbcf22004-08-19 22:39:55 +000012# as bug fixes (deviation from the spec is a compatibility, usability
13# bug) and will be backported. At this point the spec is stabilizing
14# and the updates are becoming fewer, smaller, and less significant.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000015
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000016"""
Facundo Batista6ab24792009-02-16 15:41:37 +000017This is an implementation of decimal floating point arithmetic based on
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000018the General Decimal Arithmetic Specification:
19
Raymond Hettinger960dc362009-04-21 03:43:15 +000020 http://speleotrove.com/decimal/decarith.html
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000021
Raymond Hettinger0ea241e2004-07-04 13:53:24 +000022and IEEE standard 854-1987:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000023
24 www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
25
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000026Decimal floating point has finite precision with arbitrarily large bounds.
27
Guido van Rossumd8faa362007-04-27 19:54:29 +000028The purpose of this module is to support arithmetic using familiar
29"schoolhouse" rules and to avoid some of the tricky representation
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000030issues associated with binary floating point. The package is especially
31useful for financial applications or for contexts where users have
32expectations that are at odds with binary floating point (for instance,
33in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
Mark Dickinsonaa63c4d2010-06-12 16:37:53 +000034of 0.0; Decimal('1.00') % Decimal('0.1') returns the expected
35Decimal('0.00')).
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000036
37Here are some examples of using the decimal module:
38
39>>> from decimal import *
Raymond Hettingerbd7f76d2004-07-08 00:49:18 +000040>>> setcontext(ExtendedContext)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000041>>> Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000042Decimal('0')
43>>> Decimal('1')
44Decimal('1')
45>>> Decimal('-.0123')
46Decimal('-0.0123')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000047>>> Decimal(123456)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000048Decimal('123456')
Stefan Krah1919b7e2012-03-21 18:25:23 +010049>>> Decimal('123.45e12345678')
50Decimal('1.2345E+12345680')
Christian Heimes68f5fbe2008-02-14 08:27:37 +000051>>> Decimal('1.33') + Decimal('1.27')
52Decimal('2.60')
53>>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
54Decimal('-2.20')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000055>>> dig = Decimal(1)
Guido van Rossum7131f842007-02-09 20:13:25 +000056>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000570.333333333
58>>> getcontext().prec = 18
Guido van Rossum7131f842007-02-09 20:13:25 +000059>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000600.333333333333333333
Guido van Rossum7131f842007-02-09 20:13:25 +000061>>> print(dig.sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000621
Guido van Rossum7131f842007-02-09 20:13:25 +000063>>> print(Decimal(3).sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000641.73205080756887729
Guido van Rossum7131f842007-02-09 20:13:25 +000065>>> print(Decimal(3) ** 123)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000664.85192780976896427E+58
67>>> inf = Decimal(1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000068>>> print(inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000069Infinity
70>>> neginf = Decimal(-1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000071>>> print(neginf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000072-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000073>>> print(neginf + inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000074NaN
Guido van Rossum7131f842007-02-09 20:13:25 +000075>>> print(neginf * inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000076-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000077>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000078Infinity
Raymond Hettingerbf440692004-07-10 14:14:37 +000079>>> getcontext().traps[DivisionByZero] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000080>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000081Traceback (most recent call last):
82 ...
83 ...
84 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +000085decimal.DivisionByZero: x / 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000086>>> c = Context()
Raymond Hettingerbf440692004-07-10 14:14:37 +000087>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000088>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000890
90>>> c.divide(Decimal(0), Decimal(0))
Christian Heimes68f5fbe2008-02-14 08:27:37 +000091Decimal('NaN')
Raymond Hettingerbf440692004-07-10 14:14:37 +000092>>> c.traps[InvalidOperation] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000093>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000941
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000095>>> c.flags[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000096>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000970
Guido van Rossum7131f842007-02-09 20:13:25 +000098>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000099Traceback (most recent call last):
100 ...
101 ...
102 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +0000103decimal.InvalidOperation: 0 / 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000104>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001051
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000106>>> c.flags[InvalidOperation] = 0
Raymond Hettingerbf440692004-07-10 14:14:37 +0000107>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000108>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000109NaN
Guido van Rossum7131f842007-02-09 20:13:25 +0000110>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001111
112>>>
113"""
114
115__all__ = [
116 # Two major classes
117 'Decimal', 'Context',
118
119 # Contexts
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +0000120 'DefaultContext', 'BasicContext', 'ExtendedContext',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000121
122 # Exceptions
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +0000123 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
124 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
Stefan Krah1919b7e2012-03-21 18:25:23 +0100125 'FloatOperation',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000126
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000127 # Constants for use in setting up contexts
128 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000129 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000130
131 # Functions for manipulating contexts
Stefan Krah1919b7e2012-03-21 18:25:23 +0100132 'setcontext', 'getcontext', 'localcontext',
133
134 # Limits for the C version for compatibility
135 'MAX_PREC', 'MAX_EMAX', 'MIN_EMIN', 'MIN_ETINY',
136
137 # C version: compile time choice that enables the thread local context
138 'HAVE_THREADS'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000139]
140
Raymond Hettinger960dc362009-04-21 03:43:15 +0000141__version__ = '1.70' # Highest version of the spec this complies with
Raymond Hettinger697ce952010-11-30 20:32:59 +0000142 # See http://speleotrove.com/decimal/
Raymond Hettinger960dc362009-04-21 03:43:15 +0000143
Raymond Hettingereb260842005-06-07 18:52:34 +0000144import copy as _copy
Raymond Hettinger771ed762009-01-03 19:20:32 +0000145import math as _math
Raymond Hettinger82417ca2009-02-03 03:54:28 +0000146import numbers as _numbers
Stefan Krah1919b7e2012-03-21 18:25:23 +0100147import sys
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000148
Christian Heimes25bb7832008-01-11 16:17:00 +0000149try:
150 from collections import namedtuple as _namedtuple
151 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
152except ImportError:
153 DecimalTuple = lambda *args: args
154
Guido van Rossumd8faa362007-04-27 19:54:29 +0000155# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000156ROUND_DOWN = 'ROUND_DOWN'
157ROUND_HALF_UP = 'ROUND_HALF_UP'
158ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
159ROUND_CEILING = 'ROUND_CEILING'
160ROUND_FLOOR = 'ROUND_FLOOR'
161ROUND_UP = 'ROUND_UP'
162ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000163ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000164
Stefan Krah1919b7e2012-03-21 18:25:23 +0100165# Compatibility with the C version
166HAVE_THREADS = True
167if sys.maxsize == 2**63-1:
168 MAX_PREC = 999999999999999999
169 MAX_EMAX = 999999999999999999
170 MIN_EMIN = -999999999999999999
171else:
172 MAX_PREC = 425000000
173 MAX_EMAX = 425000000
174 MIN_EMIN = -425000000
175
176MIN_ETINY = MIN_EMIN - (MAX_PREC-1)
177
Guido van Rossumd8faa362007-04-27 19:54:29 +0000178# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000179
180class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000181 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000182
183 Used exceptions derive from this.
184 If an exception derives from another exception besides this (such as
185 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
186 called if the others are present. This isn't actually used for
187 anything, though.
188
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000189 handle -- Called when context._raise_error is called and the
Stefan Krah2eb4a072010-05-19 15:52:31 +0000190 trap_enabler is not set. First argument is self, second is the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000191 context. More arguments can be given, those being after
192 the explanation in _raise_error (For example,
193 context._raise_error(NewError, '(-x)!', self._sign) would
194 call NewError().handle(context, self._sign).)
195
196 To define a new exception, it should be sufficient to have it derive
197 from DecimalException.
198 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000199 def handle(self, context, *args):
200 pass
201
202
203class Clamped(DecimalException):
204 """Exponent of a 0 changed to fit bounds.
205
206 This occurs and signals clamped if the exponent of a result has been
207 altered in order to fit the constraints of a specific concrete
Guido van Rossumd8faa362007-04-27 19:54:29 +0000208 representation. This may occur when the exponent of a zero result would
209 be outside the bounds of a representation, or when a large normal
210 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000211 this latter case, the exponent is reduced to fit and the corresponding
212 number of zero digits are appended to the coefficient ("fold-down").
213 """
214
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000215class InvalidOperation(DecimalException):
216 """An invalid operation was performed.
217
218 Various bad things cause this:
219
220 Something creates a signaling NaN
221 -INF + INF
Guido van Rossumd8faa362007-04-27 19:54:29 +0000222 0 * (+-)INF
223 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000224 x % 0
225 (+-)INF % x
226 x._rescale( non-integer )
227 sqrt(-x) , x > 0
228 0 ** 0
229 x ** (non-integer)
230 x ** (+-)INF
231 An operand is invalid
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000232
233 The result of the operation after these is a quiet positive NaN,
234 except when the cause is a signaling NaN, in which case the result is
235 also a quiet NaN, but with the original sign, and an optional
236 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000237 """
238 def handle(self, context, *args):
239 if args:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000240 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
241 return ans._fix_nan(context)
Mark Dickinsonf9236412009-01-02 23:23:21 +0000242 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000243
244class ConversionSyntax(InvalidOperation):
245 """Trying to convert badly formed string.
246
247 This occurs and signals invalid-operation if an string is being
248 converted to a number and it does not conform to the numeric string
Guido van Rossumd8faa362007-04-27 19:54:29 +0000249 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000250 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000251 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000252 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000253
254class DivisionByZero(DecimalException, ZeroDivisionError):
255 """Division by 0.
256
257 This occurs and signals division-by-zero if division of a finite number
258 by zero was attempted (during a divide-integer or divide operation, or a
259 power operation with negative right-hand operand), and the dividend was
260 not zero.
261
262 The result of the operation is [sign,inf], where sign is the exclusive
263 or of the signs of the operands for divide, or is 1 for an odd power of
264 -0, for power.
265 """
266
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000267 def handle(self, context, sign, *args):
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000268 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000269
270class DivisionImpossible(InvalidOperation):
271 """Cannot perform the division adequately.
272
273 This occurs and signals invalid-operation if the integer result of a
274 divide-integer or remainder operation had too many digits (would be
Guido van Rossumd8faa362007-04-27 19:54:29 +0000275 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000276 """
277
278 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000279 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000280
281class DivisionUndefined(InvalidOperation, ZeroDivisionError):
282 """Undefined result of division.
283
284 This occurs and signals invalid-operation if division by zero was
285 attempted (during a divide-integer, divide, or remainder operation), and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000286 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000287 """
288
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000289 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000290 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000291
292class Inexact(DecimalException):
293 """Had to round, losing information.
294
295 This occurs and signals inexact whenever the result of an operation is
296 not exact (that is, it needed to be rounded and any discarded digits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000297 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000298 result in all cases is unchanged.
299
300 The inexact signal may be tested (or trapped) to determine if a given
301 operation (or sequence of operations) was inexact.
302 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000303
304class InvalidContext(InvalidOperation):
305 """Invalid context. Unknown rounding, for example.
306
307 This occurs and signals invalid-operation if an invalid context was
Guido van Rossumd8faa362007-04-27 19:54:29 +0000308 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000309 on creation and either the precision exceeds the capability of the
310 underlying concrete representation or an unknown or unsupported rounding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000311 was specified. These aspects of the context need only be checked when
312 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000313 """
314
315 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000316 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000317
318class Rounded(DecimalException):
319 """Number got rounded (not necessarily changed during rounding).
320
321 This occurs and signals rounded whenever the result of an operation is
322 rounded (that is, some zero or non-zero digits were discarded from the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000323 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000324 result in all cases is unchanged.
325
326 The rounded signal may be tested (or trapped) to determine if a given
327 operation (or sequence of operations) caused a loss of precision.
328 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000329
330class Subnormal(DecimalException):
331 """Exponent < Emin before rounding.
332
333 This occurs and signals subnormal whenever the result of a conversion or
334 operation is subnormal (that is, its adjusted exponent is less than
Guido van Rossumd8faa362007-04-27 19:54:29 +0000335 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000336
337 The subnormal signal may be tested (or trapped) to determine if a given
338 or operation (or sequence of operations) yielded a subnormal result.
339 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000340
341class Overflow(Inexact, Rounded):
342 """Numerical overflow.
343
344 This occurs and signals overflow if the adjusted exponent of a result
345 (from a conversion or from an operation that is not an attempt to divide
346 by zero), after rounding, would be greater than the largest value that
347 can be handled by the implementation (the value Emax).
348
349 The result depends on the rounding mode:
350
351 For round-half-up and round-half-even (and for round-half-down and
352 round-up, if implemented), the result of the operation is [sign,inf],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000353 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000354 result is the largest finite number that can be represented in the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000355 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000356 round-ceiling, the result is the same as for round-down if the sign of
Guido van Rossumd8faa362007-04-27 19:54:29 +0000357 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000358 the result is the same as for round-down if the sign of the intermediate
Guido van Rossumd8faa362007-04-27 19:54:29 +0000359 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000360 will also be raised.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000361 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000362
363 def handle(self, context, sign, *args):
364 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000365 ROUND_HALF_DOWN, ROUND_UP):
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000366 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000367 if sign == 0:
368 if context.rounding == ROUND_CEILING:
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000369 return _SignedInfinity[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000370 return _dec_from_triple(sign, '9'*context.prec,
371 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000372 if sign == 1:
373 if context.rounding == ROUND_FLOOR:
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000374 return _SignedInfinity[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000375 return _dec_from_triple(sign, '9'*context.prec,
376 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000377
378
379class Underflow(Inexact, Rounded, Subnormal):
380 """Numerical underflow with result rounded to 0.
381
382 This occurs and signals underflow if a result is inexact and the
383 adjusted exponent of the result would be smaller (more negative) than
384 the smallest value that can be handled by the implementation (the value
Guido van Rossumd8faa362007-04-27 19:54:29 +0000385 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000386
387 The result after an underflow will be a subnormal number rounded, if
Guido van Rossumd8faa362007-04-27 19:54:29 +0000388 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000389 in 0 with the sign of the intermediate result and an exponent of Etiny.
390
391 In all cases, Inexact, Rounded, and Subnormal will also be raised.
392 """
393
Stefan Krahb6405ef2012-03-23 14:46:48 +0100394class FloatOperation(DecimalException, TypeError):
Stefan Krah1919b7e2012-03-21 18:25:23 +0100395 """Enable stricter semantics for mixing floats and Decimals.
396
397 If the signal is not trapped (default), mixing floats and Decimals is
398 permitted in the Decimal() constructor, context.create_decimal() and
399 all comparison operators. Both conversion and comparisons are exact.
400 Any occurrence of a mixed operation is silently recorded by setting
401 FloatOperation in the context flags. Explicit conversions with
402 Decimal.from_float() or context.create_decimal_from_float() do not
403 set the flag.
404
405 Otherwise (the signal is trapped), only equality comparisons and explicit
406 conversions are silent. All other mixed operations raise FloatOperation.
407 """
408
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000409# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000410_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Stefan Krah1919b7e2012-03-21 18:25:23 +0100411 Underflow, InvalidOperation, Subnormal, FloatOperation]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000412
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000413# Map conditions (per the spec) to signals
414_condition_map = {ConversionSyntax:InvalidOperation,
415 DivisionImpossible:InvalidOperation,
416 DivisionUndefined:InvalidOperation,
417 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000418
Stefan Krah1919b7e2012-03-21 18:25:23 +0100419# Valid rounding modes
420_rounding_modes = (ROUND_DOWN, ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_CEILING,
421 ROUND_FLOOR, ROUND_UP, ROUND_HALF_DOWN, ROUND_05UP)
422
Guido van Rossumd8faa362007-04-27 19:54:29 +0000423##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000424
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000425# The getcontext() and setcontext() function manage access to a thread-local
426# current context. Py2.4 offers direct support for thread locals. If that
Georg Brandlf9926402008-06-13 06:32:25 +0000427# is not available, use threading.current_thread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000428# work for older Pythons. If threads are not part of the build, create a
429# mock threading object with threading.local() returning the module namespace.
430
431try:
432 import threading
433except ImportError:
434 # Python was compiled without threads; create a mock object instead
Guido van Rossumd8faa362007-04-27 19:54:29 +0000435 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000436 def local(self, sys=sys):
437 return sys.modules[__name__]
438 threading = MockThreading()
Stefan Krah1919b7e2012-03-21 18:25:23 +0100439 del MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000440
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000441try:
442 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000443
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000444except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000445
Guido van Rossumd8faa362007-04-27 19:54:29 +0000446 # To fix reloading, force it to create a new context
447 # Old contexts have different exceptions in their dicts, making problems.
Georg Brandlf9926402008-06-13 06:32:25 +0000448 if hasattr(threading.current_thread(), '__decimal_context__'):
449 del threading.current_thread().__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000450
451 def setcontext(context):
452 """Set this thread's context to context."""
453 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000454 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000455 context.clear_flags()
Georg Brandlf9926402008-06-13 06:32:25 +0000456 threading.current_thread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000457
458 def getcontext():
459 """Returns this thread's context.
460
461 If this thread does not yet have a context, returns
462 a new context and sets this thread's context.
463 New contexts are copies of DefaultContext.
464 """
465 try:
Georg Brandlf9926402008-06-13 06:32:25 +0000466 return threading.current_thread().__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000467 except AttributeError:
468 context = Context()
Georg Brandlf9926402008-06-13 06:32:25 +0000469 threading.current_thread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000470 return context
471
472else:
473
474 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000475 if hasattr(local, '__decimal_context__'):
476 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000477
478 def getcontext(_local=local):
479 """Returns this thread's context.
480
481 If this thread does not yet have a context, returns
482 a new context and sets this thread's context.
483 New contexts are copies of DefaultContext.
484 """
485 try:
486 return _local.__decimal_context__
487 except AttributeError:
488 context = Context()
489 _local.__decimal_context__ = context
490 return context
491
492 def setcontext(context, _local=local):
493 """Set this thread's context to context."""
494 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000495 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000496 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000497 _local.__decimal_context__ = context
498
499 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000500
Thomas Wouters89f507f2006-12-13 04:49:30 +0000501def localcontext(ctx=None):
502 """Return a context manager for a copy of the supplied context
503
504 Uses a copy of the current context if no context is specified
505 The returned context manager creates a local decimal context
506 in a with statement:
507 def sin(x):
508 with localcontext() as ctx:
509 ctx.prec += 2
510 # Rest of sin calculation algorithm
511 # uses a precision 2 greater than normal
Guido van Rossumd8faa362007-04-27 19:54:29 +0000512 return +s # Convert result to normal precision
Thomas Wouters89f507f2006-12-13 04:49:30 +0000513
514 def sin(x):
515 with localcontext(ExtendedContext):
516 # Rest of sin calculation algorithm
517 # uses the Extended Context from the
518 # General Decimal Arithmetic Specification
Guido van Rossumd8faa362007-04-27 19:54:29 +0000519 return +s # Convert result to normal context
Thomas Wouters89f507f2006-12-13 04:49:30 +0000520
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000521 >>> setcontext(DefaultContext)
Guido van Rossum7131f842007-02-09 20:13:25 +0000522 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000523 28
524 >>> with localcontext():
525 ... ctx = getcontext()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000526 ... ctx.prec += 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000527 ... print(ctx.prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000528 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000529 30
530 >>> with localcontext(ExtendedContext):
Guido van Rossum7131f842007-02-09 20:13:25 +0000531 ... print(getcontext().prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000532 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000533 9
Guido van Rossum7131f842007-02-09 20:13:25 +0000534 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000535 28
536 """
537 if ctx is None: ctx = getcontext()
538 return _ContextManager(ctx)
539
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000540
Guido van Rossumd8faa362007-04-27 19:54:29 +0000541##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000542
Raymond Hettingera0fd8882009-01-20 07:24:44 +0000543# Do not subclass Decimal from numbers.Real and do not register it as such
544# (because Decimals are not interoperable with floats). See the notes in
545# numbers.py for more detail.
546
547class Decimal(object):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000548 """Floating point class for decimal arithmetic."""
549
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000550 __slots__ = ('_exp','_int','_sign', '_is_special')
551 # Generally, the value of the Decimal instance is given by
552 # (-1)**_sign * _int * 10**_exp
553 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000554
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000555 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000556 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000557 """Create a decimal point instance.
558
559 >>> Decimal('3.14') # string input
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000560 Decimal('3.14')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000561 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000562 Decimal('3.14')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000563 >>> Decimal(314) # int
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000564 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000565 >>> Decimal(Decimal(314)) # another decimal instance
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000566 Decimal('314')
Christian Heimesa62da1d2008-01-12 19:39:10 +0000567 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000568 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000569 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000570
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000571 # Note that the coefficient, self._int, is actually stored as
572 # a string rather than as a tuple of digits. This speeds up
573 # the "digits to integer" and "integer to digits" conversions
574 # that are used in almost every arithmetic operation on
575 # Decimals. This is an internal detail: the as_tuple function
576 # and the Decimal constructor still deal with tuples of
577 # digits.
578
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000579 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000580
Christian Heimesd59c64c2007-11-30 19:27:20 +0000581 # From a string
582 # REs insist on real strings, so we can too.
583 if isinstance(value, str):
Christian Heimesa62da1d2008-01-12 19:39:10 +0000584 m = _parser(value.strip())
Christian Heimesd59c64c2007-11-30 19:27:20 +0000585 if m is None:
586 if context is None:
587 context = getcontext()
588 return context._raise_error(ConversionSyntax,
589 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000590
Christian Heimesd59c64c2007-11-30 19:27:20 +0000591 if m.group('sign') == "-":
592 self._sign = 1
593 else:
594 self._sign = 0
595 intpart = m.group('int')
596 if intpart is not None:
597 # finite number
Mark Dickinson345adc42009-08-02 10:14:23 +0000598 fracpart = m.group('frac') or ''
Christian Heimesd59c64c2007-11-30 19:27:20 +0000599 exp = int(m.group('exp') or '0')
Mark Dickinson345adc42009-08-02 10:14:23 +0000600 self._int = str(int(intpart+fracpart))
601 self._exp = exp - len(fracpart)
Christian Heimesd59c64c2007-11-30 19:27:20 +0000602 self._is_special = False
603 else:
604 diag = m.group('diag')
605 if diag is not None:
606 # NaN
Mark Dickinson345adc42009-08-02 10:14:23 +0000607 self._int = str(int(diag or '0')).lstrip('0')
Christian Heimesd59c64c2007-11-30 19:27:20 +0000608 if m.group('signal'):
609 self._exp = 'N'
610 else:
611 self._exp = 'n'
612 else:
613 # infinity
614 self._int = '0'
615 self._exp = 'F'
616 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000617 return self
618
619 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000620 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000621 if value >= 0:
622 self._sign = 0
623 else:
624 self._sign = 1
625 self._exp = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000626 self._int = str(abs(value))
Christian Heimesd59c64c2007-11-30 19:27:20 +0000627 self._is_special = False
628 return self
629
630 # From another decimal
631 if isinstance(value, Decimal):
632 self._exp = value._exp
633 self._sign = value._sign
634 self._int = value._int
635 self._is_special = value._is_special
636 return self
637
638 # From an internal working value
639 if isinstance(value, _WorkRep):
640 self._sign = value.sign
641 self._int = str(value.int)
642 self._exp = int(value.exp)
643 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000644 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000645
646 # tuple/list conversion (possibly from as_tuple())
647 if isinstance(value, (list,tuple)):
648 if len(value) != 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000649 raise ValueError('Invalid tuple size in creation of Decimal '
650 'from list or tuple. The list or tuple '
651 'should have exactly three elements.')
652 # process sign. The isinstance test rejects floats
653 if not (isinstance(value[0], int) and value[0] in (0,1)):
654 raise ValueError("Invalid sign. The first value in the tuple "
655 "should be an integer; either 0 for a "
656 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000657 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000658 if value[2] == 'F':
659 # infinity: value[1] is ignored
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000660 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000661 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000662 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000663 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000664 # process and validate the digits in value[1]
665 digits = []
666 for digit in value[1]:
667 if isinstance(digit, int) and 0 <= digit <= 9:
668 # skip leading zeros
669 if digits or digit != 0:
670 digits.append(digit)
671 else:
672 raise ValueError("The second value in the tuple must "
673 "be composed of integers in the range "
674 "0 through 9.")
675 if value[2] in ('n', 'N'):
676 # NaN: digits form the diagnostic
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000677 self._int = ''.join(map(str, digits))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000678 self._exp = value[2]
679 self._is_special = True
680 elif isinstance(value[2], int):
681 # finite number: digits give the coefficient
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000682 self._int = ''.join(map(str, digits or [0]))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000683 self._exp = value[2]
684 self._is_special = False
685 else:
686 raise ValueError("The third value in the tuple must "
687 "be an integer, or one of the "
688 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000689 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000690
Raymond Hettingerbf440692004-07-10 14:14:37 +0000691 if isinstance(value, float):
Stefan Krah1919b7e2012-03-21 18:25:23 +0100692 if context is None:
693 context = getcontext()
694 context._raise_error(FloatOperation,
695 "strict semantics for mixing floats and Decimals are "
696 "enabled")
Raymond Hettinger96798592010-04-02 16:58:27 +0000697 value = Decimal.from_float(value)
698 self._exp = value._exp
699 self._sign = value._sign
700 self._int = value._int
701 self._is_special = value._is_special
702 return self
Raymond Hettingerbf440692004-07-10 14:14:37 +0000703
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000704 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000705
Mark Dickinsonba298e42009-01-04 21:17:43 +0000706 # @classmethod, but @decorator is not valid Python 2.3 syntax, so
707 # don't use it (see notes on Py2.3 compatibility at top of file)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000708 def from_float(cls, f):
709 """Converts a float to a decimal number, exactly.
710
711 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
712 Since 0.1 is not exactly representable in binary floating point, the
713 value is stored as the nearest representable value which is
714 0x1.999999999999ap-4. The exact equivalent of the value in decimal
715 is 0.1000000000000000055511151231257827021181583404541015625.
716
717 >>> Decimal.from_float(0.1)
718 Decimal('0.1000000000000000055511151231257827021181583404541015625')
719 >>> Decimal.from_float(float('nan'))
720 Decimal('NaN')
721 >>> Decimal.from_float(float('inf'))
722 Decimal('Infinity')
723 >>> Decimal.from_float(-float('inf'))
724 Decimal('-Infinity')
725 >>> Decimal.from_float(-0.0)
726 Decimal('-0')
727
728 """
729 if isinstance(f, int): # handle integer inputs
730 return cls(f)
Stefan Krah1919b7e2012-03-21 18:25:23 +0100731 if not isinstance(f, float):
732 raise TypeError("argument must be int or float.")
733 if _math.isinf(f) or _math.isnan(f):
Raymond Hettinger771ed762009-01-03 19:20:32 +0000734 return cls(repr(f))
Mark Dickinsonba298e42009-01-04 21:17:43 +0000735 if _math.copysign(1.0, f) == 1.0:
736 sign = 0
737 else:
738 sign = 1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000739 n, d = abs(f).as_integer_ratio()
740 k = d.bit_length() - 1
741 result = _dec_from_triple(sign, str(n*5**k), -k)
Mark Dickinsonba298e42009-01-04 21:17:43 +0000742 if cls is Decimal:
743 return result
744 else:
745 return cls(result)
746 from_float = classmethod(from_float)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000747
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000748 def _isnan(self):
749 """Returns whether the number is not actually one.
750
751 0 if a number
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000752 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000753 2 if sNaN
754 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000755 if self._is_special:
756 exp = self._exp
757 if exp == 'n':
758 return 1
759 elif exp == 'N':
760 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000761 return 0
762
763 def _isinfinity(self):
764 """Returns whether the number is infinite
765
766 0 if finite or not a number
767 1 if +INF
768 -1 if -INF
769 """
770 if self._exp == 'F':
771 if self._sign:
772 return -1
773 return 1
774 return 0
775
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000776 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000777 """Returns whether the number is not actually one.
778
779 if self, other are sNaN, signal
780 if self, other are NaN return nan
781 return 0
782
783 Done before operations.
784 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000785
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000786 self_is_nan = self._isnan()
787 if other is None:
788 other_is_nan = False
789 else:
790 other_is_nan = other._isnan()
791
792 if self_is_nan or other_is_nan:
793 if context is None:
794 context = getcontext()
795
796 if self_is_nan == 2:
797 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000798 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000799 if other_is_nan == 2:
800 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000801 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000802 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000803 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000804
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000805 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000806 return 0
807
Christian Heimes77c02eb2008-02-09 02:18:51 +0000808 def _compare_check_nans(self, other, context):
809 """Version of _check_nans used for the signaling comparisons
810 compare_signal, __le__, __lt__, __ge__, __gt__.
811
812 Signal InvalidOperation if either self or other is a (quiet
813 or signaling) NaN. Signaling NaNs take precedence over quiet
814 NaNs.
815
816 Return 0 if neither operand is a NaN.
817
818 """
819 if context is None:
820 context = getcontext()
821
822 if self._is_special or other._is_special:
823 if self.is_snan():
824 return context._raise_error(InvalidOperation,
825 'comparison involving sNaN',
826 self)
827 elif other.is_snan():
828 return context._raise_error(InvalidOperation,
829 'comparison involving sNaN',
830 other)
831 elif self.is_qnan():
832 return context._raise_error(InvalidOperation,
833 'comparison involving NaN',
834 self)
835 elif other.is_qnan():
836 return context._raise_error(InvalidOperation,
837 'comparison involving NaN',
838 other)
839 return 0
840
Jack Diederich4dafcc42006-11-28 19:15:13 +0000841 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000842 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000843
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000844 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000845 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000846 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000847
Christian Heimes77c02eb2008-02-09 02:18:51 +0000848 def _cmp(self, other):
849 """Compare the two non-NaN decimal instances self and other.
850
851 Returns -1 if self < other, 0 if self == other and 1
852 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000853
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000854 if self._is_special or other._is_special:
Mark Dickinsone6aad752009-01-25 10:48:51 +0000855 self_inf = self._isinfinity()
856 other_inf = other._isinfinity()
857 if self_inf == other_inf:
858 return 0
859 elif self_inf < other_inf:
860 return -1
861 else:
862 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000863
Mark Dickinsone6aad752009-01-25 10:48:51 +0000864 # check for zeros; Decimal('0') == Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000865 if not self:
866 if not other:
867 return 0
868 else:
869 return -((-1)**other._sign)
870 if not other:
871 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000872
Guido van Rossumd8faa362007-04-27 19:54:29 +0000873 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000874 if other._sign < self._sign:
875 return -1
876 if self._sign < other._sign:
877 return 1
878
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000879 self_adjusted = self.adjusted()
880 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000881 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000882 self_padded = self._int + '0'*(self._exp - other._exp)
883 other_padded = other._int + '0'*(other._exp - self._exp)
Mark Dickinsone6aad752009-01-25 10:48:51 +0000884 if self_padded == other_padded:
885 return 0
886 elif self_padded < other_padded:
887 return -(-1)**self._sign
888 else:
889 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000891 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000892 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000893 return -((-1)**self._sign)
894
Christian Heimes77c02eb2008-02-09 02:18:51 +0000895 # Note: The Decimal standard doesn't cover rich comparisons for
896 # Decimals. In particular, the specification is silent on the
897 # subject of what should happen for a comparison involving a NaN.
898 # We take the following approach:
899 #
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000900 # == comparisons involving a quiet NaN always return False
901 # != comparisons involving a quiet NaN always return True
902 # == or != comparisons involving a signaling NaN signal
903 # InvalidOperation, and return False or True as above if the
904 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000905 # <, >, <= and >= comparisons involving a (quiet or signaling)
906 # NaN signal InvalidOperation, and return False if the
Christian Heimes3feef612008-02-11 06:19:17 +0000907 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000908 #
909 # This behavior is designed to conform as closely as possible to
910 # that specified by IEEE 754.
911
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000912 def __eq__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000913 self, other = _convert_for_comparison(self, other, equality_op=True)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000914 if other is NotImplemented:
915 return other
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000916 if self._check_nans(other, context):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000917 return False
918 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000919
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000920 def __ne__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000921 self, other = _convert_for_comparison(self, other, equality_op=True)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000922 if other is NotImplemented:
923 return other
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000924 if self._check_nans(other, context):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000925 return True
926 return self._cmp(other) != 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000927
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000928
Christian Heimes77c02eb2008-02-09 02:18:51 +0000929 def __lt__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000930 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000931 if other is NotImplemented:
932 return other
933 ans = self._compare_check_nans(other, context)
934 if ans:
935 return False
936 return self._cmp(other) < 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000937
Christian Heimes77c02eb2008-02-09 02:18:51 +0000938 def __le__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000939 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000940 if other is NotImplemented:
941 return other
942 ans = self._compare_check_nans(other, context)
943 if ans:
944 return False
945 return self._cmp(other) <= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000946
Christian Heimes77c02eb2008-02-09 02:18:51 +0000947 def __gt__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000948 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000949 if other is NotImplemented:
950 return other
951 ans = self._compare_check_nans(other, context)
952 if ans:
953 return False
954 return self._cmp(other) > 0
955
956 def __ge__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000957 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000958 if other is NotImplemented:
959 return other
960 ans = self._compare_check_nans(other, context)
961 if ans:
962 return False
963 return self._cmp(other) >= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000964
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000965 def compare(self, other, context=None):
966 """Compares one to another.
967
968 -1 => a < b
969 0 => a = b
970 1 => a > b
971 NaN => one is NaN
972 Like __cmp__, but returns Decimal instances.
973 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000974 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000975
Guido van Rossumd8faa362007-04-27 19:54:29 +0000976 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000977 if (self._is_special or other and other._is_special):
978 ans = self._check_nans(other, context)
979 if ans:
980 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000981
Christian Heimes77c02eb2008-02-09 02:18:51 +0000982 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000983
984 def __hash__(self):
985 """x.__hash__() <==> hash(x)"""
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000986
Mark Dickinsondc787d22010-05-23 13:33:13 +0000987 # In order to make sure that the hash of a Decimal instance
988 # agrees with the hash of a numerically equal integer, float
989 # or Fraction, we follow the rules for numeric hashes outlined
990 # in the documentation. (See library docs, 'Built-in Types').
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000991 if self._is_special:
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000992 if self.is_snan():
Raymond Hettingerd325c4b2010-11-21 04:08:28 +0000993 raise TypeError('Cannot hash a signaling NaN value.')
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000994 elif self.is_nan():
Mark Dickinsondc787d22010-05-23 13:33:13 +0000995 return _PyHASH_NAN
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000996 else:
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000997 if self._sign:
Mark Dickinsondc787d22010-05-23 13:33:13 +0000998 return -_PyHASH_INF
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000999 else:
Mark Dickinsondc787d22010-05-23 13:33:13 +00001000 return _PyHASH_INF
Mark Dickinsonac256ab2010-04-03 11:08:14 +00001001
Mark Dickinsondc787d22010-05-23 13:33:13 +00001002 if self._exp >= 0:
1003 exp_hash = pow(10, self._exp, _PyHASH_MODULUS)
1004 else:
1005 exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS)
1006 hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS
Stefan Krahdc817b22010-11-17 11:16:34 +00001007 ans = hash_ if self >= 0 else -hash_
1008 return -2 if ans == -1 else ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001009
1010 def as_tuple(self):
1011 """Represents the number as a triple tuple.
1012
1013 To show the internals exactly as they are.
1014 """
Christian Heimes25bb7832008-01-11 16:17:00 +00001015 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001016
1017 def __repr__(self):
1018 """Represents the number as an instance of Decimal."""
1019 # Invariant: eval(repr(d)) == d
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001020 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001021
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001022 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001023 """Return string representation of the number in scientific notation.
1024
1025 Captures all of the information in the underlying representation.
1026 """
1027
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001028 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +00001029 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001030 if self._exp == 'F':
1031 return sign + 'Infinity'
1032 elif self._exp == 'n':
1033 return sign + 'NaN' + self._int
1034 else: # self._exp == 'N'
1035 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001036
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001037 # number of digits of self._int to left of decimal point
1038 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001039
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001040 # dotplace is number of digits of self._int to the left of the
1041 # decimal point in the mantissa of the output string (that is,
1042 # after adjusting the exponent)
1043 if self._exp <= 0 and leftdigits > -6:
1044 # no exponent required
1045 dotplace = leftdigits
1046 elif not eng:
1047 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001048 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001049 elif self._int == '0':
1050 # engineering notation, zero
1051 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001052 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001053 # engineering notation, nonzero
1054 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001055
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001056 if dotplace <= 0:
1057 intpart = '0'
1058 fracpart = '.' + '0'*(-dotplace) + self._int
1059 elif dotplace >= len(self._int):
1060 intpart = self._int+'0'*(dotplace-len(self._int))
1061 fracpart = ''
1062 else:
1063 intpart = self._int[:dotplace]
1064 fracpart = '.' + self._int[dotplace:]
1065 if leftdigits == dotplace:
1066 exp = ''
1067 else:
1068 if context is None:
1069 context = getcontext()
1070 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1071
1072 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001073
1074 def to_eng_string(self, context=None):
1075 """Convert to engineering-type string.
1076
1077 Engineering notation has an exponent which is a multiple of 3, so there
1078 are up to 3 digits left of the decimal place.
1079
1080 Same rules for when in exponential and when as a value as in __str__.
1081 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001082 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001083
1084 def __neg__(self, context=None):
1085 """Returns a copy with the sign switched.
1086
1087 Rounds, if it has reason.
1088 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001089 if self._is_special:
1090 ans = self._check_nans(context=context)
1091 if ans:
1092 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001093
Mark Dickinson37a79fb2011-03-12 11:12:52 +00001094 if context is None:
1095 context = getcontext()
1096
1097 if not self and context.rounding != ROUND_FLOOR:
1098 # -Decimal('0') is Decimal('0'), not Decimal('-0'), except
1099 # in ROUND_FLOOR rounding mode.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001100 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001101 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001102 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001103
Christian Heimes2c181612007-12-17 20:04:13 +00001104 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001105
1106 def __pos__(self, context=None):
1107 """Returns a copy, unless it is a sNaN.
1108
1109 Rounds the number (if more then precision digits)
1110 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001111 if self._is_special:
1112 ans = self._check_nans(context=context)
1113 if ans:
1114 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001115
Mark Dickinson37a79fb2011-03-12 11:12:52 +00001116 if context is None:
1117 context = getcontext()
1118
1119 if not self and context.rounding != ROUND_FLOOR:
1120 # + (-0) = 0, except in ROUND_FLOOR rounding mode.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001121 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001122 else:
1123 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001124
Christian Heimes2c181612007-12-17 20:04:13 +00001125 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001126
Christian Heimes2c181612007-12-17 20:04:13 +00001127 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001128 """Returns the absolute value of self.
1129
Christian Heimes2c181612007-12-17 20:04:13 +00001130 If the keyword argument 'round' is false, do not round. The
1131 expression self.__abs__(round=False) is equivalent to
1132 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001133 """
Christian Heimes2c181612007-12-17 20:04:13 +00001134 if not round:
1135 return self.copy_abs()
1136
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001137 if self._is_special:
1138 ans = self._check_nans(context=context)
1139 if ans:
1140 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001142 if self._sign:
1143 ans = self.__neg__(context=context)
1144 else:
1145 ans = self.__pos__(context=context)
1146
1147 return ans
1148
1149 def __add__(self, other, context=None):
1150 """Returns self + other.
1151
1152 -INF + INF (or the reverse) cause InvalidOperation errors.
1153 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001154 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001155 if other is NotImplemented:
1156 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001157
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001158 if context is None:
1159 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001160
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001161 if self._is_special or other._is_special:
1162 ans = self._check_nans(other, context)
1163 if ans:
1164 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001165
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001166 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001167 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001168 if self._sign != other._sign and other._isinfinity():
1169 return context._raise_error(InvalidOperation, '-INF + INF')
1170 return Decimal(self)
1171 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001172 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001173
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001174 exp = min(self._exp, other._exp)
1175 negativezero = 0
1176 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001177 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001178 negativezero = 1
1179
1180 if not self and not other:
1181 sign = min(self._sign, other._sign)
1182 if negativezero:
1183 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001184 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001185 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001186 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001187 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001188 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001189 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001190 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001191 return ans
1192 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001193 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001194 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001195 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001196 return ans
1197
1198 op1 = _WorkRep(self)
1199 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001200 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001201
1202 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001203 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001204 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001205 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001206 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001207 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001208 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001209 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001210 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001211 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001212 if op1.sign == 1:
1213 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001214 op1.sign, op2.sign = op2.sign, op1.sign
1215 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001216 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001217 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001218 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001219 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001220 op1.sign, op2.sign = (0, 0)
1221 else:
1222 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001223 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001224
Raymond Hettinger17931de2004-10-27 06:21:46 +00001225 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001226 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001227 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001228 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001229
1230 result.exp = op1.exp
1231 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001232 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001233 return ans
1234
1235 __radd__ = __add__
1236
1237 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001238 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001239 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001240 if other is NotImplemented:
1241 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001242
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001243 if self._is_special or other._is_special:
1244 ans = self._check_nans(other, context=context)
1245 if ans:
1246 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001247
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001248 # self - other is computed as self + other.copy_negate()
1249 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001250
1251 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001252 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001253 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001254 if other is NotImplemented:
1255 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001256
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001257 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001258
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001259 def __mul__(self, other, context=None):
1260 """Return self * other.
1261
1262 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1263 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001264 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001265 if other is NotImplemented:
1266 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001267
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001268 if context is None:
1269 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001270
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001271 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001272
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001273 if self._is_special or other._is_special:
1274 ans = self._check_nans(other, context)
1275 if ans:
1276 return ans
1277
1278 if self._isinfinity():
1279 if not other:
1280 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001281 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001282
1283 if other._isinfinity():
1284 if not self:
1285 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001286 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001287
1288 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001289
1290 # Special case for multiplying by zero
1291 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001292 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001293 # Fixing in case the exponent is out of bounds
1294 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001295 return ans
1296
1297 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001298 if self._int == '1':
1299 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001300 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001301 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001302 if other._int == '1':
1303 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001304 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001305 return ans
1306
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001307 op1 = _WorkRep(self)
1308 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001309
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001310 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001311 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001312
1313 return ans
1314 __rmul__ = __mul__
1315
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001316 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001317 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001318 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001319 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001320 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001321
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001322 if context is None:
1323 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001324
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001325 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001326
1327 if self._is_special or other._is_special:
1328 ans = self._check_nans(other, context)
1329 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001330 return ans
1331
1332 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001333 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001334
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001335 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001336 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001337
1338 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001339 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001340 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001341
1342 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001343 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001344 if not self:
1345 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001346 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001347
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001348 if not self:
1349 exp = self._exp - other._exp
1350 coeff = 0
1351 else:
1352 # OK, so neither = 0, INF or NaN
1353 shift = len(other._int) - len(self._int) + context.prec + 1
1354 exp = self._exp - other._exp - shift
1355 op1 = _WorkRep(self)
1356 op2 = _WorkRep(other)
1357 if shift >= 0:
1358 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1359 else:
1360 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1361 if remainder:
1362 # result is not exact; adjust to ensure correct rounding
1363 if coeff % 5 == 0:
1364 coeff += 1
1365 else:
1366 # result is exact; get as close to ideal exponent as possible
1367 ideal_exp = self._exp - other._exp
1368 while exp < ideal_exp and coeff % 10 == 0:
1369 coeff //= 10
1370 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001371
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001372 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001373 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001374
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001375 def _divide(self, other, context):
1376 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001377
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001378 Assumes that neither self nor other is a NaN, that self is not
1379 infinite and that other is nonzero.
1380 """
1381 sign = self._sign ^ other._sign
1382 if other._isinfinity():
1383 ideal_exp = self._exp
1384 else:
1385 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001386
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001387 expdiff = self.adjusted() - other.adjusted()
1388 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001389 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001390 self._rescale(ideal_exp, context.rounding))
1391 if expdiff <= context.prec:
1392 op1 = _WorkRep(self)
1393 op2 = _WorkRep(other)
1394 if op1.exp >= op2.exp:
1395 op1.int *= 10**(op1.exp - op2.exp)
1396 else:
1397 op2.int *= 10**(op2.exp - op1.exp)
1398 q, r = divmod(op1.int, op2.int)
1399 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001400 return (_dec_from_triple(sign, str(q), 0),
1401 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001402
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001403 # Here the quotient is too large to be representable
1404 ans = context._raise_error(DivisionImpossible,
1405 'quotient too large in //, % or divmod')
1406 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001407
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001408 def __rtruediv__(self, other, context=None):
1409 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001410 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001411 if other is NotImplemented:
1412 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001413 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001414
1415 def __divmod__(self, other, context=None):
1416 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001417 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001418 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001419 other = _convert_other(other)
1420 if other is NotImplemented:
1421 return other
1422
1423 if context is None:
1424 context = getcontext()
1425
1426 ans = self._check_nans(other, context)
1427 if ans:
1428 return (ans, ans)
1429
1430 sign = self._sign ^ other._sign
1431 if self._isinfinity():
1432 if other._isinfinity():
1433 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1434 return ans, ans
1435 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001436 return (_SignedInfinity[sign],
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001437 context._raise_error(InvalidOperation, 'INF % x'))
1438
1439 if not other:
1440 if not self:
1441 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1442 return ans, ans
1443 else:
1444 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1445 context._raise_error(InvalidOperation, 'x % 0'))
1446
1447 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001448 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001449 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001450
1451 def __rdivmod__(self, other, context=None):
1452 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001453 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001454 if other is NotImplemented:
1455 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001456 return other.__divmod__(self, context=context)
1457
1458 def __mod__(self, other, context=None):
1459 """
1460 self % other
1461 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001462 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001463 if other is NotImplemented:
1464 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001465
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001466 if context is None:
1467 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001468
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001469 ans = self._check_nans(other, context)
1470 if ans:
1471 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001472
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001473 if self._isinfinity():
1474 return context._raise_error(InvalidOperation, 'INF % x')
1475 elif not other:
1476 if self:
1477 return context._raise_error(InvalidOperation, 'x % 0')
1478 else:
1479 return context._raise_error(DivisionUndefined, '0 % 0')
1480
1481 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001482 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001483 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001484
1485 def __rmod__(self, other, context=None):
1486 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001487 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001488 if other is NotImplemented:
1489 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001490 return other.__mod__(self, context=context)
1491
1492 def remainder_near(self, other, context=None):
1493 """
1494 Remainder nearest to 0- abs(remainder-near) <= other/2
1495 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001496 if context is None:
1497 context = getcontext()
1498
1499 other = _convert_other(other, raiseit=True)
1500
1501 ans = self._check_nans(other, context)
1502 if ans:
1503 return ans
1504
1505 # self == +/-infinity -> InvalidOperation
1506 if self._isinfinity():
1507 return context._raise_error(InvalidOperation,
1508 'remainder_near(infinity, x)')
1509
1510 # other == 0 -> either InvalidOperation or DivisionUndefined
1511 if not other:
1512 if self:
1513 return context._raise_error(InvalidOperation,
1514 'remainder_near(x, 0)')
1515 else:
1516 return context._raise_error(DivisionUndefined,
1517 'remainder_near(0, 0)')
1518
1519 # other = +/-infinity -> remainder = self
1520 if other._isinfinity():
1521 ans = Decimal(self)
1522 return ans._fix(context)
1523
1524 # self = 0 -> remainder = self, with ideal exponent
1525 ideal_exponent = min(self._exp, other._exp)
1526 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001527 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001528 return ans._fix(context)
1529
1530 # catch most cases of large or small quotient
1531 expdiff = self.adjusted() - other.adjusted()
1532 if expdiff >= context.prec + 1:
1533 # expdiff >= prec+1 => abs(self/other) > 10**prec
1534 return context._raise_error(DivisionImpossible)
1535 if expdiff <= -2:
1536 # expdiff <= -2 => abs(self/other) < 0.1
1537 ans = self._rescale(ideal_exponent, context.rounding)
1538 return ans._fix(context)
1539
1540 # adjust both arguments to have the same exponent, then divide
1541 op1 = _WorkRep(self)
1542 op2 = _WorkRep(other)
1543 if op1.exp >= op2.exp:
1544 op1.int *= 10**(op1.exp - op2.exp)
1545 else:
1546 op2.int *= 10**(op2.exp - op1.exp)
1547 q, r = divmod(op1.int, op2.int)
1548 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1549 # 10**ideal_exponent. Apply correction to ensure that
1550 # abs(remainder) <= abs(other)/2
1551 if 2*r + (q&1) > op2.int:
1552 r -= op2.int
1553 q += 1
1554
1555 if q >= 10**context.prec:
1556 return context._raise_error(DivisionImpossible)
1557
1558 # result has same sign as self unless r is negative
1559 sign = self._sign
1560 if r < 0:
1561 sign = 1-sign
1562 r = -r
1563
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001564 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001565 return ans._fix(context)
1566
1567 def __floordiv__(self, other, context=None):
1568 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001569 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001570 if other is NotImplemented:
1571 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001572
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001573 if context is None:
1574 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001575
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001576 ans = self._check_nans(other, context)
1577 if ans:
1578 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001579
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001580 if self._isinfinity():
1581 if other._isinfinity():
1582 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001583 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001584 return _SignedInfinity[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001585
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001586 if not other:
1587 if self:
1588 return context._raise_error(DivisionByZero, 'x // 0',
1589 self._sign ^ other._sign)
1590 else:
1591 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001592
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001593 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001594
1595 def __rfloordiv__(self, other, context=None):
1596 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001597 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001598 if other is NotImplemented:
1599 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001600 return other.__floordiv__(self, context=context)
1601
1602 def __float__(self):
1603 """Float representation."""
1604 return float(str(self))
1605
1606 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001607 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001608 if self._is_special:
1609 if self._isnan():
Mark Dickinson825fce32009-09-07 18:08:12 +00001610 raise ValueError("Cannot convert NaN to integer")
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001611 elif self._isinfinity():
Mark Dickinson825fce32009-09-07 18:08:12 +00001612 raise OverflowError("Cannot convert infinity to integer")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001613 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001614 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001615 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001616 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001617 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001618
Christian Heimes969fe572008-01-25 11:23:10 +00001619 __trunc__ = __int__
1620
Christian Heimes0bd4e112008-02-12 22:59:25 +00001621 def real(self):
1622 return self
Mark Dickinson315a20a2009-01-04 21:34:18 +00001623 real = property(real)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001624
Christian Heimes0bd4e112008-02-12 22:59:25 +00001625 def imag(self):
1626 return Decimal(0)
Mark Dickinson315a20a2009-01-04 21:34:18 +00001627 imag = property(imag)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001628
1629 def conjugate(self):
1630 return self
1631
1632 def __complex__(self):
1633 return complex(float(self))
1634
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001635 def _fix_nan(self, context):
1636 """Decapitate the payload of a NaN to fit the context"""
1637 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001638
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001639 # maximum length of payload is precision if clamp=0,
1640 # precision-1 if clamp=1.
1641 max_payload_len = context.prec - context.clamp
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001642 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001643 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1644 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001645 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001646
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001647 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001648 """Round if it is necessary to keep self within prec precision.
1649
1650 Rounds and fixes the exponent. Does not raise on a sNaN.
1651
1652 Arguments:
1653 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001654 context - context used.
1655 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001656
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001657 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001658 if self._isnan():
1659 # decapitate payload if necessary
1660 return self._fix_nan(context)
1661 else:
1662 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001663 return Decimal(self)
1664
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001665 # if self is zero then exponent should be between Etiny and
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001666 # Emax if clamp==0, and between Etiny and Etop if clamp==1.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001667 Etiny = context.Etiny()
1668 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001669 if not self:
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001670 exp_max = [context.Emax, Etop][context.clamp]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001671 new_exp = min(max(self._exp, Etiny), exp_max)
1672 if new_exp != self._exp:
1673 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001674 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001675 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001676 return Decimal(self)
1677
1678 # exp_min is the smallest allowable exponent of the result,
1679 # equal to max(self.adjusted()-context.prec+1, Etiny)
1680 exp_min = len(self._int) + self._exp - context.prec
1681 if exp_min > Etop:
1682 # overflow: exp_min > Etop iff self.adjusted() > Emax
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001683 ans = context._raise_error(Overflow, 'above Emax', self._sign)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001684 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001685 context._raise_error(Rounded)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001686 return ans
1687
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001688 self_is_subnormal = exp_min < Etiny
1689 if self_is_subnormal:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001690 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001691
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001692 # round if self has too many digits
1693 if self._exp < exp_min:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001694 digits = len(self._int) + self._exp - exp_min
1695 if digits < 0:
1696 self = _dec_from_triple(self._sign, '1', exp_min-1)
1697 digits = 0
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001698 rounding_method = self._pick_rounding_function[context.rounding]
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04001699 changed = rounding_method(self, digits)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001700 coeff = self._int[:digits] or '0'
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001701 if changed > 0:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001702 coeff = str(int(coeff)+1)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001703 if len(coeff) > context.prec:
1704 coeff = coeff[:-1]
1705 exp_min += 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001706
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001707 # check whether the rounding pushed the exponent out of range
1708 if exp_min > Etop:
1709 ans = context._raise_error(Overflow, 'above Emax', self._sign)
1710 else:
1711 ans = _dec_from_triple(self._sign, coeff, exp_min)
1712
1713 # raise the appropriate signals, taking care to respect
1714 # the precedence described in the specification
1715 if changed and self_is_subnormal:
1716 context._raise_error(Underflow)
1717 if self_is_subnormal:
1718 context._raise_error(Subnormal)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001719 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001720 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001721 context._raise_error(Rounded)
1722 if not ans:
1723 # raise Clamped on underflow to 0
1724 context._raise_error(Clamped)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001725 return ans
1726
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001727 if self_is_subnormal:
1728 context._raise_error(Subnormal)
1729
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001730 # fold down if clamp == 1 and self has too few digits
1731 if context.clamp == 1 and self._exp > Etop:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001732 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001733 self_padded = self._int + '0'*(self._exp - Etop)
1734 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001735
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001736 # here self was representable to begin with; return unchanged
1737 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001738
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001739 # for each of the rounding functions below:
1740 # self is a finite, nonzero Decimal
1741 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001742 #
1743 # each function returns either -1, 0, or 1, as follows:
1744 # 1 indicates that self should be rounded up (away from zero)
1745 # 0 indicates that self should be truncated, and that all the
1746 # digits to be truncated are zeros (so the value is unchanged)
1747 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001748
1749 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001750 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001751 if _all_zeros(self._int, prec):
1752 return 0
1753 else:
1754 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001755
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001756 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001757 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001758 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001759
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001760 def _round_half_up(self, prec):
1761 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001762 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001763 return 1
1764 elif _all_zeros(self._int, prec):
1765 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001766 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001767 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001768
1769 def _round_half_down(self, prec):
1770 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001771 if _exact_half(self._int, prec):
1772 return -1
1773 else:
1774 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001775
1776 def _round_half_even(self, prec):
1777 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001778 if _exact_half(self._int, prec) and \
1779 (prec == 0 or self._int[prec-1] in '02468'):
1780 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001781 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001782 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001783
1784 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001785 """Rounds up (not away from 0 if negative.)"""
1786 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001787 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001788 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001789 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001790
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001791 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001792 """Rounds down (not towards 0 if negative)"""
1793 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001794 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001795 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001796 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001797
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001798 def _round_05up(self, prec):
1799 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001800 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001801 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001802 else:
1803 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001804
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04001805 _pick_rounding_function = dict(
1806 ROUND_DOWN = _round_down,
1807 ROUND_UP = _round_up,
1808 ROUND_HALF_UP = _round_half_up,
1809 ROUND_HALF_DOWN = _round_half_down,
1810 ROUND_HALF_EVEN = _round_half_even,
1811 ROUND_CEILING = _round_ceiling,
1812 ROUND_FLOOR = _round_floor,
1813 ROUND_05UP = _round_05up,
1814 )
1815
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001816 def __round__(self, n=None):
1817 """Round self to the nearest integer, or to a given precision.
1818
1819 If only one argument is supplied, round a finite Decimal
1820 instance self to the nearest integer. If self is infinite or
1821 a NaN then a Python exception is raised. If self is finite
1822 and lies exactly halfway between two integers then it is
1823 rounded to the integer with even last digit.
1824
1825 >>> round(Decimal('123.456'))
1826 123
1827 >>> round(Decimal('-456.789'))
1828 -457
1829 >>> round(Decimal('-3.0'))
1830 -3
1831 >>> round(Decimal('2.5'))
1832 2
1833 >>> round(Decimal('3.5'))
1834 4
1835 >>> round(Decimal('Inf'))
1836 Traceback (most recent call last):
1837 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001838 OverflowError: cannot round an infinity
1839 >>> round(Decimal('NaN'))
1840 Traceback (most recent call last):
1841 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001842 ValueError: cannot round a NaN
1843
1844 If a second argument n is supplied, self is rounded to n
1845 decimal places using the rounding mode for the current
1846 context.
1847
1848 For an integer n, round(self, -n) is exactly equivalent to
1849 self.quantize(Decimal('1En')).
1850
1851 >>> round(Decimal('123.456'), 0)
1852 Decimal('123')
1853 >>> round(Decimal('123.456'), 2)
1854 Decimal('123.46')
1855 >>> round(Decimal('123.456'), -2)
1856 Decimal('1E+2')
1857 >>> round(Decimal('-Infinity'), 37)
1858 Decimal('NaN')
1859 >>> round(Decimal('sNaN123'), 0)
1860 Decimal('NaN123')
1861
1862 """
1863 if n is not None:
1864 # two-argument form: use the equivalent quantize call
1865 if not isinstance(n, int):
1866 raise TypeError('Second argument to round should be integral')
1867 exp = _dec_from_triple(0, '1', -n)
1868 return self.quantize(exp)
1869
1870 # one-argument form
1871 if self._is_special:
1872 if self.is_nan():
1873 raise ValueError("cannot round a NaN")
1874 else:
1875 raise OverflowError("cannot round an infinity")
1876 return int(self._rescale(0, ROUND_HALF_EVEN))
1877
1878 def __floor__(self):
1879 """Return the floor of self, as an integer.
1880
1881 For a finite Decimal instance self, return the greatest
1882 integer n such that n <= self. If self is infinite or a NaN
1883 then a Python exception is raised.
1884
1885 """
1886 if self._is_special:
1887 if self.is_nan():
1888 raise ValueError("cannot round a NaN")
1889 else:
1890 raise OverflowError("cannot round an infinity")
1891 return int(self._rescale(0, ROUND_FLOOR))
1892
1893 def __ceil__(self):
1894 """Return the ceiling of self, as an integer.
1895
1896 For a finite Decimal instance self, return the least integer n
1897 such that n >= self. If self is infinite or a NaN then a
1898 Python exception is raised.
1899
1900 """
1901 if self._is_special:
1902 if self.is_nan():
1903 raise ValueError("cannot round a NaN")
1904 else:
1905 raise OverflowError("cannot round an infinity")
1906 return int(self._rescale(0, ROUND_CEILING))
1907
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001908 def fma(self, other, third, context=None):
1909 """Fused multiply-add.
1910
1911 Returns self*other+third with no rounding of the intermediate
1912 product self*other.
1913
1914 self and other are multiplied together, with no rounding of
1915 the result. The third operand is then added to the result,
1916 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001917 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001918
1919 other = _convert_other(other, raiseit=True)
Mark Dickinsonb455e582011-05-22 12:53:18 +01001920 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001921
1922 # compute product; raise InvalidOperation if either operand is
1923 # a signaling NaN or if the product is zero times infinity.
1924 if self._is_special or other._is_special:
1925 if context is None:
1926 context = getcontext()
1927 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001928 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001929 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001930 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001931 if self._exp == 'n':
1932 product = self
1933 elif other._exp == 'n':
1934 product = other
1935 elif self._exp == 'F':
1936 if not other:
1937 return context._raise_error(InvalidOperation,
1938 'INF * 0 in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001939 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001940 elif other._exp == 'F':
1941 if not self:
1942 return context._raise_error(InvalidOperation,
1943 '0 * INF in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001944 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001945 else:
1946 product = _dec_from_triple(self._sign ^ other._sign,
1947 str(int(self._int) * int(other._int)),
1948 self._exp + other._exp)
1949
Christian Heimes8b0facf2007-12-04 19:30:01 +00001950 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001951
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001952 def _power_modulo(self, other, modulo, context=None):
1953 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001954
Stefan Krah1919b7e2012-03-21 18:25:23 +01001955 other = _convert_other(other)
1956 if other is NotImplemented:
1957 return other
1958 modulo = _convert_other(modulo)
1959 if modulo is NotImplemented:
1960 return modulo
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001961
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001962 if context is None:
1963 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001964
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001965 # deal with NaNs: if there are any sNaNs then first one wins,
1966 # (i.e. behaviour for NaNs is identical to that of fma)
1967 self_is_nan = self._isnan()
1968 other_is_nan = other._isnan()
1969 modulo_is_nan = modulo._isnan()
1970 if self_is_nan or other_is_nan or modulo_is_nan:
1971 if self_is_nan == 2:
1972 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001973 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001974 if other_is_nan == 2:
1975 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001976 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001977 if modulo_is_nan == 2:
1978 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001979 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001980 if self_is_nan:
1981 return self._fix_nan(context)
1982 if other_is_nan:
1983 return other._fix_nan(context)
1984 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001985
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001986 # check inputs: we apply same restrictions as Python's pow()
1987 if not (self._isinteger() and
1988 other._isinteger() and
1989 modulo._isinteger()):
1990 return context._raise_error(InvalidOperation,
1991 'pow() 3rd argument not allowed '
1992 'unless all arguments are integers')
1993 if other < 0:
1994 return context._raise_error(InvalidOperation,
1995 'pow() 2nd argument cannot be '
1996 'negative when 3rd argument specified')
1997 if not modulo:
1998 return context._raise_error(InvalidOperation,
1999 'pow() 3rd argument cannot be 0')
2000
2001 # additional restriction for decimal: the modulus must be less
2002 # than 10**prec in absolute value
2003 if modulo.adjusted() >= context.prec:
2004 return context._raise_error(InvalidOperation,
2005 'insufficient precision: pow() 3rd '
2006 'argument must not have more than '
2007 'precision digits')
2008
2009 # define 0**0 == NaN, for consistency with two-argument pow
2010 # (even though it hurts!)
2011 if not other and not self:
2012 return context._raise_error(InvalidOperation,
2013 'at least one of pow() 1st argument '
2014 'and 2nd argument must be nonzero ;'
2015 '0**0 is not defined')
2016
2017 # compute sign of result
2018 if other._iseven():
2019 sign = 0
2020 else:
2021 sign = self._sign
2022
2023 # convert modulo to a Python integer, and self and other to
2024 # Decimal integers (i.e. force their exponents to be >= 0)
2025 modulo = abs(int(modulo))
2026 base = _WorkRep(self.to_integral_value())
2027 exponent = _WorkRep(other.to_integral_value())
2028
2029 # compute result using integer pow()
2030 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
2031 for i in range(exponent.exp):
2032 base = pow(base, 10, modulo)
2033 base = pow(base, exponent.int, modulo)
2034
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002035 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002036
2037 def _power_exact(self, other, p):
2038 """Attempt to compute self**other exactly.
2039
2040 Given Decimals self and other and an integer p, attempt to
2041 compute an exact result for the power self**other, with p
2042 digits of precision. Return None if self**other is not
2043 exactly representable in p digits.
2044
2045 Assumes that elimination of special cases has already been
2046 performed: self and other must both be nonspecial; self must
2047 be positive and not numerically equal to 1; other must be
2048 nonzero. For efficiency, other._exp should not be too large,
2049 so that 10**abs(other._exp) is a feasible calculation."""
2050
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002051 # In the comments below, we write x for the value of self and y for the
2052 # value of other. Write x = xc*10**xe and abs(y) = yc*10**ye, with xc
2053 # and yc positive integers not divisible by 10.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002054
2055 # The main purpose of this method is to identify the *failure*
2056 # of x**y to be exactly representable with as little effort as
2057 # possible. So we look for cheap and easy tests that
2058 # eliminate the possibility of x**y being exact. Only if all
2059 # these tests are passed do we go on to actually compute x**y.
2060
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002061 # Here's the main idea. Express y as a rational number m/n, with m and
2062 # n relatively prime and n>0. Then for x**y to be exactly
2063 # representable (at *any* precision), xc must be the nth power of a
2064 # positive integer and xe must be divisible by n. If y is negative
2065 # then additionally xc must be a power of either 2 or 5, hence a power
2066 # of 2**n or 5**n.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002067 #
2068 # There's a limit to how small |y| can be: if y=m/n as above
2069 # then:
2070 #
2071 # (1) if xc != 1 then for the result to be representable we
2072 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
2073 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
2074 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
2075 # representable.
2076 #
2077 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
2078 # |y| < 1/|xe| then the result is not representable.
2079 #
2080 # Note that since x is not equal to 1, at least one of (1) and
2081 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
2082 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
2083 #
2084 # There's also a limit to how large y can be, at least if it's
2085 # positive: the normalized result will have coefficient xc**y,
2086 # so if it's representable then xc**y < 10**p, and y <
2087 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
2088 # not exactly representable.
2089
2090 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
2091 # so |y| < 1/xe and the result is not representable.
2092 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
2093 # < 1/nbits(xc).
2094
2095 x = _WorkRep(self)
2096 xc, xe = x.int, x.exp
2097 while xc % 10 == 0:
2098 xc //= 10
2099 xe += 1
2100
2101 y = _WorkRep(other)
2102 yc, ye = y.int, y.exp
2103 while yc % 10 == 0:
2104 yc //= 10
2105 ye += 1
2106
2107 # case where xc == 1: result is 10**(xe*y), with xe*y
2108 # required to be an integer
2109 if xc == 1:
Mark Dickinsona1236312010-07-08 19:03:34 +00002110 xe *= yc
2111 # result is now 10**(xe * 10**ye); xe * 10**ye must be integral
2112 while xe % 10 == 0:
2113 xe //= 10
2114 ye += 1
2115 if ye < 0:
2116 return None
2117 exponent = xe * 10**ye
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002118 if y.sign == 1:
2119 exponent = -exponent
2120 # if other is a nonnegative integer, use ideal exponent
2121 if other._isinteger() and other._sign == 0:
2122 ideal_exponent = self._exp*int(other)
2123 zeros = min(exponent-ideal_exponent, p-1)
2124 else:
2125 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002126 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002127
2128 # case where y is negative: xc must be either a power
2129 # of 2 or a power of 5.
2130 if y.sign == 1:
2131 last_digit = xc % 10
2132 if last_digit in (2,4,6,8):
2133 # quick test for power of 2
2134 if xc & -xc != xc:
2135 return None
2136 # now xc is a power of 2; e is its exponent
2137 e = _nbits(xc)-1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002138
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002139 # We now have:
2140 #
2141 # x = 2**e * 10**xe, e > 0, and y < 0.
2142 #
2143 # The exact result is:
2144 #
2145 # x**y = 5**(-e*y) * 10**(e*y + xe*y)
2146 #
2147 # provided that both e*y and xe*y are integers. Note that if
2148 # 5**(-e*y) >= 10**p, then the result can't be expressed
2149 # exactly with p digits of precision.
2150 #
2151 # Using the above, we can guard against large values of ye.
2152 # 93/65 is an upper bound for log(10)/log(5), so if
2153 #
2154 # ye >= len(str(93*p//65))
2155 #
2156 # then
2157 #
2158 # -e*y >= -y >= 10**ye > 93*p/65 > p*log(10)/log(5),
2159 #
2160 # so 5**(-e*y) >= 10**p, and the coefficient of the result
2161 # can't be expressed in p digits.
2162
2163 # emax >= largest e such that 5**e < 10**p.
2164 emax = p*93//65
2165 if ye >= len(str(emax)):
2166 return None
2167
2168 # Find -e*y and -xe*y; both must be integers
2169 e = _decimal_lshift_exact(e * yc, ye)
2170 xe = _decimal_lshift_exact(xe * yc, ye)
2171 if e is None or xe is None:
2172 return None
2173
2174 if e > emax:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002175 return None
2176 xc = 5**e
2177
2178 elif last_digit == 5:
2179 # e >= log_5(xc) if xc is a power of 5; we have
2180 # equality all the way up to xc=5**2658
2181 e = _nbits(xc)*28//65
2182 xc, remainder = divmod(5**e, xc)
2183 if remainder:
2184 return None
2185 while xc % 5 == 0:
2186 xc //= 5
2187 e -= 1
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002188
2189 # Guard against large values of ye, using the same logic as in
2190 # the 'xc is a power of 2' branch. 10/3 is an upper bound for
2191 # log(10)/log(2).
2192 emax = p*10//3
2193 if ye >= len(str(emax)):
2194 return None
2195
2196 e = _decimal_lshift_exact(e * yc, ye)
2197 xe = _decimal_lshift_exact(xe * yc, ye)
2198 if e is None or xe is None:
2199 return None
2200
2201 if e > emax:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002202 return None
2203 xc = 2**e
2204 else:
2205 return None
2206
2207 if xc >= 10**p:
2208 return None
2209 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002210 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002211
2212 # now y is positive; find m and n such that y = m/n
2213 if ye >= 0:
2214 m, n = yc*10**ye, 1
2215 else:
2216 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2217 return None
2218 xc_bits = _nbits(xc)
2219 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2220 return None
2221 m, n = yc, 10**(-ye)
2222 while m % 2 == n % 2 == 0:
2223 m //= 2
2224 n //= 2
2225 while m % 5 == n % 5 == 0:
2226 m //= 5
2227 n //= 5
2228
2229 # compute nth root of xc*10**xe
2230 if n > 1:
2231 # if 1 < xc < 2**n then xc isn't an nth power
2232 if xc != 1 and xc_bits <= n:
2233 return None
2234
2235 xe, rem = divmod(xe, n)
2236 if rem != 0:
2237 return None
2238
2239 # compute nth root of xc using Newton's method
2240 a = 1 << -(-_nbits(xc)//n) # initial estimate
2241 while True:
2242 q, r = divmod(xc, a**(n-1))
2243 if a <= q:
2244 break
2245 else:
2246 a = (a*(n-1) + q)//n
2247 if not (a == q and r == 0):
2248 return None
2249 xc = a
2250
2251 # now xc*10**xe is the nth root of the original xc*10**xe
2252 # compute mth power of xc*10**xe
2253
2254 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2255 # 10**p and the result is not representable.
2256 if xc > 1 and m > p*100//_log10_lb(xc):
2257 return None
2258 xc = xc**m
2259 xe *= m
2260 if xc > 10**p:
2261 return None
2262
2263 # by this point the result *is* exactly representable
2264 # adjust the exponent to get as close as possible to the ideal
2265 # exponent, if necessary
2266 str_xc = str(xc)
2267 if other._isinteger() and other._sign == 0:
2268 ideal_exponent = self._exp*int(other)
2269 zeros = min(xe-ideal_exponent, p-len(str_xc))
2270 else:
2271 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002272 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002273
2274 def __pow__(self, other, modulo=None, context=None):
2275 """Return self ** other [ % modulo].
2276
2277 With two arguments, compute self**other.
2278
2279 With three arguments, compute (self**other) % modulo. For the
2280 three argument form, the following restrictions on the
2281 arguments hold:
2282
2283 - all three arguments must be integral
2284 - other must be nonnegative
2285 - either self or other (or both) must be nonzero
2286 - modulo must be nonzero and must have at most p digits,
2287 where p is the context precision.
2288
2289 If any of these restrictions is violated the InvalidOperation
2290 flag is raised.
2291
2292 The result of pow(self, other, modulo) is identical to the
2293 result that would be obtained by computing (self**other) %
2294 modulo with unbounded precision, but is computed more
2295 efficiently. It is always exact.
2296 """
2297
2298 if modulo is not None:
2299 return self._power_modulo(other, modulo, context)
2300
2301 other = _convert_other(other)
2302 if other is NotImplemented:
2303 return other
2304
2305 if context is None:
2306 context = getcontext()
2307
2308 # either argument is a NaN => result is NaN
2309 ans = self._check_nans(other, context)
2310 if ans:
2311 return ans
2312
2313 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2314 if not other:
2315 if not self:
2316 return context._raise_error(InvalidOperation, '0 ** 0')
2317 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002318 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002319
2320 # result has sign 1 iff self._sign is 1 and other is an odd integer
2321 result_sign = 0
2322 if self._sign == 1:
2323 if other._isinteger():
2324 if not other._iseven():
2325 result_sign = 1
2326 else:
2327 # -ve**noninteger = NaN
2328 # (-0)**noninteger = 0**noninteger
2329 if self:
2330 return context._raise_error(InvalidOperation,
2331 'x ** y with x negative and y not an integer')
2332 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002333 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002334
2335 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2336 if not self:
2337 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002338 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002339 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002340 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002341
2342 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002343 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002344 if other._sign == 0:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002345 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002346 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002347 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002348
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002349 # 1**other = 1, but the choice of exponent and the flags
2350 # depend on the exponent of self, and on whether other is a
2351 # positive integer, a negative integer, or neither
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002352 if self == _One:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002353 if other._isinteger():
2354 # exp = max(self._exp*max(int(other), 0),
2355 # 1-context.prec) but evaluating int(other) directly
2356 # is dangerous until we know other is small (other
2357 # could be 1e999999999)
2358 if other._sign == 1:
2359 multiplier = 0
2360 elif other > context.prec:
2361 multiplier = context.prec
2362 else:
2363 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002364
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002365 exp = self._exp * multiplier
2366 if exp < 1-context.prec:
2367 exp = 1-context.prec
2368 context._raise_error(Rounded)
2369 else:
2370 context._raise_error(Inexact)
2371 context._raise_error(Rounded)
2372 exp = 1-context.prec
2373
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002374 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002375
2376 # compute adjusted exponent of self
2377 self_adj = self.adjusted()
2378
2379 # self ** infinity is infinity if self > 1, 0 if self < 1
2380 # self ** -infinity is infinity if self < 1, 0 if self > 1
2381 if other._isinfinity():
2382 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002383 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002384 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002385 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002386
2387 # from here on, the result always goes through the call
2388 # to _fix at the end of this function.
2389 ans = None
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002390 exact = False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002391
2392 # crude test to catch cases of extreme overflow/underflow. If
2393 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2394 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2395 # self**other >= 10**(Emax+1), so overflow occurs. The test
2396 # for underflow is similar.
2397 bound = self._log10_exp_bound() + other.adjusted()
2398 if (self_adj >= 0) == (other._sign == 0):
2399 # self > 1 and other +ve, or self < 1 and other -ve
2400 # possibility of overflow
2401 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002402 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002403 else:
2404 # self > 1 and other -ve, or self < 1 and other +ve
2405 # possibility of underflow to 0
2406 Etiny = context.Etiny()
2407 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002408 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002409
2410 # try for an exact result with precision +1
2411 if ans is None:
2412 ans = self._power_exact(other, context.prec + 1)
Mark Dickinsone42f1bb2010-07-08 19:09:16 +00002413 if ans is not None:
2414 if result_sign == 1:
2415 ans = _dec_from_triple(1, ans._int, ans._exp)
2416 exact = True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002417
2418 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2419 if ans is None:
2420 p = context.prec
2421 x = _WorkRep(self)
2422 xc, xe = x.int, x.exp
2423 y = _WorkRep(other)
2424 yc, ye = y.int, y.exp
2425 if y.sign == 1:
2426 yc = -yc
2427
2428 # compute correctly rounded result: start with precision +3,
2429 # then increase precision until result is unambiguously roundable
2430 extra = 3
2431 while True:
2432 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2433 if coeff % (5*10**(len(str(coeff))-p-1)):
2434 break
2435 extra += 3
2436
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002437 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002438
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002439 # unlike exp, ln and log10, the power function respects the
2440 # rounding mode; no need to switch to ROUND_HALF_EVEN here
2441
2442 # There's a difficulty here when 'other' is not an integer and
2443 # the result is exact. In this case, the specification
2444 # requires that the Inexact flag be raised (in spite of
2445 # exactness), but since the result is exact _fix won't do this
2446 # for us. (Correspondingly, the Underflow signal should also
2447 # be raised for subnormal results.) We can't directly raise
2448 # these signals either before or after calling _fix, since
2449 # that would violate the precedence for signals. So we wrap
2450 # the ._fix call in a temporary context, and reraise
2451 # afterwards.
2452 if exact and not other._isinteger():
2453 # pad with zeros up to length context.prec+1 if necessary; this
2454 # ensures that the Rounded signal will be raised.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002455 if len(ans._int) <= context.prec:
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002456 expdiff = context.prec + 1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002457 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2458 ans._exp-expdiff)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002459
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002460 # create a copy of the current context, with cleared flags/traps
2461 newcontext = context.copy()
2462 newcontext.clear_flags()
2463 for exception in _signals:
2464 newcontext.traps[exception] = 0
2465
2466 # round in the new context
2467 ans = ans._fix(newcontext)
2468
2469 # raise Inexact, and if necessary, Underflow
2470 newcontext._raise_error(Inexact)
2471 if newcontext.flags[Subnormal]:
2472 newcontext._raise_error(Underflow)
2473
2474 # propagate signals to the original context; _fix could
2475 # have raised any of Overflow, Underflow, Subnormal,
2476 # Inexact, Rounded, Clamped. Overflow needs the correct
2477 # arguments. Note that the order of the exceptions is
2478 # important here.
2479 if newcontext.flags[Overflow]:
2480 context._raise_error(Overflow, 'above Emax', ans._sign)
2481 for exception in Underflow, Subnormal, Inexact, Rounded, Clamped:
2482 if newcontext.flags[exception]:
2483 context._raise_error(exception)
2484
2485 else:
2486 ans = ans._fix(context)
2487
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002488 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002489
2490 def __rpow__(self, other, context=None):
2491 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002492 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002493 if other is NotImplemented:
2494 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002495 return other.__pow__(self, context=context)
2496
2497 def normalize(self, context=None):
2498 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002499
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002500 if context is None:
2501 context = getcontext()
2502
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002503 if self._is_special:
2504 ans = self._check_nans(context=context)
2505 if ans:
2506 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002507
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002508 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002509 if dup._isinfinity():
2510 return dup
2511
2512 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002513 return _dec_from_triple(dup._sign, '0', 0)
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00002514 exp_max = [context.Emax, context.Etop()][context.clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002515 end = len(dup._int)
2516 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002517 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002518 exp += 1
2519 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002520 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002521
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002522 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002523 """Quantize self so its exponent is the same as that of exp.
2524
2525 Similar to self._rescale(exp._exp) but with error checking.
2526 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002527 exp = _convert_other(exp, raiseit=True)
2528
2529 if context is None:
2530 context = getcontext()
2531 if rounding is None:
2532 rounding = context.rounding
2533
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002534 if self._is_special or exp._is_special:
2535 ans = self._check_nans(exp, context)
2536 if ans:
2537 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002538
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002539 if exp._isinfinity() or self._isinfinity():
2540 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002541 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002542 return context._raise_error(InvalidOperation,
2543 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002544
2545 # if we're not watching exponents, do a simple rescale
2546 if not watchexp:
2547 ans = self._rescale(exp._exp, rounding)
2548 # raise Inexact and Rounded where appropriate
2549 if ans._exp > self._exp:
2550 context._raise_error(Rounded)
2551 if ans != self:
2552 context._raise_error(Inexact)
2553 return ans
2554
2555 # exp._exp should be between Etiny and Emax
2556 if not (context.Etiny() <= exp._exp <= context.Emax):
2557 return context._raise_error(InvalidOperation,
2558 'target exponent out of bounds in quantize')
2559
2560 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002561 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002562 return ans._fix(context)
2563
2564 self_adjusted = self.adjusted()
2565 if self_adjusted > context.Emax:
2566 return context._raise_error(InvalidOperation,
2567 'exponent of quantize result too large for current context')
2568 if self_adjusted - exp._exp + 1 > context.prec:
2569 return context._raise_error(InvalidOperation,
2570 'quantize result has too many digits for current context')
2571
2572 ans = self._rescale(exp._exp, rounding)
2573 if ans.adjusted() > context.Emax:
2574 return context._raise_error(InvalidOperation,
2575 'exponent of quantize result too large for current context')
2576 if len(ans._int) > context.prec:
2577 return context._raise_error(InvalidOperation,
2578 'quantize result has too many digits for current context')
2579
2580 # raise appropriate flags
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002581 if ans and ans.adjusted() < context.Emin:
2582 context._raise_error(Subnormal)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002583 if ans._exp > self._exp:
2584 if ans != self:
2585 context._raise_error(Inexact)
2586 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002587
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002588 # call to fix takes care of any necessary folddown, and
2589 # signals Clamped if necessary
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002590 ans = ans._fix(context)
2591 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002592
2593 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002594 """Return True if self and other have the same exponent; otherwise
2595 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002596
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002597 If either operand is a special value, the following rules are used:
2598 * return True if both operands are infinities
2599 * return True if both operands are NaNs
2600 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002601 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002602 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002603 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002604 return (self.is_nan() and other.is_nan() or
2605 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002606 return self._exp == other._exp
2607
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002608 def _rescale(self, exp, rounding):
2609 """Rescale self so that the exponent is exp, either by padding with zeros
2610 or by truncating digits, using the given rounding mode.
2611
2612 Specials are returned without change. This operation is
2613 quiet: it raises no flags, and uses no information from the
2614 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002615
2616 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002617 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002618 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002619 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002620 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002621 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002622 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002623
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002624 if self._exp >= exp:
2625 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002626 return _dec_from_triple(self._sign,
2627 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002628
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002629 # too many digits; round and lose data. If self.adjusted() <
2630 # exp-1, replace self by 10**(exp-1) before rounding
2631 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002632 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002633 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002634 digits = 0
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04002635 this_function = self._pick_rounding_function[rounding]
2636 changed = this_function(self, digits)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002637 coeff = self._int[:digits] or '0'
2638 if changed == 1:
2639 coeff = str(int(coeff)+1)
2640 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002641
Christian Heimesf16baeb2008-02-29 14:57:44 +00002642 def _round(self, places, rounding):
2643 """Round a nonzero, nonspecial Decimal to a fixed number of
2644 significant figures, using the given rounding mode.
2645
2646 Infinities, NaNs and zeros are returned unaltered.
2647
2648 This operation is quiet: it raises no flags, and uses no
2649 information from the context.
2650
2651 """
2652 if places <= 0:
2653 raise ValueError("argument should be at least 1 in _round")
2654 if self._is_special or not self:
2655 return Decimal(self)
2656 ans = self._rescale(self.adjusted()+1-places, rounding)
2657 # it can happen that the rescale alters the adjusted exponent;
2658 # for example when rounding 99.97 to 3 significant figures.
2659 # When this happens we end up with an extra 0 at the end of
2660 # the number; a second rescale fixes this.
2661 if ans.adjusted() != self.adjusted():
2662 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2663 return ans
2664
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002665 def to_integral_exact(self, rounding=None, context=None):
2666 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002667
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002668 If no rounding mode is specified, take the rounding mode from
2669 the context. This method raises the Rounded and Inexact flags
2670 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002671
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002672 See also: to_integral_value, which does exactly the same as
2673 this method except that it doesn't raise Inexact or Rounded.
2674 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002675 if self._is_special:
2676 ans = self._check_nans(context=context)
2677 if ans:
2678 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002679 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002680 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002681 return Decimal(self)
2682 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002683 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002684 if context is None:
2685 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002686 if rounding is None:
2687 rounding = context.rounding
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002688 ans = self._rescale(0, rounding)
2689 if ans != self:
2690 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002691 context._raise_error(Rounded)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002692 return ans
2693
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002694 def to_integral_value(self, rounding=None, context=None):
2695 """Rounds to the nearest integer, without raising inexact, rounded."""
2696 if context is None:
2697 context = getcontext()
2698 if rounding is None:
2699 rounding = context.rounding
2700 if self._is_special:
2701 ans = self._check_nans(context=context)
2702 if ans:
2703 return ans
2704 return Decimal(self)
2705 if self._exp >= 0:
2706 return Decimal(self)
2707 else:
2708 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002709
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002710 # the method name changed, but we provide also the old one, for compatibility
2711 to_integral = to_integral_value
2712
2713 def sqrt(self, context=None):
2714 """Return the square root of self."""
Christian Heimes0348fb62008-03-26 12:55:56 +00002715 if context is None:
2716 context = getcontext()
2717
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002718 if self._is_special:
2719 ans = self._check_nans(context=context)
2720 if ans:
2721 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002722
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002723 if self._isinfinity() and self._sign == 0:
2724 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002725
2726 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002727 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002728 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002729 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002730
2731 if self._sign == 1:
2732 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2733
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002734 # At this point self represents a positive number. Let p be
2735 # the desired precision and express self in the form c*100**e
2736 # with c a positive real number and e an integer, c and e
2737 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2738 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2739 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2740 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2741 # the closest integer to sqrt(c) with the even integer chosen
2742 # in the case of a tie.
2743 #
2744 # To ensure correct rounding in all cases, we use the
2745 # following trick: we compute the square root to an extra
2746 # place (precision p+1 instead of precision p), rounding down.
2747 # Then, if the result is inexact and its last digit is 0 or 5,
2748 # we increase the last digit to 1 or 6 respectively; if it's
2749 # exact we leave the last digit alone. Now the final round to
2750 # p places (or fewer in the case of underflow) will round
2751 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002752
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002753 # use an extra digit of precision
2754 prec = context.prec+1
2755
2756 # write argument in the form c*100**e where e = self._exp//2
2757 # is the 'ideal' exponent, to be used if the square root is
2758 # exactly representable. l is the number of 'digits' of c in
2759 # base 100, so that 100**(l-1) <= c < 100**l.
2760 op = _WorkRep(self)
2761 e = op.exp >> 1
2762 if op.exp & 1:
2763 c = op.int * 10
2764 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002765 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002766 c = op.int
2767 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002768
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002769 # rescale so that c has exactly prec base 100 'digits'
2770 shift = prec-l
2771 if shift >= 0:
2772 c *= 100**shift
2773 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002774 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002775 c, remainder = divmod(c, 100**-shift)
2776 exact = not remainder
2777 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002778
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002779 # find n = floor(sqrt(c)) using Newton's method
2780 n = 10**prec
2781 while True:
2782 q = c//n
2783 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002784 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002785 else:
2786 n = n + q >> 1
2787 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002788
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002789 if exact:
2790 # result is exact; rescale to use ideal exponent e
2791 if shift >= 0:
2792 # assert n % 10**shift == 0
2793 n //= 10**shift
2794 else:
2795 n *= 10**-shift
2796 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002797 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002798 # result is not exact; fix last digit as described above
2799 if n % 5 == 0:
2800 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002801
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002802 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002803
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002804 # round, and fit to current context
2805 context = context._shallow_copy()
2806 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002807 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002808 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002809
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002810 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002811
2812 def max(self, other, context=None):
2813 """Returns the larger value.
2814
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002815 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002816 NaN (and signals if one is sNaN). Also rounds.
2817 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002818 other = _convert_other(other, raiseit=True)
2819
2820 if context is None:
2821 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002822
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002823 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002824 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002825 # number is always returned
2826 sn = self._isnan()
2827 on = other._isnan()
2828 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002829 if on == 1 and sn == 0:
2830 return self._fix(context)
2831 if sn == 1 and on == 0:
2832 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002833 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002834
Christian Heimes77c02eb2008-02-09 02:18:51 +00002835 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002836 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002837 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002838 # then an ordering is applied:
2839 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002840 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002841 # positive sign and min returns the operand with the negative sign
2842 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002843 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002844 # the result. This is exactly the ordering used in compare_total.
2845 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002846
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002847 if c == -1:
2848 ans = other
2849 else:
2850 ans = self
2851
Christian Heimes2c181612007-12-17 20:04:13 +00002852 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002853
2854 def min(self, other, context=None):
2855 """Returns the smaller value.
2856
Guido van Rossumd8faa362007-04-27 19:54:29 +00002857 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002858 NaN (and signals if one is sNaN). Also rounds.
2859 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002860 other = _convert_other(other, raiseit=True)
2861
2862 if context is None:
2863 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002864
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002865 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002866 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002867 # number is always returned
2868 sn = self._isnan()
2869 on = other._isnan()
2870 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002871 if on == 1 and sn == 0:
2872 return self._fix(context)
2873 if sn == 1 and on == 0:
2874 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002875 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002876
Christian Heimes77c02eb2008-02-09 02:18:51 +00002877 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002878 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002879 c = self.compare_total(other)
2880
2881 if c == -1:
2882 ans = self
2883 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002884 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002885
Christian Heimes2c181612007-12-17 20:04:13 +00002886 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002887
2888 def _isinteger(self):
2889 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002890 if self._is_special:
2891 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002892 if self._exp >= 0:
2893 return True
2894 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002895 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002896
2897 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002898 """Returns True if self is even. Assumes self is an integer."""
2899 if not self or self._exp > 0:
2900 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002901 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002902
2903 def adjusted(self):
2904 """Return the adjusted exponent of self"""
2905 try:
2906 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002907 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002908 except TypeError:
2909 return 0
2910
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002911 def canonical(self, context=None):
2912 """Returns the same Decimal object.
2913
2914 As we do not have different encodings for the same number, the
2915 received object already is in its canonical form.
2916 """
2917 return self
2918
2919 def compare_signal(self, other, context=None):
2920 """Compares self to the other operand numerically.
2921
2922 It's pretty much like compare(), but all NaNs signal, with signaling
2923 NaNs taking precedence over quiet NaNs.
2924 """
Christian Heimes77c02eb2008-02-09 02:18:51 +00002925 other = _convert_other(other, raiseit = True)
2926 ans = self._compare_check_nans(other, context)
2927 if ans:
2928 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002929 return self.compare(other, context=context)
2930
2931 def compare_total(self, other):
2932 """Compares self to other using the abstract representations.
2933
2934 This is not like the standard compare, which use their numerical
2935 value. Note that a total ordering is defined for all possible abstract
2936 representations.
2937 """
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00002938 other = _convert_other(other, raiseit=True)
2939
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002940 # if one is negative and the other is positive, it's easy
2941 if self._sign and not other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002942 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002943 if not self._sign and other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002944 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002945 sign = self._sign
2946
2947 # let's handle both NaN types
2948 self_nan = self._isnan()
2949 other_nan = other._isnan()
2950 if self_nan or other_nan:
2951 if self_nan == other_nan:
Mark Dickinsond314e1b2009-08-28 13:39:53 +00002952 # compare payloads as though they're integers
2953 self_key = len(self._int), self._int
2954 other_key = len(other._int), other._int
2955 if self_key < other_key:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002956 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002957 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002958 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002959 return _NegativeOne
Mark Dickinsond314e1b2009-08-28 13:39:53 +00002960 if self_key > other_key:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002961 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002962 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002963 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002964 return _One
2965 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002966
2967 if sign:
2968 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002969 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002970 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002971 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002972 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002973 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002974 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002975 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002976 else:
2977 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002978 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002979 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002980 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002981 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002982 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002983 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002984 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002985
2986 if self < other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002987 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002988 if self > other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002989 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002990
2991 if self._exp < other._exp:
2992 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002993 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002994 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002995 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002996 if self._exp > other._exp:
2997 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002998 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002999 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003000 return _One
3001 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003002
3003
3004 def compare_total_mag(self, other):
3005 """Compares self to other using abstract repr., ignoring sign.
3006
3007 Like compare_total, but with operand's sign ignored and assumed to be 0.
3008 """
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003009 other = _convert_other(other, raiseit=True)
3010
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003011 s = self.copy_abs()
3012 o = other.copy_abs()
3013 return s.compare_total(o)
3014
3015 def copy_abs(self):
3016 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003017 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003018
3019 def copy_negate(self):
3020 """Returns a copy with the sign inverted."""
3021 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003022 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003023 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003024 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003025
3026 def copy_sign(self, other):
3027 """Returns self with the sign of other."""
Mark Dickinson84230a12010-02-18 14:49:50 +00003028 other = _convert_other(other, raiseit=True)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003029 return _dec_from_triple(other._sign, self._int,
3030 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003031
3032 def exp(self, context=None):
3033 """Returns e ** self."""
3034
3035 if context is None:
3036 context = getcontext()
3037
3038 # exp(NaN) = NaN
3039 ans = self._check_nans(context=context)
3040 if ans:
3041 return ans
3042
3043 # exp(-Infinity) = 0
3044 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003045 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003046
3047 # exp(0) = 1
3048 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003049 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003050
3051 # exp(Infinity) = Infinity
3052 if self._isinfinity() == 1:
3053 return Decimal(self)
3054
3055 # the result is now guaranteed to be inexact (the true
3056 # mathematical result is transcendental). There's no need to
3057 # raise Rounded and Inexact here---they'll always be raised as
3058 # a result of the call to _fix.
3059 p = context.prec
3060 adj = self.adjusted()
3061
3062 # we only need to do any computation for quite a small range
3063 # of adjusted exponents---for example, -29 <= adj <= 10 for
3064 # the default context. For smaller exponent the result is
3065 # indistinguishable from 1 at the given precision, while for
3066 # larger exponent the result either overflows or underflows.
3067 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
3068 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003069 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003070 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
3071 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003072 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003073 elif self._sign == 0 and adj < -p:
3074 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003075 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003076 elif self._sign == 1 and adj < -p-1:
3077 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003078 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003079 # general case
3080 else:
3081 op = _WorkRep(self)
3082 c, e = op.int, op.exp
3083 if op.sign == 1:
3084 c = -c
3085
3086 # compute correctly rounded result: increase precision by
3087 # 3 digits at a time until we get an unambiguously
3088 # roundable result
3089 extra = 3
3090 while True:
3091 coeff, exp = _dexp(c, e, p+extra)
3092 if coeff % (5*10**(len(str(coeff))-p-1)):
3093 break
3094 extra += 3
3095
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003096 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003097
3098 # at this stage, ans should round correctly with *any*
3099 # rounding mode, not just with ROUND_HALF_EVEN
3100 context = context._shallow_copy()
3101 rounding = context._set_rounding(ROUND_HALF_EVEN)
3102 ans = ans._fix(context)
3103 context.rounding = rounding
3104
3105 return ans
3106
3107 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003108 """Return True if self is canonical; otherwise return False.
3109
3110 Currently, the encoding of a Decimal instance is always
3111 canonical, so this method returns True for any Decimal.
3112 """
3113 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003114
3115 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003116 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003117
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003118 A Decimal instance is considered finite if it is neither
3119 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003120 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003121 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003122
3123 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003124 """Return True if self is infinite; otherwise return False."""
3125 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003126
3127 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003128 """Return True if self is a qNaN or sNaN; otherwise return False."""
3129 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003130
3131 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003132 """Return True if self is a normal number; otherwise return False."""
3133 if self._is_special or not self:
3134 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003135 if context is None:
3136 context = getcontext()
Mark Dickinson06bb6742009-10-20 13:38:04 +00003137 return context.Emin <= self.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003138
3139 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003140 """Return True if self is a quiet NaN; otherwise return False."""
3141 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003142
3143 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003144 """Return True if self is negative; otherwise return False."""
3145 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003146
3147 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003148 """Return True if self is a signaling NaN; otherwise return False."""
3149 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003150
3151 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003152 """Return True if self is subnormal; otherwise return False."""
3153 if self._is_special or not self:
3154 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003155 if context is None:
3156 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003157 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003158
3159 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003160 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003161 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003162
3163 def _ln_exp_bound(self):
3164 """Compute a lower bound for the adjusted exponent of self.ln().
3165 In other words, compute r such that self.ln() >= 10**r. Assumes
3166 that self is finite and positive and that self != 1.
3167 """
3168
3169 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
3170 adj = self._exp + len(self._int) - 1
3171 if adj >= 1:
3172 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
3173 return len(str(adj*23//10)) - 1
3174 if adj <= -2:
3175 # argument <= 0.1
3176 return len(str((-1-adj)*23//10)) - 1
3177 op = _WorkRep(self)
3178 c, e = op.int, op.exp
3179 if adj == 0:
3180 # 1 < self < 10
3181 num = str(c-10**-e)
3182 den = str(c)
3183 return len(num) - len(den) - (num < den)
3184 # adj == -1, 0.1 <= self < 1
3185 return e + len(str(10**-e - c)) - 1
3186
3187
3188 def ln(self, context=None):
3189 """Returns the natural (base e) logarithm of self."""
3190
3191 if context is None:
3192 context = getcontext()
3193
3194 # ln(NaN) = NaN
3195 ans = self._check_nans(context=context)
3196 if ans:
3197 return ans
3198
3199 # ln(0.0) == -Infinity
3200 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003201 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003202
3203 # ln(Infinity) = Infinity
3204 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003205 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003206
3207 # ln(1.0) == 0.0
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003208 if self == _One:
3209 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003210
3211 # ln(negative) raises InvalidOperation
3212 if self._sign == 1:
3213 return context._raise_error(InvalidOperation,
3214 'ln of a negative value')
3215
3216 # result is irrational, so necessarily inexact
3217 op = _WorkRep(self)
3218 c, e = op.int, op.exp
3219 p = context.prec
3220
3221 # correctly rounded result: repeatedly increase precision by 3
3222 # until we get an unambiguously roundable result
3223 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3224 while True:
3225 coeff = _dlog(c, e, places)
3226 # assert len(str(abs(coeff)))-p >= 1
3227 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3228 break
3229 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003230 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003231
3232 context = context._shallow_copy()
3233 rounding = context._set_rounding(ROUND_HALF_EVEN)
3234 ans = ans._fix(context)
3235 context.rounding = rounding
3236 return ans
3237
3238 def _log10_exp_bound(self):
3239 """Compute a lower bound for the adjusted exponent of self.log10().
3240 In other words, find r such that self.log10() >= 10**r.
3241 Assumes that self is finite and positive and that self != 1.
3242 """
3243
3244 # For x >= 10 or x < 0.1 we only need a bound on the integer
3245 # part of log10(self), and this comes directly from the
3246 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3247 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3248 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3249
3250 adj = self._exp + len(self._int) - 1
3251 if adj >= 1:
3252 # self >= 10
3253 return len(str(adj))-1
3254 if adj <= -2:
3255 # self < 0.1
3256 return len(str(-1-adj))-1
3257 op = _WorkRep(self)
3258 c, e = op.int, op.exp
3259 if adj == 0:
3260 # 1 < self < 10
3261 num = str(c-10**-e)
3262 den = str(231*c)
3263 return len(num) - len(den) - (num < den) + 2
3264 # adj == -1, 0.1 <= self < 1
3265 num = str(10**-e-c)
3266 return len(num) + e - (num < "231") - 1
3267
3268 def log10(self, context=None):
3269 """Returns the base 10 logarithm of self."""
3270
3271 if context is None:
3272 context = getcontext()
3273
3274 # log10(NaN) = NaN
3275 ans = self._check_nans(context=context)
3276 if ans:
3277 return ans
3278
3279 # log10(0.0) == -Infinity
3280 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003281 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003282
3283 # log10(Infinity) = Infinity
3284 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003285 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003286
3287 # log10(negative or -Infinity) raises InvalidOperation
3288 if self._sign == 1:
3289 return context._raise_error(InvalidOperation,
3290 'log10 of a negative value')
3291
3292 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003293 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003294 # answer may need rounding
3295 ans = Decimal(self._exp + len(self._int) - 1)
3296 else:
3297 # result is irrational, so necessarily inexact
3298 op = _WorkRep(self)
3299 c, e = op.int, op.exp
3300 p = context.prec
3301
3302 # correctly rounded result: repeatedly increase precision
3303 # until result is unambiguously roundable
3304 places = p-self._log10_exp_bound()+2
3305 while True:
3306 coeff = _dlog10(c, e, places)
3307 # assert len(str(abs(coeff)))-p >= 1
3308 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3309 break
3310 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003311 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003312
3313 context = context._shallow_copy()
3314 rounding = context._set_rounding(ROUND_HALF_EVEN)
3315 ans = ans._fix(context)
3316 context.rounding = rounding
3317 return ans
3318
3319 def logb(self, context=None):
3320 """ Returns the exponent of the magnitude of self's MSD.
3321
3322 The result is the integer which is the exponent of the magnitude
3323 of the most significant digit of self (as though it were truncated
3324 to a single digit while maintaining the value of that digit and
3325 without limiting the resulting exponent).
3326 """
3327 # logb(NaN) = NaN
3328 ans = self._check_nans(context=context)
3329 if ans:
3330 return ans
3331
3332 if context is None:
3333 context = getcontext()
3334
3335 # logb(+/-Inf) = +Inf
3336 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003337 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003338
3339 # logb(0) = -Inf, DivisionByZero
3340 if not self:
3341 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3342
3343 # otherwise, simply return the adjusted exponent of self, as a
3344 # Decimal. Note that no attempt is made to fit the result
3345 # into the current context.
Mark Dickinson56df8872009-10-07 19:23:50 +00003346 ans = Decimal(self.adjusted())
3347 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003348
3349 def _islogical(self):
3350 """Return True if self is a logical operand.
3351
Christian Heimes679db4a2008-01-18 09:56:22 +00003352 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003353 an exponent of 0, and a coefficient whose digits must all be
3354 either 0 or 1.
3355 """
3356 if self._sign != 0 or self._exp != 0:
3357 return False
3358 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003359 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003360 return False
3361 return True
3362
3363 def _fill_logical(self, context, opa, opb):
3364 dif = context.prec - len(opa)
3365 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003366 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003367 elif dif < 0:
3368 opa = opa[-context.prec:]
3369 dif = context.prec - len(opb)
3370 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003371 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003372 elif dif < 0:
3373 opb = opb[-context.prec:]
3374 return opa, opb
3375
3376 def logical_and(self, other, context=None):
3377 """Applies an 'and' operation between self and other's digits."""
3378 if context is None:
3379 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003380
3381 other = _convert_other(other, raiseit=True)
3382
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003383 if not self._islogical() or not other._islogical():
3384 return context._raise_error(InvalidOperation)
3385
3386 # fill to context.prec
3387 (opa, opb) = self._fill_logical(context, self._int, other._int)
3388
3389 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003390 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3391 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003392
3393 def logical_invert(self, context=None):
3394 """Invert all its digits."""
3395 if context is None:
3396 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003397 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3398 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003399
3400 def logical_or(self, other, context=None):
3401 """Applies an 'or' operation between self and other's digits."""
3402 if context is None:
3403 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003404
3405 other = _convert_other(other, raiseit=True)
3406
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003407 if not self._islogical() or not other._islogical():
3408 return context._raise_error(InvalidOperation)
3409
3410 # fill to context.prec
3411 (opa, opb) = self._fill_logical(context, self._int, other._int)
3412
3413 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003414 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003415 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003416
3417 def logical_xor(self, other, context=None):
3418 """Applies an 'xor' operation between self and other's digits."""
3419 if context is None:
3420 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003421
3422 other = _convert_other(other, raiseit=True)
3423
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003424 if not self._islogical() or not other._islogical():
3425 return context._raise_error(InvalidOperation)
3426
3427 # fill to context.prec
3428 (opa, opb) = self._fill_logical(context, self._int, other._int)
3429
3430 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003431 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003432 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003433
3434 def max_mag(self, other, context=None):
3435 """Compares the values numerically with their sign ignored."""
3436 other = _convert_other(other, raiseit=True)
3437
3438 if context is None:
3439 context = getcontext()
3440
3441 if self._is_special or other._is_special:
3442 # If one operand is a quiet NaN and the other is number, then the
3443 # number is always returned
3444 sn = self._isnan()
3445 on = other._isnan()
3446 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003447 if on == 1 and sn == 0:
3448 return self._fix(context)
3449 if sn == 1 and on == 0:
3450 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003451 return self._check_nans(other, context)
3452
Christian Heimes77c02eb2008-02-09 02:18:51 +00003453 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003454 if c == 0:
3455 c = self.compare_total(other)
3456
3457 if c == -1:
3458 ans = other
3459 else:
3460 ans = self
3461
Christian Heimes2c181612007-12-17 20:04:13 +00003462 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003463
3464 def min_mag(self, other, context=None):
3465 """Compares the values numerically with their sign ignored."""
3466 other = _convert_other(other, raiseit=True)
3467
3468 if context is None:
3469 context = getcontext()
3470
3471 if self._is_special or other._is_special:
3472 # If one operand is a quiet NaN and the other is number, then the
3473 # number is always returned
3474 sn = self._isnan()
3475 on = other._isnan()
3476 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003477 if on == 1 and sn == 0:
3478 return self._fix(context)
3479 if sn == 1 and on == 0:
3480 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003481 return self._check_nans(other, context)
3482
Christian Heimes77c02eb2008-02-09 02:18:51 +00003483 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003484 if c == 0:
3485 c = self.compare_total(other)
3486
3487 if c == -1:
3488 ans = self
3489 else:
3490 ans = other
3491
Christian Heimes2c181612007-12-17 20:04:13 +00003492 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003493
3494 def next_minus(self, context=None):
3495 """Returns the largest representable number smaller than itself."""
3496 if context is None:
3497 context = getcontext()
3498
3499 ans = self._check_nans(context=context)
3500 if ans:
3501 return ans
3502
3503 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003504 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003505 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003506 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003507
3508 context = context.copy()
3509 context._set_rounding(ROUND_FLOOR)
3510 context._ignore_all_flags()
3511 new_self = self._fix(context)
3512 if new_self != self:
3513 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003514 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3515 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003516
3517 def next_plus(self, context=None):
3518 """Returns the smallest representable number larger than itself."""
3519 if context is None:
3520 context = getcontext()
3521
3522 ans = self._check_nans(context=context)
3523 if ans:
3524 return ans
3525
3526 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003527 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003528 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003529 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003530
3531 context = context.copy()
3532 context._set_rounding(ROUND_CEILING)
3533 context._ignore_all_flags()
3534 new_self = self._fix(context)
3535 if new_self != self:
3536 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003537 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3538 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003539
3540 def next_toward(self, other, context=None):
3541 """Returns the number closest to self, in the direction towards other.
3542
3543 The result is the closest representable number to self
3544 (excluding self) that is in the direction towards other,
3545 unless both have the same value. If the two operands are
3546 numerically equal, then the result is a copy of self with the
3547 sign set to be the same as the sign of other.
3548 """
3549 other = _convert_other(other, raiseit=True)
3550
3551 if context is None:
3552 context = getcontext()
3553
3554 ans = self._check_nans(other, context)
3555 if ans:
3556 return ans
3557
Christian Heimes77c02eb2008-02-09 02:18:51 +00003558 comparison = self._cmp(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003559 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003560 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003561
3562 if comparison == -1:
3563 ans = self.next_plus(context)
3564 else: # comparison == 1
3565 ans = self.next_minus(context)
3566
3567 # decide which flags to raise using value of ans
3568 if ans._isinfinity():
3569 context._raise_error(Overflow,
3570 'Infinite result from next_toward',
3571 ans._sign)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003572 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00003573 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003574 elif ans.adjusted() < context.Emin:
3575 context._raise_error(Underflow)
3576 context._raise_error(Subnormal)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003577 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00003578 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003579 # if precision == 1 then we don't raise Clamped for a
3580 # result 0E-Etiny.
3581 if not ans:
3582 context._raise_error(Clamped)
3583
3584 return ans
3585
3586 def number_class(self, context=None):
3587 """Returns an indication of the class of self.
3588
3589 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003590 sNaN
3591 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003592 -Infinity
3593 -Normal
3594 -Subnormal
3595 -Zero
3596 +Zero
3597 +Subnormal
3598 +Normal
3599 +Infinity
3600 """
3601 if self.is_snan():
3602 return "sNaN"
3603 if self.is_qnan():
3604 return "NaN"
3605 inf = self._isinfinity()
3606 if inf == 1:
3607 return "+Infinity"
3608 if inf == -1:
3609 return "-Infinity"
3610 if self.is_zero():
3611 if self._sign:
3612 return "-Zero"
3613 else:
3614 return "+Zero"
3615 if context is None:
3616 context = getcontext()
3617 if self.is_subnormal(context=context):
3618 if self._sign:
3619 return "-Subnormal"
3620 else:
3621 return "+Subnormal"
3622 # just a normal, regular, boring number, :)
3623 if self._sign:
3624 return "-Normal"
3625 else:
3626 return "+Normal"
3627
3628 def radix(self):
3629 """Just returns 10, as this is Decimal, :)"""
3630 return Decimal(10)
3631
3632 def rotate(self, other, context=None):
3633 """Returns a rotated copy of self, value-of-other times."""
3634 if context is None:
3635 context = getcontext()
3636
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003637 other = _convert_other(other, raiseit=True)
3638
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003639 ans = self._check_nans(other, context)
3640 if ans:
3641 return ans
3642
3643 if other._exp != 0:
3644 return context._raise_error(InvalidOperation)
3645 if not (-context.prec <= int(other) <= context.prec):
3646 return context._raise_error(InvalidOperation)
3647
3648 if self._isinfinity():
3649 return Decimal(self)
3650
3651 # get values, pad if necessary
3652 torot = int(other)
3653 rotdig = self._int
3654 topad = context.prec - len(rotdig)
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003655 if topad > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003656 rotdig = '0'*topad + rotdig
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003657 elif topad < 0:
3658 rotdig = rotdig[-topad:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003659
3660 # let's rotate!
3661 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003662 return _dec_from_triple(self._sign,
3663 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003664
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003665 def scaleb(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003666 """Returns self operand after adding the second value to its exp."""
3667 if context is None:
3668 context = getcontext()
3669
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003670 other = _convert_other(other, raiseit=True)
3671
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003672 ans = self._check_nans(other, context)
3673 if ans:
3674 return ans
3675
3676 if other._exp != 0:
3677 return context._raise_error(InvalidOperation)
3678 liminf = -2 * (context.Emax + context.prec)
3679 limsup = 2 * (context.Emax + context.prec)
3680 if not (liminf <= int(other) <= limsup):
3681 return context._raise_error(InvalidOperation)
3682
3683 if self._isinfinity():
3684 return Decimal(self)
3685
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003686 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003687 d = d._fix(context)
3688 return d
3689
3690 def shift(self, other, context=None):
3691 """Returns a shifted copy of self, value-of-other times."""
3692 if context is None:
3693 context = getcontext()
3694
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003695 other = _convert_other(other, raiseit=True)
3696
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003697 ans = self._check_nans(other, context)
3698 if ans:
3699 return ans
3700
3701 if other._exp != 0:
3702 return context._raise_error(InvalidOperation)
3703 if not (-context.prec <= int(other) <= context.prec):
3704 return context._raise_error(InvalidOperation)
3705
3706 if self._isinfinity():
3707 return Decimal(self)
3708
3709 # get values, pad if necessary
3710 torot = int(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003711 rotdig = self._int
3712 topad = context.prec - len(rotdig)
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003713 if topad > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003714 rotdig = '0'*topad + rotdig
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003715 elif topad < 0:
3716 rotdig = rotdig[-topad:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003717
3718 # let's shift!
3719 if torot < 0:
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003720 shifted = rotdig[:torot]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003721 else:
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003722 shifted = rotdig + '0'*torot
3723 shifted = shifted[-context.prec:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003724
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003725 return _dec_from_triple(self._sign,
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003726 shifted.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003727
Guido van Rossumd8faa362007-04-27 19:54:29 +00003728 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003729 def __reduce__(self):
3730 return (self.__class__, (str(self),))
3731
3732 def __copy__(self):
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00003733 if type(self) is Decimal:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003734 return self # I'm immutable; therefore I am my own clone
3735 return self.__class__(str(self))
3736
3737 def __deepcopy__(self, memo):
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00003738 if type(self) is Decimal:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003739 return self # My components are also immutable
3740 return self.__class__(str(self))
3741
Mark Dickinson79f52032009-03-17 23:12:51 +00003742 # PEP 3101 support. the _localeconv keyword argument should be
3743 # considered private: it's provided for ease of testing only.
3744 def __format__(self, specifier, context=None, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00003745 """Format a Decimal instance according to the given specifier.
3746
3747 The specifier should be a standard format specifier, with the
3748 form described in PEP 3101. Formatting types 'e', 'E', 'f',
Mark Dickinson79f52032009-03-17 23:12:51 +00003749 'F', 'g', 'G', 'n' and '%' are supported. If the formatting
3750 type is omitted it defaults to 'g' or 'G', depending on the
3751 value of context.capitals.
Christian Heimesf16baeb2008-02-29 14:57:44 +00003752 """
3753
3754 # Note: PEP 3101 says that if the type is not present then
3755 # there should be at least one digit after the decimal point.
3756 # We take the liberty of ignoring this requirement for
3757 # Decimal---it's presumably there to make sure that
3758 # format(float, '') behaves similarly to str(float).
3759 if context is None:
3760 context = getcontext()
3761
Mark Dickinson79f52032009-03-17 23:12:51 +00003762 spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003763
Mark Dickinson79f52032009-03-17 23:12:51 +00003764 # special values don't care about the type or precision
Christian Heimesf16baeb2008-02-29 14:57:44 +00003765 if self._is_special:
Mark Dickinson79f52032009-03-17 23:12:51 +00003766 sign = _format_sign(self._sign, spec)
3767 body = str(self.copy_abs())
3768 return _format_align(sign, body, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003769
3770 # a type of None defaults to 'g' or 'G', depending on context
Christian Heimesf16baeb2008-02-29 14:57:44 +00003771 if spec['type'] is None:
3772 spec['type'] = ['g', 'G'][context.capitals]
Mark Dickinson79f52032009-03-17 23:12:51 +00003773
3774 # if type is '%', adjust exponent of self accordingly
3775 if spec['type'] == '%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003776 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3777
3778 # round if necessary, taking rounding mode from the context
3779 rounding = context.rounding
3780 precision = spec['precision']
3781 if precision is not None:
3782 if spec['type'] in 'eE':
3783 self = self._round(precision+1, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003784 elif spec['type'] in 'fF%':
3785 self = self._rescale(-precision, rounding)
Mark Dickinson79f52032009-03-17 23:12:51 +00003786 elif spec['type'] in 'gG' and len(self._int) > precision:
3787 self = self._round(precision, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003788 # special case: zeros with a positive exponent can't be
3789 # represented in fixed point; rescale them to 0e0.
Mark Dickinson79f52032009-03-17 23:12:51 +00003790 if not self and self._exp > 0 and spec['type'] in 'fF%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003791 self = self._rescale(0, rounding)
3792
3793 # figure out placement of the decimal point
3794 leftdigits = self._exp + len(self._int)
Mark Dickinson79f52032009-03-17 23:12:51 +00003795 if spec['type'] in 'eE':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003796 if not self and precision is not None:
3797 dotplace = 1 - precision
3798 else:
3799 dotplace = 1
Mark Dickinson79f52032009-03-17 23:12:51 +00003800 elif spec['type'] in 'fF%':
3801 dotplace = leftdigits
Christian Heimesf16baeb2008-02-29 14:57:44 +00003802 elif spec['type'] in 'gG':
3803 if self._exp <= 0 and leftdigits > -6:
3804 dotplace = leftdigits
3805 else:
3806 dotplace = 1
3807
Mark Dickinson79f52032009-03-17 23:12:51 +00003808 # find digits before and after decimal point, and get exponent
3809 if dotplace < 0:
3810 intpart = '0'
3811 fracpart = '0'*(-dotplace) + self._int
3812 elif dotplace > len(self._int):
3813 intpart = self._int + '0'*(dotplace-len(self._int))
3814 fracpart = ''
Christian Heimesf16baeb2008-02-29 14:57:44 +00003815 else:
Mark Dickinson79f52032009-03-17 23:12:51 +00003816 intpart = self._int[:dotplace] or '0'
3817 fracpart = self._int[dotplace:]
3818 exp = leftdigits-dotplace
Christian Heimesf16baeb2008-02-29 14:57:44 +00003819
Mark Dickinson79f52032009-03-17 23:12:51 +00003820 # done with the decimal-specific stuff; hand over the rest
3821 # of the formatting to the _format_number function
3822 return _format_number(self._sign, intpart, fracpart, exp, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003823
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003824def _dec_from_triple(sign, coefficient, exponent, special=False):
3825 """Create a decimal instance directly, without any validation,
3826 normalization (e.g. removal of leading zeros) or argument
3827 conversion.
3828
3829 This function is for *internal use only*.
3830 """
3831
3832 self = object.__new__(Decimal)
3833 self._sign = sign
3834 self._int = coefficient
3835 self._exp = exponent
3836 self._is_special = special
3837
3838 return self
3839
Raymond Hettinger82417ca2009-02-03 03:54:28 +00003840# Register Decimal as a kind of Number (an abstract base class).
3841# However, do not register it as Real (because Decimals are not
3842# interoperable with floats).
3843_numbers.Number.register(Decimal)
3844
3845
Guido van Rossumd8faa362007-04-27 19:54:29 +00003846##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003847
Thomas Wouters89f507f2006-12-13 04:49:30 +00003848class _ContextManager(object):
3849 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003850
Thomas Wouters89f507f2006-12-13 04:49:30 +00003851 Sets a copy of the supplied context in __enter__() and restores
3852 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003853 """
3854 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003855 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003856 def __enter__(self):
3857 self.saved_context = getcontext()
3858 setcontext(self.new_context)
3859 return self.new_context
3860 def __exit__(self, t, v, tb):
3861 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003862
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003863class Context(object):
3864 """Contains the context for a Decimal instance.
3865
3866 Contains:
3867 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003868 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003869 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003870 raised when it is caused. Otherwise, a value is
3871 substituted in.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003872 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003873 (Whether or not the trap_enabler is set)
3874 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003875 Emin - Minimum exponent
3876 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003877 capitals - If 1, 1*10^1 is printed as 1E+1.
3878 If 0, printed as 1e1
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00003879 clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003880 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003881
Stefan Krah1919b7e2012-03-21 18:25:23 +01003882 def __init__(self, prec=None, rounding=None, Emin=None, Emax=None,
3883 capitals=None, clamp=None, flags=None, traps=None,
3884 _ignored_flags=None):
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003885 # Set defaults; for everything except flags and _ignored_flags,
3886 # inherit from DefaultContext.
3887 try:
3888 dc = DefaultContext
3889 except NameError:
3890 pass
3891
3892 self.prec = prec if prec is not None else dc.prec
3893 self.rounding = rounding if rounding is not None else dc.rounding
3894 self.Emin = Emin if Emin is not None else dc.Emin
3895 self.Emax = Emax if Emax is not None else dc.Emax
3896 self.capitals = capitals if capitals is not None else dc.capitals
3897 self.clamp = clamp if clamp is not None else dc.clamp
3898
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003899 if _ignored_flags is None:
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003900 self._ignored_flags = []
3901 else:
3902 self._ignored_flags = _ignored_flags
3903
3904 if traps is None:
3905 self.traps = dc.traps.copy()
3906 elif not isinstance(traps, dict):
Stefan Krah1919b7e2012-03-21 18:25:23 +01003907 self.traps = dict((s, int(s in traps)) for s in _signals + traps)
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003908 else:
3909 self.traps = traps
3910
3911 if flags is None:
3912 self.flags = dict.fromkeys(_signals, 0)
3913 elif not isinstance(flags, dict):
Stefan Krah1919b7e2012-03-21 18:25:23 +01003914 self.flags = dict((s, int(s in flags)) for s in _signals + flags)
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003915 else:
3916 self.flags = flags
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003917
Stefan Krah1919b7e2012-03-21 18:25:23 +01003918 def _set_integer_check(self, name, value, vmin, vmax):
3919 if not isinstance(value, int):
3920 raise TypeError("%s must be an integer" % name)
3921 if vmin == '-inf':
3922 if value > vmax:
3923 raise ValueError("%s must be in [%s, %d]. got: %s" % (name, vmin, vmax, value))
3924 elif vmax == 'inf':
3925 if value < vmin:
3926 raise ValueError("%s must be in [%d, %s]. got: %s" % (name, vmin, vmax, value))
3927 else:
3928 if value < vmin or value > vmax:
3929 raise ValueError("%s must be in [%d, %d]. got %s" % (name, vmin, vmax, value))
3930 return object.__setattr__(self, name, value)
3931
3932 def _set_signal_dict(self, name, d):
3933 if not isinstance(d, dict):
3934 raise TypeError("%s must be a signal dict" % d)
3935 for key in d:
3936 if not key in _signals:
3937 raise KeyError("%s is not a valid signal dict" % d)
3938 for key in _signals:
3939 if not key in d:
3940 raise KeyError("%s is not a valid signal dict" % d)
3941 return object.__setattr__(self, name, d)
3942
3943 def __setattr__(self, name, value):
3944 if name == 'prec':
3945 return self._set_integer_check(name, value, 1, 'inf')
3946 elif name == 'Emin':
3947 return self._set_integer_check(name, value, '-inf', 0)
3948 elif name == 'Emax':
3949 return self._set_integer_check(name, value, 0, 'inf')
3950 elif name == 'capitals':
3951 return self._set_integer_check(name, value, 0, 1)
3952 elif name == 'clamp':
3953 return self._set_integer_check(name, value, 0, 1)
3954 elif name == 'rounding':
3955 if not value in _rounding_modes:
3956 # raise TypeError even for strings to have consistency
3957 # among various implementations.
3958 raise TypeError("%s: invalid rounding mode" % value)
3959 return object.__setattr__(self, name, value)
3960 elif name == 'flags' or name == 'traps':
3961 return self._set_signal_dict(name, value)
3962 elif name == '_ignored_flags':
3963 return object.__setattr__(self, name, value)
3964 else:
3965 raise AttributeError(
3966 "'decimal.Context' object has no attribute '%s'" % name)
3967
3968 def __delattr__(self, name):
3969 raise AttributeError("%s cannot be deleted" % name)
3970
3971 # Support for pickling, copy, and deepcopy
3972 def __reduce__(self):
3973 flags = [sig for sig, v in self.flags.items() if v]
3974 traps = [sig for sig, v in self.traps.items() if v]
3975 return (self.__class__,
3976 (self.prec, self.rounding, self.Emin, self.Emax,
3977 self.capitals, self.clamp, flags, traps))
3978
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003979 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003980 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003981 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003982 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00003983 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d, '
3984 'clamp=%(clamp)d'
Guido van Rossumd8faa362007-04-27 19:54:29 +00003985 % vars(self))
3986 names = [f.__name__ for f, v in self.flags.items() if v]
3987 s.append('flags=[' + ', '.join(names) + ']')
3988 names = [t.__name__ for t, v in self.traps.items() if v]
3989 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003990 return ', '.join(s) + ')'
3991
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003992 def clear_flags(self):
3993 """Reset all flags to zero"""
3994 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003995 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003996
Stefan Krah1919b7e2012-03-21 18:25:23 +01003997 def clear_traps(self):
3998 """Reset all traps to zero"""
3999 for flag in self.traps:
4000 self.traps[flag] = 0
4001
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004002 def _shallow_copy(self):
4003 """Returns a shallow copy from self."""
Stefan Krah1919b7e2012-03-21 18:25:23 +01004004 nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
4005 self.capitals, self.clamp, self.flags, self.traps,
4006 self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004007 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004008
4009 def copy(self):
4010 """Returns a deep copy from self."""
Stefan Krah1919b7e2012-03-21 18:25:23 +01004011 nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
4012 self.capitals, self.clamp,
4013 self.flags.copy(), self.traps.copy(),
4014 self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004015 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004016 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004017
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004018 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004019 """Handles an error
4020
4021 If the flag is in _ignored_flags, returns the default response.
Raymond Hettinger86173da2008-02-01 20:38:12 +00004022 Otherwise, it sets the flag, then, if the corresponding
Stefan Krah2eb4a072010-05-19 15:52:31 +00004023 trap_enabler is set, it reraises the exception. Otherwise, it returns
Raymond Hettinger86173da2008-02-01 20:38:12 +00004024 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004025 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004026 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004027 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00004028 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004029 return error().handle(self, *args)
4030
Raymond Hettinger86173da2008-02-01 20:38:12 +00004031 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00004032 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00004033 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004034 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004035
4036 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00004037 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00004038 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004039
4040 def _ignore_all_flags(self):
4041 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00004042 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004043
4044 def _ignore_flags(self, *flags):
4045 """Ignore the flags, if they are raised"""
4046 # Do not mutate-- This way, copies of a context leave the original
4047 # alone.
4048 self._ignored_flags = (self._ignored_flags + list(flags))
4049 return list(flags)
4050
4051 def _regard_flags(self, *flags):
4052 """Stop ignoring the flags, if they are raised"""
4053 if flags and isinstance(flags[0], (tuple,list)):
4054 flags = flags[0]
4055 for flag in flags:
4056 self._ignored_flags.remove(flag)
4057
Nick Coghland1abd252008-07-15 15:46:38 +00004058 # We inherit object.__hash__, so we must deny this explicitly
4059 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004060
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004061 def Etiny(self):
4062 """Returns Etiny (= Emin - prec + 1)"""
4063 return int(self.Emin - self.prec + 1)
4064
4065 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004066 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004067 return int(self.Emax - self.prec + 1)
4068
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004069 def _set_rounding(self, type):
4070 """Sets the rounding type.
4071
4072 Sets the rounding type, and returns the current (previous)
4073 rounding type. Often used like:
4074
4075 context = context.copy()
4076 # so you don't change the calling context
4077 # if an error occurs in the middle.
4078 rounding = context._set_rounding(ROUND_UP)
4079 val = self.__sub__(other, context=context)
4080 context._set_rounding(rounding)
4081
4082 This will make it round up for that operation.
4083 """
4084 rounding = self.rounding
4085 self.rounding= type
4086 return rounding
4087
Raymond Hettingerfed52962004-07-14 15:41:57 +00004088 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00004089 """Creates a new Decimal instance but using self as context.
4090
4091 This method implements the to-number operation of the
4092 IBM Decimal specification."""
4093
4094 if isinstance(num, str) and num != num.strip():
4095 return self._raise_error(ConversionSyntax,
4096 "no trailing or leading whitespace is "
4097 "permitted.")
4098
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004099 d = Decimal(num, context=self)
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00004100 if d._isnan() and len(d._int) > self.prec - self.clamp:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004101 return self._raise_error(ConversionSyntax,
4102 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00004103 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004104
Raymond Hettinger771ed762009-01-03 19:20:32 +00004105 def create_decimal_from_float(self, f):
4106 """Creates a new Decimal instance from a float but rounding using self
4107 as the context.
4108
4109 >>> context = Context(prec=5, rounding=ROUND_DOWN)
4110 >>> context.create_decimal_from_float(3.1415926535897932)
4111 Decimal('3.1415')
4112 >>> context = Context(prec=5, traps=[Inexact])
4113 >>> context.create_decimal_from_float(3.1415926535897932)
4114 Traceback (most recent call last):
4115 ...
4116 decimal.Inexact: None
4117
4118 """
4119 d = Decimal.from_float(f) # An exact conversion
4120 return d._fix(self) # Apply the context rounding
4121
Guido van Rossumd8faa362007-04-27 19:54:29 +00004122 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004123 def abs(self, a):
4124 """Returns the absolute value of the operand.
4125
4126 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00004127 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004128 the plus operation on the operand.
4129
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004130 >>> ExtendedContext.abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004131 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004132 >>> ExtendedContext.abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004133 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004134 >>> ExtendedContext.abs(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004135 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004136 >>> ExtendedContext.abs(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004137 Decimal('101.5')
Mark Dickinson84230a12010-02-18 14:49:50 +00004138 >>> ExtendedContext.abs(-1)
4139 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004140 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004141 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004142 return a.__abs__(context=self)
4143
4144 def add(self, a, b):
4145 """Return the sum of the two operands.
4146
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004147 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004148 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004149 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004150 Decimal('1.02E+4')
Mark Dickinson84230a12010-02-18 14:49:50 +00004151 >>> ExtendedContext.add(1, Decimal(2))
4152 Decimal('3')
4153 >>> ExtendedContext.add(Decimal(8), 5)
4154 Decimal('13')
4155 >>> ExtendedContext.add(5, 5)
4156 Decimal('10')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004157 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004158 a = _convert_other(a, raiseit=True)
4159 r = a.__add__(b, context=self)
4160 if r is NotImplemented:
4161 raise TypeError("Unable to convert %s to Decimal" % b)
4162 else:
4163 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004164
4165 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00004166 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004167
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004168 def canonical(self, a):
4169 """Returns the same Decimal object.
4170
4171 As we do not have different encodings for the same number, the
4172 received object already is in its canonical form.
4173
4174 >>> ExtendedContext.canonical(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004175 Decimal('2.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004176 """
Stefan Krah1919b7e2012-03-21 18:25:23 +01004177 if not isinstance(a, Decimal):
4178 raise TypeError("canonical requires a Decimal as an argument.")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004179 return a.canonical(context=self)
4180
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004181 def compare(self, a, b):
4182 """Compares values numerically.
4183
4184 If the signs of the operands differ, a value representing each operand
4185 ('-1' if the operand is less than zero, '0' if the operand is zero or
4186 negative zero, or '1' if the operand is greater than zero) is used in
4187 place of that operand for the comparison instead of the actual
4188 operand.
4189
4190 The comparison is then effected by subtracting the second operand from
4191 the first and then returning a value according to the result of the
4192 subtraction: '-1' if the result is less than zero, '0' if the result is
4193 zero or negative zero, or '1' if the result is greater than zero.
4194
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004195 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004196 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004197 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004198 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004199 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004200 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004201 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004202 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004203 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004204 Decimal('1')
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')
Mark Dickinson84230a12010-02-18 14:49:50 +00004207 >>> ExtendedContext.compare(1, 2)
4208 Decimal('-1')
4209 >>> ExtendedContext.compare(Decimal(1), 2)
4210 Decimal('-1')
4211 >>> ExtendedContext.compare(1, Decimal(2))
4212 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004213 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004214 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004215 return a.compare(b, context=self)
4216
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004217 def compare_signal(self, a, b):
4218 """Compares the values of the two operands numerically.
4219
4220 It's pretty much like compare(), but all NaNs signal, with signaling
4221 NaNs taking precedence over quiet NaNs.
4222
4223 >>> c = ExtendedContext
4224 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004225 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004226 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004227 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004228 >>> c.flags[InvalidOperation] = 0
4229 >>> print(c.flags[InvalidOperation])
4230 0
4231 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004232 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004233 >>> print(c.flags[InvalidOperation])
4234 1
4235 >>> c.flags[InvalidOperation] = 0
4236 >>> print(c.flags[InvalidOperation])
4237 0
4238 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004239 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004240 >>> print(c.flags[InvalidOperation])
4241 1
Mark Dickinson84230a12010-02-18 14:49:50 +00004242 >>> c.compare_signal(-1, 2)
4243 Decimal('-1')
4244 >>> c.compare_signal(Decimal(-1), 2)
4245 Decimal('-1')
4246 >>> c.compare_signal(-1, Decimal(2))
4247 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004248 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004249 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004250 return a.compare_signal(b, context=self)
4251
4252 def compare_total(self, a, b):
4253 """Compares two operands using their abstract representation.
4254
4255 This is not like the standard compare, which use their numerical
4256 value. Note that a total ordering is defined for all possible abstract
4257 representations.
4258
4259 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004260 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004261 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004262 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004263 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004264 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004265 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004266 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004267 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004268 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004269 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004270 Decimal('-1')
Mark Dickinson84230a12010-02-18 14:49:50 +00004271 >>> ExtendedContext.compare_total(1, 2)
4272 Decimal('-1')
4273 >>> ExtendedContext.compare_total(Decimal(1), 2)
4274 Decimal('-1')
4275 >>> ExtendedContext.compare_total(1, Decimal(2))
4276 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004277 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004278 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004279 return a.compare_total(b)
4280
4281 def compare_total_mag(self, a, b):
4282 """Compares two operands using their abstract representation ignoring sign.
4283
4284 Like compare_total, but with operand's sign ignored and assumed to be 0.
4285 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004286 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004287 return a.compare_total_mag(b)
4288
4289 def copy_abs(self, a):
4290 """Returns a copy of the operand with the sign set to 0.
4291
4292 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004293 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004294 >>> ExtendedContext.copy_abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004295 Decimal('100')
Mark Dickinson84230a12010-02-18 14:49:50 +00004296 >>> ExtendedContext.copy_abs(-1)
4297 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004298 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004299 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004300 return a.copy_abs()
4301
4302 def copy_decimal(self, a):
Mark Dickinson84230a12010-02-18 14:49:50 +00004303 """Returns a copy of the decimal object.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004304
4305 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004306 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004307 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004308 Decimal('-1.00')
Mark Dickinson84230a12010-02-18 14:49:50 +00004309 >>> ExtendedContext.copy_decimal(1)
4310 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004311 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004312 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004313 return Decimal(a)
4314
4315 def copy_negate(self, a):
4316 """Returns a copy of the operand with the sign inverted.
4317
4318 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004319 Decimal('-101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004320 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004321 Decimal('101.5')
Mark Dickinson84230a12010-02-18 14:49:50 +00004322 >>> ExtendedContext.copy_negate(1)
4323 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004324 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004325 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004326 return a.copy_negate()
4327
4328 def copy_sign(self, a, b):
4329 """Copies the second operand's sign to the first one.
4330
4331 In detail, it returns a copy of the first operand with the sign
4332 equal to the sign of the second operand.
4333
4334 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004335 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004336 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004337 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004338 >>> 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')
Mark Dickinson84230a12010-02-18 14:49:50 +00004342 >>> ExtendedContext.copy_sign(1, -2)
4343 Decimal('-1')
4344 >>> ExtendedContext.copy_sign(Decimal(1), -2)
4345 Decimal('-1')
4346 >>> ExtendedContext.copy_sign(1, Decimal(-2))
4347 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004348 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004349 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004350 return a.copy_sign(b)
4351
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004352 def divide(self, a, b):
4353 """Decimal division in a specified context.
4354
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004355 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004356 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004357 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004358 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004359 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004360 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004361 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004362 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004363 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004364 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004365 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004366 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004367 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004368 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004369 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004370 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004371 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004372 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004373 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004374 Decimal('1.20E+6')
Mark Dickinson84230a12010-02-18 14:49:50 +00004375 >>> ExtendedContext.divide(5, 5)
4376 Decimal('1')
4377 >>> ExtendedContext.divide(Decimal(5), 5)
4378 Decimal('1')
4379 >>> ExtendedContext.divide(5, Decimal(5))
4380 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004381 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004382 a = _convert_other(a, raiseit=True)
4383 r = a.__truediv__(b, context=self)
4384 if r is NotImplemented:
4385 raise TypeError("Unable to convert %s to Decimal" % b)
4386 else:
4387 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004388
4389 def divide_int(self, a, b):
4390 """Divides two numbers and returns the integer part of the result.
4391
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004392 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004393 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004394 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004395 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004396 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004397 Decimal('3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004398 >>> ExtendedContext.divide_int(10, 3)
4399 Decimal('3')
4400 >>> ExtendedContext.divide_int(Decimal(10), 3)
4401 Decimal('3')
4402 >>> ExtendedContext.divide_int(10, Decimal(3))
4403 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004404 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004405 a = _convert_other(a, raiseit=True)
4406 r = a.__floordiv__(b, context=self)
4407 if r is NotImplemented:
4408 raise TypeError("Unable to convert %s to Decimal" % b)
4409 else:
4410 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004411
4412 def divmod(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004413 """Return (a // b, a % b).
Mark Dickinsonc53796e2010-01-06 16:22:15 +00004414
4415 >>> ExtendedContext.divmod(Decimal(8), Decimal(3))
4416 (Decimal('2'), Decimal('2'))
4417 >>> ExtendedContext.divmod(Decimal(8), Decimal(4))
4418 (Decimal('2'), Decimal('0'))
Mark Dickinson84230a12010-02-18 14:49:50 +00004419 >>> ExtendedContext.divmod(8, 4)
4420 (Decimal('2'), Decimal('0'))
4421 >>> ExtendedContext.divmod(Decimal(8), 4)
4422 (Decimal('2'), Decimal('0'))
4423 >>> ExtendedContext.divmod(8, Decimal(4))
4424 (Decimal('2'), Decimal('0'))
Mark Dickinsonc53796e2010-01-06 16:22:15 +00004425 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004426 a = _convert_other(a, raiseit=True)
4427 r = a.__divmod__(b, context=self)
4428 if r is NotImplemented:
4429 raise TypeError("Unable to convert %s to Decimal" % b)
4430 else:
4431 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004432
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004433 def exp(self, a):
4434 """Returns e ** a.
4435
4436 >>> c = ExtendedContext.copy()
4437 >>> c.Emin = -999
4438 >>> c.Emax = 999
4439 >>> c.exp(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004440 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004441 >>> c.exp(Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004442 Decimal('0.367879441')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004443 >>> c.exp(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004444 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004445 >>> c.exp(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004446 Decimal('2.71828183')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004447 >>> c.exp(Decimal('0.693147181'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004448 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004449 >>> c.exp(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004450 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004451 >>> c.exp(10)
4452 Decimal('22026.4658')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004453 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004454 a =_convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004455 return a.exp(context=self)
4456
4457 def fma(self, a, b, c):
4458 """Returns a multiplied by b, plus c.
4459
4460 The first two operands are multiplied together, using multiply,
4461 the third operand is then added to the result of that
4462 multiplication, using add, all with only one final rounding.
4463
4464 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004465 Decimal('22')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004466 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004467 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004468 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004469 Decimal('1.38435736E+12')
Mark Dickinson84230a12010-02-18 14:49:50 +00004470 >>> ExtendedContext.fma(1, 3, 4)
4471 Decimal('7')
4472 >>> ExtendedContext.fma(1, Decimal(3), 4)
4473 Decimal('7')
4474 >>> ExtendedContext.fma(1, 3, Decimal(4))
4475 Decimal('7')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004476 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004477 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004478 return a.fma(b, c, context=self)
4479
4480 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004481 """Return True if the operand is canonical; otherwise return False.
4482
4483 Currently, the encoding of a Decimal instance is always
4484 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004485
4486 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004487 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004488 """
Stefan Krah1919b7e2012-03-21 18:25:23 +01004489 if not isinstance(a, Decimal):
4490 raise TypeError("is_canonical requires a Decimal as an argument.")
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004491 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004492
4493 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004494 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004495
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004496 A Decimal instance is considered finite if it is neither
4497 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004498
4499 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004500 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004501 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004502 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004503 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004504 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004505 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004506 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004507 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004508 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004509 >>> ExtendedContext.is_finite(1)
4510 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004511 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004512 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004513 return a.is_finite()
4514
4515 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004516 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004517
4518 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004519 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004520 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004521 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004522 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004523 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004524 >>> ExtendedContext.is_infinite(1)
4525 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004526 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004527 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004528 return a.is_infinite()
4529
4530 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004531 """Return True if the operand is a qNaN or sNaN;
4532 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004533
4534 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004535 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004536 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004537 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004538 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004539 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004540 >>> ExtendedContext.is_nan(1)
4541 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004542 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004543 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004544 return a.is_nan()
4545
4546 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004547 """Return True if the operand is a normal number;
4548 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004549
4550 >>> c = ExtendedContext.copy()
4551 >>> c.Emin = -999
4552 >>> c.Emax = 999
4553 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004554 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004555 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004556 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004557 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004558 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004559 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004560 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004561 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004562 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004563 >>> c.is_normal(1)
4564 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004565 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004566 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004567 return a.is_normal(context=self)
4568
4569 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004570 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004571
4572 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004573 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004574 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004575 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004576 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004577 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004578 >>> ExtendedContext.is_qnan(1)
4579 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004580 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004581 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004582 return a.is_qnan()
4583
4584 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004585 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004586
4587 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004588 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004589 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004590 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004591 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004592 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004593 >>> ExtendedContext.is_signed(8)
4594 False
4595 >>> ExtendedContext.is_signed(-8)
4596 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004597 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004598 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004599 return a.is_signed()
4600
4601 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004602 """Return True if the operand is a signaling NaN;
4603 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004604
4605 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004606 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004607 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004608 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004609 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004610 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004611 >>> ExtendedContext.is_snan(1)
4612 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004613 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004614 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004615 return a.is_snan()
4616
4617 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004618 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004619
4620 >>> c = ExtendedContext.copy()
4621 >>> c.Emin = -999
4622 >>> c.Emax = 999
4623 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004624 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004625 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004626 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004627 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004628 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004629 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004630 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004631 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004632 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004633 >>> c.is_subnormal(1)
4634 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004635 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004636 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004637 return a.is_subnormal(context=self)
4638
4639 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004640 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004641
4642 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004643 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004644 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004645 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004646 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004647 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004648 >>> ExtendedContext.is_zero(1)
4649 False
4650 >>> ExtendedContext.is_zero(0)
4651 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004652 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004653 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004654 return a.is_zero()
4655
4656 def ln(self, a):
4657 """Returns the natural (base e) logarithm of the operand.
4658
4659 >>> c = ExtendedContext.copy()
4660 >>> c.Emin = -999
4661 >>> c.Emax = 999
4662 >>> c.ln(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004663 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004664 >>> c.ln(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004665 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004666 >>> c.ln(Decimal('2.71828183'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004667 Decimal('1.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004668 >>> c.ln(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004669 Decimal('2.30258509')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004670 >>> c.ln(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004671 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004672 >>> c.ln(1)
4673 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004674 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004675 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004676 return a.ln(context=self)
4677
4678 def log10(self, a):
4679 """Returns the base 10 logarithm of the operand.
4680
4681 >>> c = ExtendedContext.copy()
4682 >>> c.Emin = -999
4683 >>> c.Emax = 999
4684 >>> c.log10(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004685 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004686 >>> c.log10(Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004687 Decimal('-3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004688 >>> c.log10(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004689 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004690 >>> c.log10(Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004691 Decimal('0.301029996')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004692 >>> c.log10(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004693 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004694 >>> c.log10(Decimal('70'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004695 Decimal('1.84509804')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004696 >>> c.log10(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004697 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004698 >>> c.log10(0)
4699 Decimal('-Infinity')
4700 >>> c.log10(1)
4701 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004702 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004703 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004704 return a.log10(context=self)
4705
4706 def logb(self, a):
4707 """ Returns the exponent of the magnitude of the operand's MSD.
4708
4709 The result is the integer which is the exponent of the magnitude
4710 of the most significant digit of the operand (as though the
4711 operand were truncated to a single digit while maintaining the
4712 value of that digit and without limiting the resulting exponent).
4713
4714 >>> ExtendedContext.logb(Decimal('250'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004715 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004716 >>> ExtendedContext.logb(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004717 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004718 >>> ExtendedContext.logb(Decimal('0.03'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004719 Decimal('-2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004720 >>> ExtendedContext.logb(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004721 Decimal('-Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004722 >>> ExtendedContext.logb(1)
4723 Decimal('0')
4724 >>> ExtendedContext.logb(10)
4725 Decimal('1')
4726 >>> ExtendedContext.logb(100)
4727 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004728 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004729 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004730 return a.logb(context=self)
4731
4732 def logical_and(self, a, b):
4733 """Applies the logical operation 'and' between each operand's digits.
4734
4735 The operands must be both logical numbers.
4736
4737 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004738 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004739 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004740 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004741 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004742 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004743 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004744 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004745 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004746 Decimal('1000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004747 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004748 Decimal('10')
Mark Dickinson84230a12010-02-18 14:49:50 +00004749 >>> ExtendedContext.logical_and(110, 1101)
4750 Decimal('100')
4751 >>> ExtendedContext.logical_and(Decimal(110), 1101)
4752 Decimal('100')
4753 >>> ExtendedContext.logical_and(110, Decimal(1101))
4754 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004755 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004756 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004757 return a.logical_and(b, context=self)
4758
4759 def logical_invert(self, a):
4760 """Invert all the digits in the operand.
4761
4762 The operand must be a logical number.
4763
4764 >>> ExtendedContext.logical_invert(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004765 Decimal('111111111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004766 >>> ExtendedContext.logical_invert(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004767 Decimal('111111110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004768 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004769 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004770 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004771 Decimal('10101010')
Mark Dickinson84230a12010-02-18 14:49:50 +00004772 >>> ExtendedContext.logical_invert(1101)
4773 Decimal('111110010')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004774 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004775 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004776 return a.logical_invert(context=self)
4777
4778 def logical_or(self, a, b):
4779 """Applies the logical operation 'or' between each operand's digits.
4780
4781 The operands must be both logical numbers.
4782
4783 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004784 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004785 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004786 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004787 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004788 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004789 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004790 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004791 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004792 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004793 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004794 Decimal('1110')
Mark Dickinson84230a12010-02-18 14:49:50 +00004795 >>> ExtendedContext.logical_or(110, 1101)
4796 Decimal('1111')
4797 >>> ExtendedContext.logical_or(Decimal(110), 1101)
4798 Decimal('1111')
4799 >>> ExtendedContext.logical_or(110, Decimal(1101))
4800 Decimal('1111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004801 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004802 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004803 return a.logical_or(b, context=self)
4804
4805 def logical_xor(self, a, b):
4806 """Applies the logical operation 'xor' between each operand's digits.
4807
4808 The operands must be both logical numbers.
4809
4810 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004811 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004812 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004813 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004814 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004815 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004816 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004817 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004818 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004819 Decimal('110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004820 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004821 Decimal('1101')
Mark Dickinson84230a12010-02-18 14:49:50 +00004822 >>> ExtendedContext.logical_xor(110, 1101)
4823 Decimal('1011')
4824 >>> ExtendedContext.logical_xor(Decimal(110), 1101)
4825 Decimal('1011')
4826 >>> ExtendedContext.logical_xor(110, Decimal(1101))
4827 Decimal('1011')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004828 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004829 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004830 return a.logical_xor(b, context=self)
4831
Mark Dickinson84230a12010-02-18 14:49:50 +00004832 def max(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004833 """max compares two values numerically and returns the maximum.
4834
4835 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004836 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004837 operation. If they are numerically equal then the left-hand operand
4838 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004839 infinity) of the two operands is chosen as the result.
4840
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004841 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004842 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004843 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004844 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004845 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004846 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004847 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004848 Decimal('7')
Mark Dickinson84230a12010-02-18 14:49:50 +00004849 >>> ExtendedContext.max(1, 2)
4850 Decimal('2')
4851 >>> ExtendedContext.max(Decimal(1), 2)
4852 Decimal('2')
4853 >>> ExtendedContext.max(1, Decimal(2))
4854 Decimal('2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004855 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004856 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004857 return a.max(b, context=self)
4858
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004859 def max_mag(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004860 """Compares the values numerically with their sign ignored.
4861
4862 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
4863 Decimal('7')
4864 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
4865 Decimal('-10')
4866 >>> ExtendedContext.max_mag(1, -2)
4867 Decimal('-2')
4868 >>> ExtendedContext.max_mag(Decimal(1), -2)
4869 Decimal('-2')
4870 >>> ExtendedContext.max_mag(1, Decimal(-2))
4871 Decimal('-2')
4872 """
4873 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004874 return a.max_mag(b, context=self)
4875
Mark Dickinson84230a12010-02-18 14:49:50 +00004876 def min(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004877 """min compares two values numerically and returns the minimum.
4878
4879 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004880 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004881 operation. If they are numerically equal then the left-hand operand
4882 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004883 infinity) of the two operands is chosen as the result.
4884
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004885 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004886 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004887 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004888 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004889 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004890 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004891 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004892 Decimal('7')
Mark Dickinson84230a12010-02-18 14:49:50 +00004893 >>> ExtendedContext.min(1, 2)
4894 Decimal('1')
4895 >>> ExtendedContext.min(Decimal(1), 2)
4896 Decimal('1')
4897 >>> ExtendedContext.min(1, Decimal(29))
4898 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004899 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004900 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004901 return a.min(b, context=self)
4902
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004903 def min_mag(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004904 """Compares the values numerically with their sign ignored.
4905
4906 >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2'))
4907 Decimal('-2')
4908 >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN'))
4909 Decimal('-3')
4910 >>> ExtendedContext.min_mag(1, -2)
4911 Decimal('1')
4912 >>> ExtendedContext.min_mag(Decimal(1), -2)
4913 Decimal('1')
4914 >>> ExtendedContext.min_mag(1, Decimal(-2))
4915 Decimal('1')
4916 """
4917 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004918 return a.min_mag(b, context=self)
4919
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004920 def minus(self, a):
4921 """Minus corresponds to unary prefix minus in Python.
4922
4923 The operation is evaluated using the same rules as subtract; the
4924 operation minus(a) is calculated as subtract('0', a) where the '0'
4925 has the same exponent as the operand.
4926
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004927 >>> ExtendedContext.minus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004928 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004929 >>> ExtendedContext.minus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004930 Decimal('1.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004931 >>> ExtendedContext.minus(1)
4932 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004933 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004934 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004935 return a.__neg__(context=self)
4936
4937 def multiply(self, a, b):
4938 """multiply multiplies two operands.
4939
4940 If either operand is a special value then the general rules apply.
Mark Dickinson84230a12010-02-18 14:49:50 +00004941 Otherwise, the operands are multiplied together
4942 ('long multiplication'), resulting in a number which may be as long as
4943 the sum of the lengths of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004944
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004945 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004946 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004947 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004948 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004949 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004950 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004951 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004952 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004953 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004954 Decimal('4.28135971E+11')
Mark Dickinson84230a12010-02-18 14:49:50 +00004955 >>> ExtendedContext.multiply(7, 7)
4956 Decimal('49')
4957 >>> ExtendedContext.multiply(Decimal(7), 7)
4958 Decimal('49')
4959 >>> ExtendedContext.multiply(7, Decimal(7))
4960 Decimal('49')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004961 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004962 a = _convert_other(a, raiseit=True)
4963 r = a.__mul__(b, context=self)
4964 if r is NotImplemented:
4965 raise TypeError("Unable to convert %s to Decimal" % b)
4966 else:
4967 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004968
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004969 def next_minus(self, a):
4970 """Returns the largest representable number smaller than a.
4971
4972 >>> c = ExtendedContext.copy()
4973 >>> c.Emin = -999
4974 >>> c.Emax = 999
4975 >>> ExtendedContext.next_minus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004976 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004977 >>> c.next_minus(Decimal('1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004978 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004979 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004980 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004981 >>> c.next_minus(Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004982 Decimal('9.99999999E+999')
Mark Dickinson84230a12010-02-18 14:49:50 +00004983 >>> c.next_minus(1)
4984 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004985 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004986 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004987 return a.next_minus(context=self)
4988
4989 def next_plus(self, a):
4990 """Returns the smallest representable number larger than a.
4991
4992 >>> c = ExtendedContext.copy()
4993 >>> c.Emin = -999
4994 >>> c.Emax = 999
4995 >>> ExtendedContext.next_plus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004996 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004997 >>> c.next_plus(Decimal('-1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004998 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004999 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005000 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005001 >>> c.next_plus(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005002 Decimal('-9.99999999E+999')
Mark Dickinson84230a12010-02-18 14:49:50 +00005003 >>> c.next_plus(1)
5004 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005005 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005006 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005007 return a.next_plus(context=self)
5008
5009 def next_toward(self, a, b):
5010 """Returns the number closest to a, in direction towards b.
5011
5012 The result is the closest representable number from the first
5013 operand (but not the first operand) that is in the direction
5014 towards the second operand, unless the operands have the same
5015 value.
5016
5017 >>> c = ExtendedContext.copy()
5018 >>> c.Emin = -999
5019 >>> c.Emax = 999
5020 >>> c.next_toward(Decimal('1'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005021 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005022 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005023 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005024 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005025 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005026 >>> c.next_toward(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005027 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005028 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005029 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005030 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005031 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005032 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005033 Decimal('-0.00')
Mark Dickinson84230a12010-02-18 14:49:50 +00005034 >>> c.next_toward(0, 1)
5035 Decimal('1E-1007')
5036 >>> c.next_toward(Decimal(0), 1)
5037 Decimal('1E-1007')
5038 >>> c.next_toward(0, Decimal(1))
5039 Decimal('1E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005040 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005041 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005042 return a.next_toward(b, context=self)
5043
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005044 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00005045 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005046
5047 Essentially a plus operation with all trailing zeros removed from the
5048 result.
5049
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005050 >>> ExtendedContext.normalize(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005051 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005052 >>> ExtendedContext.normalize(Decimal('-2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005053 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005054 >>> ExtendedContext.normalize(Decimal('1.200'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005055 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005056 >>> ExtendedContext.normalize(Decimal('-120'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005057 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005058 >>> ExtendedContext.normalize(Decimal('120.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005059 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005060 >>> ExtendedContext.normalize(Decimal('0.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005061 Decimal('0')
Mark Dickinson84230a12010-02-18 14:49:50 +00005062 >>> ExtendedContext.normalize(6)
5063 Decimal('6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005064 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005065 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005066 return a.normalize(context=self)
5067
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005068 def number_class(self, a):
5069 """Returns an indication of the class of the operand.
5070
5071 The class is one of the following strings:
5072 -sNaN
5073 -NaN
5074 -Infinity
5075 -Normal
5076 -Subnormal
5077 -Zero
5078 +Zero
5079 +Subnormal
5080 +Normal
5081 +Infinity
5082
Stefan Krah1919b7e2012-03-21 18:25:23 +01005083 >>> c = ExtendedContext.copy()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005084 >>> c.Emin = -999
5085 >>> c.Emax = 999
5086 >>> c.number_class(Decimal('Infinity'))
5087 '+Infinity'
5088 >>> c.number_class(Decimal('1E-10'))
5089 '+Normal'
5090 >>> c.number_class(Decimal('2.50'))
5091 '+Normal'
5092 >>> c.number_class(Decimal('0.1E-999'))
5093 '+Subnormal'
5094 >>> c.number_class(Decimal('0'))
5095 '+Zero'
5096 >>> c.number_class(Decimal('-0'))
5097 '-Zero'
5098 >>> c.number_class(Decimal('-0.1E-999'))
5099 '-Subnormal'
5100 >>> c.number_class(Decimal('-1E-10'))
5101 '-Normal'
5102 >>> c.number_class(Decimal('-2.50'))
5103 '-Normal'
5104 >>> c.number_class(Decimal('-Infinity'))
5105 '-Infinity'
5106 >>> c.number_class(Decimal('NaN'))
5107 'NaN'
5108 >>> c.number_class(Decimal('-NaN'))
5109 'NaN'
5110 >>> c.number_class(Decimal('sNaN'))
5111 'sNaN'
Mark Dickinson84230a12010-02-18 14:49:50 +00005112 >>> c.number_class(123)
5113 '+Normal'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005114 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005115 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005116 return a.number_class(context=self)
5117
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005118 def plus(self, a):
5119 """Plus corresponds to unary prefix plus in Python.
5120
5121 The operation is evaluated using the same rules as add; the
5122 operation plus(a) is calculated as add('0', a) where the '0'
5123 has the same exponent as the operand.
5124
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005125 >>> ExtendedContext.plus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005126 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005127 >>> ExtendedContext.plus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005128 Decimal('-1.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005129 >>> ExtendedContext.plus(-1)
5130 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005131 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005132 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005133 return a.__pos__(context=self)
5134
5135 def power(self, a, b, modulo=None):
5136 """Raises a to the power of b, to modulo if given.
5137
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005138 With two arguments, compute a**b. If a is negative then b
5139 must be integral. The result will be inexact unless b is
5140 integral and the result is finite and can be expressed exactly
5141 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005142
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005143 With three arguments, compute (a**b) % modulo. For the
5144 three argument form, the following restrictions on the
5145 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005146
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005147 - all three arguments must be integral
5148 - b must be nonnegative
5149 - at least one of a or b must be nonzero
5150 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005151
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005152 The result of pow(a, b, modulo) is identical to the result
5153 that would be obtained by computing (a**b) % modulo with
5154 unbounded precision, but is computed more efficiently. It is
5155 always exact.
5156
5157 >>> c = ExtendedContext.copy()
5158 >>> c.Emin = -999
5159 >>> c.Emax = 999
5160 >>> c.power(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005161 Decimal('8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005162 >>> c.power(Decimal('-2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005163 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005164 >>> c.power(Decimal('2'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005165 Decimal('0.125')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005166 >>> c.power(Decimal('1.7'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005167 Decimal('69.7575744')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005168 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005169 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005170 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005171 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005172 >>> c.power(Decimal('Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005173 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005174 >>> c.power(Decimal('Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005175 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005176 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005177 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005178 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005179 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005180 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005181 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005182 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005183 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005184 >>> c.power(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005185 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005186
5187 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005188 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005189 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005190 Decimal('-11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005191 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005192 Decimal('1')
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('23E12345'), Decimal('67E189'), Decimal('123456789'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005196 Decimal('11729830')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005197 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005198 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005199 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005200 Decimal('1')
Mark Dickinson84230a12010-02-18 14:49:50 +00005201 >>> ExtendedContext.power(7, 7)
5202 Decimal('823543')
5203 >>> ExtendedContext.power(Decimal(7), 7)
5204 Decimal('823543')
5205 >>> ExtendedContext.power(7, Decimal(7), 2)
5206 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005207 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005208 a = _convert_other(a, raiseit=True)
5209 r = a.__pow__(b, modulo, context=self)
5210 if r is NotImplemented:
5211 raise TypeError("Unable to convert %s to Decimal" % b)
5212 else:
5213 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005214
5215 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005216 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005217
5218 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00005219 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005220 exponent is being increased), multiplied by a positive power of ten (if
5221 the exponent is being decreased), or is unchanged (if the exponent is
5222 already equal to that of the right-hand operand).
5223
5224 Unlike other operations, if the length of the coefficient after the
5225 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00005226 operation condition is raised. This guarantees that, unless there is
5227 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005228 equal to that of the right-hand operand.
5229
5230 Also unlike other operations, quantize will never raise Underflow, even
5231 if the result is subnormal and inexact.
5232
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005233 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005234 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005235 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005236 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005237 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005238 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005239 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005240 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005241 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005242 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005243 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005244 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005245 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005246 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005247 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005248 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005249 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005250 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005251 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005252 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005253 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005254 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005255 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005256 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005257 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005258 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005259 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005260 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005261 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005262 Decimal('2E+2')
Mark Dickinson84230a12010-02-18 14:49:50 +00005263 >>> ExtendedContext.quantize(1, 2)
5264 Decimal('1')
5265 >>> ExtendedContext.quantize(Decimal(1), 2)
5266 Decimal('1')
5267 >>> ExtendedContext.quantize(1, Decimal(2))
5268 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005269 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005270 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005271 return a.quantize(b, context=self)
5272
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005273 def radix(self):
5274 """Just returns 10, as this is Decimal, :)
5275
5276 >>> ExtendedContext.radix()
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005277 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005278 """
5279 return Decimal(10)
5280
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005281 def remainder(self, a, b):
5282 """Returns the remainder from integer division.
5283
5284 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00005285 calculating integer division as described for divide-integer, rounded
5286 to precision digits if necessary. The sign of the result, if
5287 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005288
5289 This operation will fail under the same conditions as integer division
5290 (that is, if integer division on the same two operands would fail, the
5291 remainder cannot be calculated).
5292
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005293 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005294 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005295 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005296 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005297 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005298 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005299 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005300 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005301 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005302 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005303 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005304 Decimal('1.0')
Mark Dickinson84230a12010-02-18 14:49:50 +00005305 >>> ExtendedContext.remainder(22, 6)
5306 Decimal('4')
5307 >>> ExtendedContext.remainder(Decimal(22), 6)
5308 Decimal('4')
5309 >>> ExtendedContext.remainder(22, Decimal(6))
5310 Decimal('4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005311 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005312 a = _convert_other(a, raiseit=True)
5313 r = a.__mod__(b, context=self)
5314 if r is NotImplemented:
5315 raise TypeError("Unable to convert %s to Decimal" % b)
5316 else:
5317 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005318
5319 def remainder_near(self, a, b):
5320 """Returns to be "a - b * n", where n is the integer nearest the exact
5321 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00005322 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005323 sign of a.
5324
5325 This operation will fail under the same conditions as integer division
5326 (that is, if integer division on the same two operands would fail, the
5327 remainder cannot be calculated).
5328
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005329 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005330 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005331 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005332 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005333 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005334 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005335 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005336 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005337 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005338 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005339 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005340 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005341 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005342 Decimal('-0.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005343 >>> ExtendedContext.remainder_near(3, 11)
5344 Decimal('3')
5345 >>> ExtendedContext.remainder_near(Decimal(3), 11)
5346 Decimal('3')
5347 >>> ExtendedContext.remainder_near(3, Decimal(11))
5348 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005349 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005350 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005351 return a.remainder_near(b, context=self)
5352
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005353 def rotate(self, a, b):
5354 """Returns a rotated copy of a, b times.
5355
5356 The coefficient of the result is a rotated copy of the digits in
5357 the coefficient of the first operand. The number of places of
5358 rotation is taken from the absolute value of the second operand,
5359 with the rotation being to the left if the second operand is
5360 positive or to the right otherwise.
5361
5362 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005363 Decimal('400000003')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005364 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005365 Decimal('12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005366 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005367 Decimal('891234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005368 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005369 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005370 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005371 Decimal('345678912')
Mark Dickinson84230a12010-02-18 14:49:50 +00005372 >>> ExtendedContext.rotate(1333333, 1)
5373 Decimal('13333330')
5374 >>> ExtendedContext.rotate(Decimal(1333333), 1)
5375 Decimal('13333330')
5376 >>> ExtendedContext.rotate(1333333, Decimal(1))
5377 Decimal('13333330')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005378 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005379 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005380 return a.rotate(b, context=self)
5381
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005382 def same_quantum(self, a, b):
5383 """Returns True if the two operands have the same exponent.
5384
5385 The result is never affected by either the sign or the coefficient of
5386 either operand.
5387
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005388 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005389 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005390 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005391 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005392 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005393 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005394 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005395 True
Mark Dickinson84230a12010-02-18 14:49:50 +00005396 >>> ExtendedContext.same_quantum(10000, -1)
5397 True
5398 >>> ExtendedContext.same_quantum(Decimal(10000), -1)
5399 True
5400 >>> ExtendedContext.same_quantum(10000, Decimal(-1))
5401 True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005402 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005403 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005404 return a.same_quantum(b)
5405
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005406 def scaleb (self, a, b):
5407 """Returns the first operand after adding the second value its exp.
5408
5409 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005410 Decimal('0.0750')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005411 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005412 Decimal('7.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005413 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005414 Decimal('7.50E+3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005415 >>> ExtendedContext.scaleb(1, 4)
5416 Decimal('1E+4')
5417 >>> ExtendedContext.scaleb(Decimal(1), 4)
5418 Decimal('1E+4')
5419 >>> ExtendedContext.scaleb(1, Decimal(4))
5420 Decimal('1E+4')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005421 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005422 a = _convert_other(a, raiseit=True)
5423 return a.scaleb(b, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005424
5425 def shift(self, a, b):
5426 """Returns a shifted copy of a, b times.
5427
5428 The coefficient of the result is a shifted copy of the digits
5429 in the coefficient of the first operand. The number of places
5430 to shift is taken from the absolute value of the second operand,
5431 with the shift being to the left if the second operand is
5432 positive or to the right otherwise. Digits shifted into the
5433 coefficient are zeros.
5434
5435 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005436 Decimal('400000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005437 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005438 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005439 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005440 Decimal('1234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005441 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005442 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005443 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005444 Decimal('345678900')
Mark Dickinson84230a12010-02-18 14:49:50 +00005445 >>> ExtendedContext.shift(88888888, 2)
5446 Decimal('888888800')
5447 >>> ExtendedContext.shift(Decimal(88888888), 2)
5448 Decimal('888888800')
5449 >>> ExtendedContext.shift(88888888, Decimal(2))
5450 Decimal('888888800')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005451 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005452 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005453 return a.shift(b, context=self)
5454
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005455 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005456 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005457
5458 If the result must be inexact, it is rounded using the round-half-even
5459 algorithm.
5460
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005461 >>> ExtendedContext.sqrt(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005462 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005463 >>> ExtendedContext.sqrt(Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005464 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005465 >>> ExtendedContext.sqrt(Decimal('0.39'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005466 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005467 >>> ExtendedContext.sqrt(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005468 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005469 >>> ExtendedContext.sqrt(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005470 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005471 >>> ExtendedContext.sqrt(Decimal('1.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005472 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005473 >>> ExtendedContext.sqrt(Decimal('1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005474 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005475 >>> ExtendedContext.sqrt(Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005476 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005477 >>> ExtendedContext.sqrt(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005478 Decimal('3.16227766')
Mark Dickinson84230a12010-02-18 14:49:50 +00005479 >>> ExtendedContext.sqrt(2)
5480 Decimal('1.41421356')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005481 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005482 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005483 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005484 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005485 return a.sqrt(context=self)
5486
5487 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00005488 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005489
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005490 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005491 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005492 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005493 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005494 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005495 Decimal('-0.77')
Mark Dickinson84230a12010-02-18 14:49:50 +00005496 >>> ExtendedContext.subtract(8, 5)
5497 Decimal('3')
5498 >>> ExtendedContext.subtract(Decimal(8), 5)
5499 Decimal('3')
5500 >>> ExtendedContext.subtract(8, Decimal(5))
5501 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005502 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005503 a = _convert_other(a, raiseit=True)
5504 r = a.__sub__(b, context=self)
5505 if r is NotImplemented:
5506 raise TypeError("Unable to convert %s to Decimal" % b)
5507 else:
5508 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005509
5510 def to_eng_string(self, a):
5511 """Converts a number to a string, using scientific notation.
5512
5513 The operation is not affected by the context.
5514 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005515 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005516 return a.to_eng_string(context=self)
5517
5518 def to_sci_string(self, a):
5519 """Converts a number to a string, using scientific notation.
5520
5521 The operation is not affected by the context.
5522 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005523 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005524 return a.__str__(context=self)
5525
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005526 def to_integral_exact(self, a):
5527 """Rounds to an integer.
5528
5529 When the operand has a negative exponent, the result is the same
5530 as using the quantize() operation using the given operand as the
5531 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5532 of the operand as the precision setting; Inexact and Rounded flags
5533 are allowed in this operation. The rounding mode is taken from the
5534 context.
5535
5536 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005537 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005538 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005539 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005540 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005541 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005542 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005543 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005544 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005545 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005546 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005547 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005548 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005549 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005550 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005551 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005552 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005553 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005554 return a.to_integral_exact(context=self)
5555
5556 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005557 """Rounds to an integer.
5558
5559 When the operand has a negative exponent, the result is the same
5560 as using the quantize() operation using the given operand as the
5561 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5562 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00005563 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005564
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005565 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005566 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005567 >>> ExtendedContext.to_integral_value(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005568 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005569 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005570 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005571 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005572 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005573 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005574 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005575 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005576 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005577 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005578 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005579 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005580 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005581 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005582 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005583 return a.to_integral_value(context=self)
5584
5585 # the method name changed, but we provide also the old one, for compatibility
5586 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005587
5588class _WorkRep(object):
5589 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00005590 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005591 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005592 # exp: None, int, or string
5593
5594 def __init__(self, value=None):
5595 if value is None:
5596 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005597 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005598 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00005599 elif isinstance(value, Decimal):
5600 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005601 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005602 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00005603 else:
5604 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005605 self.sign = value[0]
5606 self.int = value[1]
5607 self.exp = value[2]
5608
5609 def __repr__(self):
5610 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5611
5612 __str__ = __repr__
5613
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005614
5615
Christian Heimes2c181612007-12-17 20:04:13 +00005616def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005617 """Normalizes op1, op2 to have the same exp and length of coefficient.
5618
5619 Done during addition.
5620 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005621 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005622 tmp = op2
5623 other = op1
5624 else:
5625 tmp = op1
5626 other = op2
5627
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005628 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5629 # Then adding 10**exp to tmp has the same effect (after rounding)
5630 # as adding any positive quantity smaller than 10**exp; similarly
5631 # for subtraction. So if other is smaller than 10**exp we replace
5632 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00005633 tmp_len = len(str(tmp.int))
5634 other_len = len(str(other.int))
5635 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5636 if other_len + other.exp - 1 < exp:
5637 other.int = 1
5638 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005639
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005640 tmp.int *= 10 ** (tmp.exp - other.exp)
5641 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005642 return op1, op2
5643
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005644##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005645
Raymond Hettingerdb213a22010-11-27 08:09:40 +00005646_nbits = int.bit_length
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005647
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01005648def _decimal_lshift_exact(n, e):
5649 """ Given integers n and e, return n * 10**e if it's an integer, else None.
5650
5651 The computation is designed to avoid computing large powers of 10
5652 unnecessarily.
5653
5654 >>> _decimal_lshift_exact(3, 4)
5655 30000
5656 >>> _decimal_lshift_exact(300, -999999999) # returns None
5657
5658 """
5659 if n == 0:
5660 return 0
5661 elif e >= 0:
5662 return n * 10**e
5663 else:
5664 # val_n = largest power of 10 dividing n.
5665 str_n = str(abs(n))
5666 val_n = len(str_n) - len(str_n.rstrip('0'))
5667 return None if val_n < -e else n // 10**-e
5668
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005669def _sqrt_nearest(n, a):
5670 """Closest integer to the square root of the positive integer n. a is
5671 an initial approximation to the square root. Any positive integer
5672 will do for a, but the closer a is to the square root of n the
5673 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005674
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005675 """
5676 if n <= 0 or a <= 0:
5677 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5678
5679 b=0
5680 while a != b:
5681 b, a = a, a--n//a>>1
5682 return a
5683
5684def _rshift_nearest(x, shift):
5685 """Given an integer x and a nonnegative integer shift, return closest
5686 integer to x / 2**shift; use round-to-even in case of a tie.
5687
5688 """
5689 b, q = 1 << shift, x >> shift
5690 return q + (2*(x & (b-1)) + (q&1) > b)
5691
5692def _div_nearest(a, b):
5693 """Closest integer to a/b, a and b positive integers; rounds to even
5694 in the case of a tie.
5695
5696 """
5697 q, r = divmod(a, b)
5698 return q + (2*r + (q&1) > b)
5699
5700def _ilog(x, M, L = 8):
5701 """Integer approximation to M*log(x/M), with absolute error boundable
5702 in terms only of x/M.
5703
5704 Given positive integers x and M, return an integer approximation to
5705 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5706 between the approximation and the exact result is at most 22. For
5707 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5708 both cases these are upper bounds on the error; it will usually be
5709 much smaller."""
5710
5711 # The basic algorithm is the following: let log1p be the function
5712 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5713 # the reduction
5714 #
5715 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5716 #
5717 # repeatedly until the argument to log1p is small (< 2**-L in
5718 # absolute value). For small y we can use the Taylor series
5719 # expansion
5720 #
5721 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5722 #
5723 # truncating at T such that y**T is small enough. The whole
5724 # computation is carried out in a form of fixed-point arithmetic,
5725 # with a real number z being represented by an integer
5726 # approximation to z*M. To avoid loss of precision, the y below
5727 # is actually an integer approximation to 2**R*y*M, where R is the
5728 # number of reductions performed so far.
5729
5730 y = x-M
5731 # argument reduction; R = number of reductions performed
5732 R = 0
5733 while (R <= L and abs(y) << L-R >= M or
5734 R > L and abs(y) >> R-L >= M):
5735 y = _div_nearest((M*y) << 1,
5736 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5737 R += 1
5738
5739 # Taylor series with T terms
5740 T = -int(-10*len(str(M))//(3*L))
5741 yshift = _rshift_nearest(y, R)
5742 w = _div_nearest(M, T)
5743 for k in range(T-1, 0, -1):
5744 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5745
5746 return _div_nearest(w*y, M)
5747
5748def _dlog10(c, e, p):
5749 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5750 approximation to 10**p * log10(c*10**e), with an absolute error of
5751 at most 1. Assumes that c*10**e is not exactly 1."""
5752
5753 # increase precision by 2; compensate for this by dividing
5754 # final result by 100
5755 p += 2
5756
5757 # write c*10**e as d*10**f with either:
5758 # f >= 0 and 1 <= d <= 10, or
5759 # f <= 0 and 0.1 <= d <= 1.
5760 # Thus for c*10**e close to 1, f = 0
5761 l = len(str(c))
5762 f = e+l - (e+l >= 1)
5763
5764 if p > 0:
5765 M = 10**p
5766 k = e+p-f
5767 if k >= 0:
5768 c *= 10**k
5769 else:
5770 c = _div_nearest(c, 10**-k)
5771
5772 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005773 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005774 log_d = _div_nearest(log_d*M, log_10)
5775 log_tenpower = f*M # exact
5776 else:
5777 log_d = 0 # error < 2.31
Neal Norwitz2f99b242008-08-24 05:48:10 +00005778 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005779
5780 return _div_nearest(log_tenpower+log_d, 100)
5781
5782def _dlog(c, e, p):
5783 """Given integers c, e and p with c > 0, compute an integer
5784 approximation to 10**p * log(c*10**e), with an absolute error of
5785 at most 1. Assumes that c*10**e is not exactly 1."""
5786
5787 # Increase precision by 2. The precision increase is compensated
5788 # for at the end with a division by 100.
5789 p += 2
5790
5791 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5792 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5793 # as 10**p * log(d) + 10**p*f * log(10).
5794 l = len(str(c))
5795 f = e+l - (e+l >= 1)
5796
5797 # compute approximation to 10**p*log(d), with error < 27
5798 if p > 0:
5799 k = e+p-f
5800 if k >= 0:
5801 c *= 10**k
5802 else:
5803 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5804
5805 # _ilog magnifies existing error in c by a factor of at most 10
5806 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5807 else:
5808 # p <= 0: just approximate the whole thing by 0; error < 2.31
5809 log_d = 0
5810
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005811 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005812 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005813 extra = len(str(abs(f)))-1
5814 if p + extra >= 0:
5815 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5816 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5817 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005818 else:
5819 f_log_ten = 0
5820 else:
5821 f_log_ten = 0
5822
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005823 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005824 return _div_nearest(f_log_ten + log_d, 100)
5825
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005826class _Log10Memoize(object):
5827 """Class to compute, store, and allow retrieval of, digits of the
5828 constant log(10) = 2.302585.... This constant is needed by
5829 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5830 def __init__(self):
5831 self.digits = "23025850929940456840179914546843642076011014886"
5832
5833 def getdigits(self, p):
5834 """Given an integer p >= 0, return floor(10**p)*log(10).
5835
5836 For example, self.getdigits(3) returns 2302.
5837 """
5838 # digits are stored as a string, for quick conversion to
5839 # integer in the case that we've already computed enough
5840 # digits; the stored digits should always be correct
5841 # (truncated, not rounded to nearest).
5842 if p < 0:
5843 raise ValueError("p should be nonnegative")
5844
5845 if p >= len(self.digits):
5846 # compute p+3, p+6, p+9, ... digits; continue until at
5847 # least one of the extra digits is nonzero
5848 extra = 3
5849 while True:
5850 # compute p+extra digits, correct to within 1ulp
5851 M = 10**(p+extra+2)
5852 digits = str(_div_nearest(_ilog(10*M, M), 100))
5853 if digits[-extra:] != '0'*extra:
5854 break
5855 extra += 3
5856 # keep all reliable digits so far; remove trailing zeros
5857 # and next nonzero digit
5858 self.digits = digits.rstrip('0')[:-1]
5859 return int(self.digits[:p+1])
5860
5861_log10_digits = _Log10Memoize().getdigits
5862
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005863def _iexp(x, M, L=8):
5864 """Given integers x and M, M > 0, such that x/M is small in absolute
5865 value, compute an integer approximation to M*exp(x/M). For 0 <=
5866 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5867 is usually much smaller)."""
5868
5869 # Algorithm: to compute exp(z) for a real number z, first divide z
5870 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5871 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5872 # series
5873 #
5874 # expm1(x) = x + x**2/2! + x**3/3! + ...
5875 #
5876 # Now use the identity
5877 #
5878 # expm1(2x) = expm1(x)*(expm1(x)+2)
5879 #
5880 # R times to compute the sequence expm1(z/2**R),
5881 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5882
5883 # Find R such that x/2**R/M <= 2**-L
5884 R = _nbits((x<<L)//M)
5885
5886 # Taylor series. (2**L)**T > M
5887 T = -int(-10*len(str(M))//(3*L))
5888 y = _div_nearest(x, T)
5889 Mshift = M<<R
5890 for i in range(T-1, 0, -1):
5891 y = _div_nearest(x*(Mshift + y), Mshift * i)
5892
5893 # Expansion
5894 for k in range(R-1, -1, -1):
5895 Mshift = M<<(k+2)
5896 y = _div_nearest(y*(y+Mshift), Mshift)
5897
5898 return M+y
5899
5900def _dexp(c, e, p):
5901 """Compute an approximation to exp(c*10**e), with p decimal places of
5902 precision.
5903
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005904 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005905
5906 10**(p-1) <= d <= 10**p, and
5907 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5908
5909 In other words, d*10**f is an approximation to exp(c*10**e) with p
5910 digits of precision, and with an error in d of at most 1. This is
5911 almost, but not quite, the same as the error being < 1ulp: when d
5912 = 10**(p-1) the error could be up to 10 ulp."""
5913
5914 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5915 p += 2
5916
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005917 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005918 extra = max(0, e + len(str(c)) - 1)
5919 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005920
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005921 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005922 # rounding down
5923 shift = e+q
5924 if shift >= 0:
5925 cshift = c*10**shift
5926 else:
5927 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005928 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005929
5930 # reduce remainder back to original precision
5931 rem = _div_nearest(rem, 10**extra)
5932
5933 # error in result of _iexp < 120; error after division < 0.62
5934 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5935
5936def _dpower(xc, xe, yc, ye, p):
5937 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5938 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5939
5940 10**(p-1) <= c <= 10**p, and
5941 (c-1)*10**e < x**y < (c+1)*10**e
5942
5943 in other words, c*10**e is an approximation to x**y with p digits
5944 of precision, and with an error in c of at most 1. (This is
5945 almost, but not quite, the same as the error being < 1ulp: when c
5946 == 10**(p-1) we can only guarantee error < 10ulp.)
5947
5948 We assume that: x is positive and not equal to 1, and y is nonzero.
5949 """
5950
5951 # Find b such that 10**(b-1) <= |y| <= 10**b
5952 b = len(str(abs(yc))) + ye
5953
5954 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5955 lxc = _dlog(xc, xe, p+b+1)
5956
5957 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5958 shift = ye-b
5959 if shift >= 0:
5960 pc = lxc*yc*10**shift
5961 else:
5962 pc = _div_nearest(lxc*yc, 10**-shift)
5963
5964 if pc == 0:
5965 # we prefer a result that isn't exactly 1; this makes it
5966 # easier to compute a correctly rounded result in __pow__
5967 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5968 coeff, exp = 10**(p-1)+1, 1-p
5969 else:
5970 coeff, exp = 10**p-1, -p
5971 else:
5972 coeff, exp = _dexp(pc, -(p+1), p+1)
5973 coeff = _div_nearest(coeff, 10)
5974 exp += 1
5975
5976 return coeff, exp
5977
5978def _log10_lb(c, correction = {
5979 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5980 '6': 23, '7': 16, '8': 10, '9': 5}):
5981 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5982 if c <= 0:
5983 raise ValueError("The argument to _log10_lb should be nonnegative.")
5984 str_c = str(c)
5985 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005986
Guido van Rossumd8faa362007-04-27 19:54:29 +00005987##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005988
Mark Dickinsonac256ab2010-04-03 11:08:14 +00005989def _convert_other(other, raiseit=False, allow_float=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005990 """Convert other to Decimal.
5991
5992 Verifies that it's ok to use in an implicit construction.
Mark Dickinsonac256ab2010-04-03 11:08:14 +00005993 If allow_float is true, allow conversion from float; this
5994 is used in the comparison methods (__eq__ and friends).
5995
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005996 """
5997 if isinstance(other, Decimal):
5998 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005999 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006000 return Decimal(other)
Mark Dickinsonac256ab2010-04-03 11:08:14 +00006001 if allow_float and isinstance(other, float):
6002 return Decimal.from_float(other)
6003
Thomas Wouters1b7f8912007-09-19 03:06:30 +00006004 if raiseit:
6005 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00006006 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006007
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006008def _convert_for_comparison(self, other, equality_op=False):
6009 """Given a Decimal instance self and a Python object other, return
Mark Dickinson1c164a62010-06-11 16:49:20 +00006010 a pair (s, o) of Decimal instances such that "s op o" is
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006011 equivalent to "self op other" for any of the 6 comparison
6012 operators "op".
6013
6014 """
6015 if isinstance(other, Decimal):
6016 return self, other
6017
6018 # Comparison with a Rational instance (also includes integers):
6019 # self op n/d <=> self*d op n (for n and d integers, d positive).
6020 # A NaN or infinity can be left unchanged without affecting the
6021 # comparison result.
6022 if isinstance(other, _numbers.Rational):
6023 if not self._is_special:
6024 self = _dec_from_triple(self._sign,
6025 str(int(self._int) * other.denominator),
6026 self._exp)
6027 return self, Decimal(other.numerator)
6028
6029 # Comparisons with float and complex types. == and != comparisons
6030 # with complex numbers should succeed, returning either True or False
6031 # as appropriate. Other comparisons return NotImplemented.
6032 if equality_op and isinstance(other, _numbers.Complex) and other.imag == 0:
6033 other = other.real
6034 if isinstance(other, float):
Stefan Krah1919b7e2012-03-21 18:25:23 +01006035 context = getcontext()
6036 if equality_op:
6037 context.flags[FloatOperation] = 1
6038 else:
6039 context._raise_error(FloatOperation,
6040 "strict semantics for mixing floats and Decimals are enabled")
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006041 return self, Decimal.from_float(other)
6042 return NotImplemented, NotImplemented
6043
6044
Guido van Rossumd8faa362007-04-27 19:54:29 +00006045##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006046
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006047# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00006048# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006049
6050DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00006051 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006052 traps=[DivisionByZero, Overflow, InvalidOperation],
6053 flags=[],
Stefan Krah1919b7e2012-03-21 18:25:23 +01006054 Emax=999999,
6055 Emin=-999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00006056 capitals=1,
6057 clamp=0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006058)
6059
6060# Pre-made alternate contexts offered by the specification
6061# Don't change these; the user should be able to select these
6062# contexts and be able to reproduce results from other implementations
6063# of the spec.
6064
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00006065BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006066 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006067 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
6068 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006069)
6070
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00006071ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00006072 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006073 traps=[],
6074 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006075)
6076
6077
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006078##### crud for parsing strings #############################################
Christian Heimes23daade02008-02-25 12:39:23 +00006079#
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006080# Regular expression used for parsing numeric strings. Additional
6081# comments:
6082#
6083# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
6084# whitespace. But note that the specification disallows whitespace in
6085# a numeric string.
6086#
6087# 2. For finite numbers (not infinities and NaNs) the body of the
6088# number between the optional sign and the optional exponent must have
6089# at least one decimal digit, possibly after the decimal point. The
Mark Dickinson345adc42009-08-02 10:14:23 +00006090# lookahead expression '(?=\d|\.\d)' checks this.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006091
6092import re
Benjamin Peterson41181742008-07-02 20:22:54 +00006093_parser = re.compile(r""" # A numeric string consists of:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006094# \s*
Benjamin Peterson41181742008-07-02 20:22:54 +00006095 (?P<sign>[-+])? # an optional sign, followed by either...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006096 (
Mark Dickinson345adc42009-08-02 10:14:23 +00006097 (?=\d|\.\d) # ...a number (with at least one digit)
6098 (?P<int>\d*) # having a (possibly empty) integer part
6099 (\.(?P<frac>\d*))? # followed by an optional fractional part
6100 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006101 |
Benjamin Peterson41181742008-07-02 20:22:54 +00006102 Inf(inity)? # ...an infinity, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006103 |
Benjamin Peterson41181742008-07-02 20:22:54 +00006104 (?P<signal>s)? # ...an (optionally signaling)
6105 NaN # NaN
Mark Dickinson345adc42009-08-02 10:14:23 +00006106 (?P<diag>\d*) # with (possibly empty) diagnostic info.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006107 )
6108# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00006109 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006110""", re.VERBOSE | re.IGNORECASE).match
6111
Christian Heimescbf3b5c2007-12-03 21:02:03 +00006112_all_zeros = re.compile('0*$').match
6113_exact_half = re.compile('50*$').match
Christian Heimesf16baeb2008-02-29 14:57:44 +00006114
6115##### PEP3101 support functions ##############################################
Mark Dickinson79f52032009-03-17 23:12:51 +00006116# The functions in this section have little to do with the Decimal
6117# class, and could potentially be reused or adapted for other pure
Christian Heimesf16baeb2008-02-29 14:57:44 +00006118# Python numeric classes that want to implement __format__
6119#
6120# A format specifier for Decimal looks like:
6121#
Eric Smith984bb582010-11-25 16:08:06 +00006122# [[fill]align][sign][#][0][minimumwidth][,][.precision][type]
Christian Heimesf16baeb2008-02-29 14:57:44 +00006123
6124_parse_format_specifier_regex = re.compile(r"""\A
6125(?:
6126 (?P<fill>.)?
6127 (?P<align>[<>=^])
6128)?
6129(?P<sign>[-+ ])?
Eric Smith984bb582010-11-25 16:08:06 +00006130(?P<alt>\#)?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006131(?P<zeropad>0)?
6132(?P<minimumwidth>(?!0)\d+)?
Mark Dickinson79f52032009-03-17 23:12:51 +00006133(?P<thousands_sep>,)?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006134(?:\.(?P<precision>0|(?!0)\d+))?
Mark Dickinson79f52032009-03-17 23:12:51 +00006135(?P<type>[eEfFgGn%])?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006136\Z
6137""", re.VERBOSE)
6138
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006139del re
6140
Mark Dickinson79f52032009-03-17 23:12:51 +00006141# The locale module is only needed for the 'n' format specifier. The
6142# rest of the PEP 3101 code functions quite happily without it, so we
6143# don't care too much if locale isn't present.
6144try:
6145 import locale as _locale
6146except ImportError:
6147 pass
6148
6149def _parse_format_specifier(format_spec, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00006150 """Parse and validate a format specifier.
6151
6152 Turns a standard numeric format specifier into a dict, with the
6153 following entries:
6154
6155 fill: fill character to pad field to minimum width
6156 align: alignment type, either '<', '>', '=' or '^'
6157 sign: either '+', '-' or ' '
6158 minimumwidth: nonnegative integer giving minimum width
Mark Dickinson79f52032009-03-17 23:12:51 +00006159 zeropad: boolean, indicating whether to pad with zeros
6160 thousands_sep: string to use as thousands separator, or ''
6161 grouping: grouping for thousands separators, in format
6162 used by localeconv
6163 decimal_point: string to use for decimal point
Christian Heimesf16baeb2008-02-29 14:57:44 +00006164 precision: nonnegative integer giving precision, or None
6165 type: one of the characters 'eEfFgG%', or None
Christian Heimesf16baeb2008-02-29 14:57:44 +00006166
6167 """
6168 m = _parse_format_specifier_regex.match(format_spec)
6169 if m is None:
6170 raise ValueError("Invalid format specifier: " + format_spec)
6171
6172 # get the dictionary
6173 format_dict = m.groupdict()
6174
Mark Dickinson79f52032009-03-17 23:12:51 +00006175 # zeropad; defaults for fill and alignment. If zero padding
6176 # is requested, the fill and align fields should be absent.
Christian Heimesf16baeb2008-02-29 14:57:44 +00006177 fill = format_dict['fill']
6178 align = format_dict['align']
Mark Dickinson79f52032009-03-17 23:12:51 +00006179 format_dict['zeropad'] = (format_dict['zeropad'] is not None)
6180 if format_dict['zeropad']:
6181 if fill is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00006182 raise ValueError("Fill character conflicts with '0'"
6183 " in format specifier: " + format_spec)
Mark Dickinson79f52032009-03-17 23:12:51 +00006184 if align is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00006185 raise ValueError("Alignment conflicts with '0' in "
6186 "format specifier: " + format_spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00006187 format_dict['fill'] = fill or ' '
Mark Dickinson46ab5d02009-09-08 20:22:46 +00006188 # PEP 3101 originally specified that the default alignment should
6189 # be left; it was later agreed that right-aligned makes more sense
6190 # for numeric types. See http://bugs.python.org/issue6857.
6191 format_dict['align'] = align or '>'
Christian Heimesf16baeb2008-02-29 14:57:44 +00006192
Mark Dickinson79f52032009-03-17 23:12:51 +00006193 # default sign handling: '-' for negative, '' for positive
Christian Heimesf16baeb2008-02-29 14:57:44 +00006194 if format_dict['sign'] is None:
6195 format_dict['sign'] = '-'
6196
Christian Heimesf16baeb2008-02-29 14:57:44 +00006197 # minimumwidth defaults to 0; precision remains None if not given
6198 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
6199 if format_dict['precision'] is not None:
6200 format_dict['precision'] = int(format_dict['precision'])
6201
6202 # if format type is 'g' or 'G' then a precision of 0 makes little
6203 # sense; convert it to 1. Same if format type is unspecified.
6204 if format_dict['precision'] == 0:
Stefan Krah1919b7e2012-03-21 18:25:23 +01006205 if format_dict['type'] is None or format_dict['type'] in 'gGn':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006206 format_dict['precision'] = 1
6207
Mark Dickinson79f52032009-03-17 23:12:51 +00006208 # determine thousands separator, grouping, and decimal separator, and
6209 # add appropriate entries to format_dict
6210 if format_dict['type'] == 'n':
6211 # apart from separators, 'n' behaves just like 'g'
6212 format_dict['type'] = 'g'
6213 if _localeconv is None:
6214 _localeconv = _locale.localeconv()
6215 if format_dict['thousands_sep'] is not None:
6216 raise ValueError("Explicit thousands separator conflicts with "
6217 "'n' type in format specifier: " + format_spec)
6218 format_dict['thousands_sep'] = _localeconv['thousands_sep']
6219 format_dict['grouping'] = _localeconv['grouping']
6220 format_dict['decimal_point'] = _localeconv['decimal_point']
6221 else:
6222 if format_dict['thousands_sep'] is None:
6223 format_dict['thousands_sep'] = ''
6224 format_dict['grouping'] = [3, 0]
6225 format_dict['decimal_point'] = '.'
Christian Heimesf16baeb2008-02-29 14:57:44 +00006226
6227 return format_dict
6228
Mark Dickinson79f52032009-03-17 23:12:51 +00006229def _format_align(sign, body, spec):
6230 """Given an unpadded, non-aligned numeric string 'body' and sign
Ezio Melotti42da6632011-03-15 05:18:48 +02006231 string 'sign', add padding and alignment conforming to the given
Mark Dickinson79f52032009-03-17 23:12:51 +00006232 format specifier dictionary 'spec' (as produced by
6233 parse_format_specifier).
Christian Heimesf16baeb2008-02-29 14:57:44 +00006234
6235 """
Christian Heimesf16baeb2008-02-29 14:57:44 +00006236 # how much extra space do we have to play with?
Mark Dickinson79f52032009-03-17 23:12:51 +00006237 minimumwidth = spec['minimumwidth']
6238 fill = spec['fill']
6239 padding = fill*(minimumwidth - len(sign) - len(body))
Christian Heimesf16baeb2008-02-29 14:57:44 +00006240
Mark Dickinson79f52032009-03-17 23:12:51 +00006241 align = spec['align']
Christian Heimesf16baeb2008-02-29 14:57:44 +00006242 if align == '<':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006243 result = sign + body + padding
Mark Dickinsonad416342009-03-17 18:10:15 +00006244 elif align == '>':
6245 result = padding + sign + body
Christian Heimesf16baeb2008-02-29 14:57:44 +00006246 elif align == '=':
6247 result = sign + padding + body
Mark Dickinson79f52032009-03-17 23:12:51 +00006248 elif align == '^':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006249 half = len(padding)//2
6250 result = padding[:half] + sign + body + padding[half:]
Mark Dickinson79f52032009-03-17 23:12:51 +00006251 else:
6252 raise ValueError('Unrecognised alignment field')
Christian Heimesf16baeb2008-02-29 14:57:44 +00006253
Christian Heimesf16baeb2008-02-29 14:57:44 +00006254 return result
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006255
Mark Dickinson79f52032009-03-17 23:12:51 +00006256def _group_lengths(grouping):
6257 """Convert a localeconv-style grouping into a (possibly infinite)
6258 iterable of integers representing group lengths.
6259
6260 """
6261 # The result from localeconv()['grouping'], and the input to this
6262 # function, should be a list of integers in one of the
6263 # following three forms:
6264 #
6265 # (1) an empty list, or
6266 # (2) nonempty list of positive integers + [0]
6267 # (3) list of positive integers + [locale.CHAR_MAX], or
6268
6269 from itertools import chain, repeat
6270 if not grouping:
6271 return []
6272 elif grouping[-1] == 0 and len(grouping) >= 2:
6273 return chain(grouping[:-1], repeat(grouping[-2]))
6274 elif grouping[-1] == _locale.CHAR_MAX:
6275 return grouping[:-1]
6276 else:
6277 raise ValueError('unrecognised format for grouping')
6278
6279def _insert_thousands_sep(digits, spec, min_width=1):
6280 """Insert thousands separators into a digit string.
6281
6282 spec is a dictionary whose keys should include 'thousands_sep' and
6283 'grouping'; typically it's the result of parsing the format
6284 specifier using _parse_format_specifier.
6285
6286 The min_width keyword argument gives the minimum length of the
6287 result, which will be padded on the left with zeros if necessary.
6288
6289 If necessary, the zero padding adds an extra '0' on the left to
6290 avoid a leading thousands separator. For example, inserting
6291 commas every three digits in '123456', with min_width=8, gives
6292 '0,123,456', even though that has length 9.
6293
6294 """
6295
6296 sep = spec['thousands_sep']
6297 grouping = spec['grouping']
6298
6299 groups = []
6300 for l in _group_lengths(grouping):
Mark Dickinson79f52032009-03-17 23:12:51 +00006301 if l <= 0:
6302 raise ValueError("group length should be positive")
6303 # max(..., 1) forces at least 1 digit to the left of a separator
6304 l = min(max(len(digits), min_width, 1), l)
6305 groups.append('0'*(l - len(digits)) + digits[-l:])
6306 digits = digits[:-l]
6307 min_width -= l
6308 if not digits and min_width <= 0:
6309 break
Mark Dickinson7303b592009-03-18 08:25:36 +00006310 min_width -= len(sep)
Mark Dickinson79f52032009-03-17 23:12:51 +00006311 else:
6312 l = max(len(digits), min_width, 1)
6313 groups.append('0'*(l - len(digits)) + digits[-l:])
6314 return sep.join(reversed(groups))
6315
6316def _format_sign(is_negative, spec):
6317 """Determine sign character."""
6318
6319 if is_negative:
6320 return '-'
6321 elif spec['sign'] in ' +':
6322 return spec['sign']
6323 else:
6324 return ''
6325
6326def _format_number(is_negative, intpart, fracpart, exp, spec):
6327 """Format a number, given the following data:
6328
6329 is_negative: true if the number is negative, else false
6330 intpart: string of digits that must appear before the decimal point
6331 fracpart: string of digits that must come after the point
6332 exp: exponent, as an integer
6333 spec: dictionary resulting from parsing the format specifier
6334
6335 This function uses the information in spec to:
6336 insert separators (decimal separator and thousands separators)
6337 format the sign
6338 format the exponent
6339 add trailing '%' for the '%' type
6340 zero-pad if necessary
6341 fill and align if necessary
6342 """
6343
6344 sign = _format_sign(is_negative, spec)
6345
Eric Smith984bb582010-11-25 16:08:06 +00006346 if fracpart or spec['alt']:
Mark Dickinson79f52032009-03-17 23:12:51 +00006347 fracpart = spec['decimal_point'] + fracpart
6348
6349 if exp != 0 or spec['type'] in 'eE':
6350 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
6351 fracpart += "{0}{1:+}".format(echar, exp)
6352 if spec['type'] == '%':
6353 fracpart += '%'
6354
6355 if spec['zeropad']:
6356 min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
6357 else:
6358 min_width = 0
6359 intpart = _insert_thousands_sep(intpart, spec, min_width)
6360
6361 return _format_align(sign, intpart+fracpart, spec)
6362
6363
Guido van Rossumd8faa362007-04-27 19:54:29 +00006364##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006365
Guido van Rossumd8faa362007-04-27 19:54:29 +00006366# Reusable defaults
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006367_Infinity = Decimal('Inf')
6368_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonf9236412009-01-02 23:23:21 +00006369_NaN = Decimal('NaN')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006370_Zero = Decimal(0)
6371_One = Decimal(1)
6372_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006373
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006374# _SignedInfinity[sign] is infinity w/ that sign
6375_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006376
Mark Dickinsondc787d22010-05-23 13:33:13 +00006377# Constants related to the hash implementation; hash(x) is based
6378# on the reduction of x modulo _PyHASH_MODULUS
Mark Dickinsondc787d22010-05-23 13:33:13 +00006379_PyHASH_MODULUS = sys.hash_info.modulus
6380# hash values to use for positive and negative infinities, and nans
6381_PyHASH_INF = sys.hash_info.inf
6382_PyHASH_NAN = sys.hash_info.nan
Mark Dickinsondc787d22010-05-23 13:33:13 +00006383
6384# _PyHASH_10INV is the inverse of 10 modulo the prime _PyHASH_MODULUS
6385_PyHASH_10INV = pow(10, _PyHASH_MODULUS - 2, _PyHASH_MODULUS)
Stefan Krah1919b7e2012-03-21 18:25:23 +01006386del sys
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006387
Stefan Krah1919b7e2012-03-21 18:25:23 +01006388try:
6389 import _decimal
6390except ImportError:
6391 pass
6392else:
6393 s1 = set(dir())
6394 s2 = set(dir(_decimal))
6395 for name in s1 - s2:
6396 del globals()[name]
6397 del s1, s2, name
6398 from _decimal import *
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006399
6400if __name__ == '__main__':
Raymond Hettinger6d7e26e2011-02-01 23:54:43 +00006401 import doctest, decimal
6402 doctest.testmod(decimal)