blob: 9f37e4fa48e2de3af7815abf006d99fce39480db [file] [log] [blame]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001# Copyright (c) 2004 Python Software Foundation.
2# All rights reserved.
3
4# Written by Eric Price <eprice at tjhsst.edu>
5# and Facundo Batista <facundo at taniquetil.com.ar>
6# and Raymond Hettinger <python at rcn.com>
Fred Drake1f34eb12004-07-01 14:28:36 +00007# and Aahz <aahz at pobox.com>
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00008# and Tim Peters
9
Facundo Batista6ab24792009-02-16 15:41:37 +000010# This module should be kept in sync with the latest updates of the
11# IBM specification as it evolves. Those updates will be treated
Raymond Hettinger27dbcf22004-08-19 22:39:55 +000012# as bug fixes (deviation from the spec is a compatibility, usability
13# bug) and will be backported. At this point the spec is stabilizing
14# and the updates are becoming fewer, smaller, and less significant.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000015
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000016"""
Facundo Batista6ab24792009-02-16 15:41:37 +000017This is an implementation of decimal floating point arithmetic based on
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000018the General Decimal Arithmetic Specification:
19
Raymond Hettinger960dc362009-04-21 03:43:15 +000020 http://speleotrove.com/decimal/decarith.html
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000021
Raymond Hettinger0ea241e2004-07-04 13:53:24 +000022and IEEE standard 854-1987:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000023
Senthil Kumaran4fec47e2013-09-07 23:19:29 -070024 http://en.wikipedia.org/wiki/IEEE_854-1987
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000025
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000026Decimal floating point has finite precision with arbitrarily large bounds.
27
Guido van Rossumd8faa362007-04-27 19:54:29 +000028The purpose of this module is to support arithmetic using familiar
29"schoolhouse" rules and to avoid some of the tricky representation
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000030issues associated with binary floating point. The package is especially
31useful for financial applications or for contexts where users have
32expectations that are at odds with binary floating point (for instance,
33in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
Mark Dickinsonaa63c4d2010-06-12 16:37:53 +000034of 0.0; Decimal('1.00') % Decimal('0.1') returns the expected
35Decimal('0.00')).
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000036
37Here are some examples of using the decimal module:
38
39>>> from decimal import *
Raymond Hettingerbd7f76d2004-07-08 00:49:18 +000040>>> setcontext(ExtendedContext)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000041>>> Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000042Decimal('0')
43>>> Decimal('1')
44Decimal('1')
45>>> Decimal('-.0123')
46Decimal('-0.0123')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000047>>> Decimal(123456)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000048Decimal('123456')
Stefan Krah1919b7e2012-03-21 18:25:23 +010049>>> Decimal('123.45e12345678')
50Decimal('1.2345E+12345680')
Christian Heimes68f5fbe2008-02-14 08:27:37 +000051>>> Decimal('1.33') + Decimal('1.27')
52Decimal('2.60')
53>>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
54Decimal('-2.20')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000055>>> dig = Decimal(1)
Guido van Rossum7131f842007-02-09 20:13:25 +000056>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000570.333333333
58>>> getcontext().prec = 18
Guido van Rossum7131f842007-02-09 20:13:25 +000059>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000600.333333333333333333
Guido van Rossum7131f842007-02-09 20:13:25 +000061>>> print(dig.sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000621
Guido van Rossum7131f842007-02-09 20:13:25 +000063>>> print(Decimal(3).sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000641.73205080756887729
Guido van Rossum7131f842007-02-09 20:13:25 +000065>>> print(Decimal(3) ** 123)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000664.85192780976896427E+58
67>>> inf = Decimal(1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000068>>> print(inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000069Infinity
70>>> neginf = Decimal(-1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000071>>> print(neginf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000072-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000073>>> print(neginf + inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000074NaN
Guido van Rossum7131f842007-02-09 20:13:25 +000075>>> print(neginf * inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000076-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000077>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000078Infinity
Raymond Hettingerbf440692004-07-10 14:14:37 +000079>>> getcontext().traps[DivisionByZero] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000080>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000081Traceback (most recent call last):
82 ...
83 ...
84 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +000085decimal.DivisionByZero: x / 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000086>>> c = Context()
Raymond Hettingerbf440692004-07-10 14:14:37 +000087>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000088>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000890
90>>> c.divide(Decimal(0), Decimal(0))
Christian Heimes68f5fbe2008-02-14 08:27:37 +000091Decimal('NaN')
Raymond Hettingerbf440692004-07-10 14:14:37 +000092>>> c.traps[InvalidOperation] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000093>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000941
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000095>>> c.flags[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000096>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000970
Guido van Rossum7131f842007-02-09 20:13:25 +000098>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000099Traceback (most recent call last):
100 ...
101 ...
102 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +0000103decimal.InvalidOperation: 0 / 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000104>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001051
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000106>>> c.flags[InvalidOperation] = 0
Raymond Hettingerbf440692004-07-10 14:14:37 +0000107>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000108>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000109NaN
Guido van Rossum7131f842007-02-09 20:13:25 +0000110>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001111
112>>>
113"""
114
115__all__ = [
116 # Two major classes
117 'Decimal', 'Context',
118
119 # Contexts
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +0000120 'DefaultContext', 'BasicContext', 'ExtendedContext',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000121
122 # Exceptions
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +0000123 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
124 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
Stefan Krah1919b7e2012-03-21 18:25:23 +0100125 'FloatOperation',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000126
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000127 # Constants for use in setting up contexts
128 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000129 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000130
131 # Functions for manipulating contexts
Stefan Krah1919b7e2012-03-21 18:25:23 +0100132 'setcontext', 'getcontext', 'localcontext',
133
134 # Limits for the C version for compatibility
135 'MAX_PREC', 'MAX_EMAX', 'MIN_EMIN', 'MIN_ETINY',
136
137 # C version: compile time choice that enables the thread local context
138 'HAVE_THREADS'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000139]
140
Raymond Hettinger960dc362009-04-21 03:43:15 +0000141__version__ = '1.70' # Highest version of the spec this complies with
Raymond Hettinger697ce952010-11-30 20:32:59 +0000142 # See http://speleotrove.com/decimal/
Stefan Krah45059eb2013-11-24 19:44:57 +0100143__libmpdec_version__ = "2.4.0" # compatible libmpdec version
Raymond Hettinger960dc362009-04-21 03:43:15 +0000144
Raymond Hettingereb260842005-06-07 18:52:34 +0000145import copy as _copy
Raymond Hettinger771ed762009-01-03 19:20:32 +0000146import math as _math
Raymond Hettinger82417ca2009-02-03 03:54:28 +0000147import numbers as _numbers
Stefan Krah1919b7e2012-03-21 18:25:23 +0100148import sys
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000149
Christian Heimes25bb7832008-01-11 16:17:00 +0000150try:
151 from collections import namedtuple as _namedtuple
152 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
153except ImportError:
154 DecimalTuple = lambda *args: args
155
Guido van Rossumd8faa362007-04-27 19:54:29 +0000156# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000157ROUND_DOWN = 'ROUND_DOWN'
158ROUND_HALF_UP = 'ROUND_HALF_UP'
159ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
160ROUND_CEILING = 'ROUND_CEILING'
161ROUND_FLOOR = 'ROUND_FLOOR'
162ROUND_UP = 'ROUND_UP'
163ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000164ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000165
Stefan Krah1919b7e2012-03-21 18:25:23 +0100166# Compatibility with the C version
167HAVE_THREADS = True
168if sys.maxsize == 2**63-1:
169 MAX_PREC = 999999999999999999
170 MAX_EMAX = 999999999999999999
171 MIN_EMIN = -999999999999999999
172else:
173 MAX_PREC = 425000000
174 MAX_EMAX = 425000000
175 MIN_EMIN = -425000000
176
177MIN_ETINY = MIN_EMIN - (MAX_PREC-1)
178
Guido van Rossumd8faa362007-04-27 19:54:29 +0000179# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000180
181class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000182 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000183
184 Used exceptions derive from this.
185 If an exception derives from another exception besides this (such as
186 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
187 called if the others are present. This isn't actually used for
188 anything, though.
189
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000190 handle -- Called when context._raise_error is called and the
Stefan Krah2eb4a072010-05-19 15:52:31 +0000191 trap_enabler is not set. First argument is self, second is the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000192 context. More arguments can be given, those being after
193 the explanation in _raise_error (For example,
194 context._raise_error(NewError, '(-x)!', self._sign) would
195 call NewError().handle(context, self._sign).)
196
197 To define a new exception, it should be sufficient to have it derive
198 from DecimalException.
199 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000200 def handle(self, context, *args):
201 pass
202
203
204class Clamped(DecimalException):
205 """Exponent of a 0 changed to fit bounds.
206
207 This occurs and signals clamped if the exponent of a result has been
208 altered in order to fit the constraints of a specific concrete
Guido van Rossumd8faa362007-04-27 19:54:29 +0000209 representation. This may occur when the exponent of a zero result would
210 be outside the bounds of a representation, or when a large normal
211 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000212 this latter case, the exponent is reduced to fit and the corresponding
213 number of zero digits are appended to the coefficient ("fold-down").
214 """
215
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000216class InvalidOperation(DecimalException):
217 """An invalid operation was performed.
218
219 Various bad things cause this:
220
221 Something creates a signaling NaN
222 -INF + INF
Guido van Rossumd8faa362007-04-27 19:54:29 +0000223 0 * (+-)INF
224 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000225 x % 0
226 (+-)INF % x
227 x._rescale( non-integer )
228 sqrt(-x) , x > 0
229 0 ** 0
230 x ** (non-integer)
231 x ** (+-)INF
232 An operand is invalid
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000233
234 The result of the operation after these is a quiet positive NaN,
235 except when the cause is a signaling NaN, in which case the result is
236 also a quiet NaN, but with the original sign, and an optional
237 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000238 """
239 def handle(self, context, *args):
240 if args:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000241 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
242 return ans._fix_nan(context)
Mark Dickinsonf9236412009-01-02 23:23:21 +0000243 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000244
245class ConversionSyntax(InvalidOperation):
246 """Trying to convert badly formed string.
247
248 This occurs and signals invalid-operation if an string is being
249 converted to a number and it does not conform to the numeric string
Guido van Rossumd8faa362007-04-27 19:54:29 +0000250 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000251 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000252 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000253 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000254
255class DivisionByZero(DecimalException, ZeroDivisionError):
256 """Division by 0.
257
258 This occurs and signals division-by-zero if division of a finite number
259 by zero was attempted (during a divide-integer or divide operation, or a
260 power operation with negative right-hand operand), and the dividend was
261 not zero.
262
263 The result of the operation is [sign,inf], where sign is the exclusive
264 or of the signs of the operands for divide, or is 1 for an odd power of
265 -0, for power.
266 """
267
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000268 def handle(self, context, sign, *args):
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000269 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000270
271class DivisionImpossible(InvalidOperation):
272 """Cannot perform the division adequately.
273
274 This occurs and signals invalid-operation if the integer result of a
275 divide-integer or remainder operation had too many digits (would be
Guido van Rossumd8faa362007-04-27 19:54:29 +0000276 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000277 """
278
279 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000280 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000281
282class DivisionUndefined(InvalidOperation, ZeroDivisionError):
283 """Undefined result of division.
284
285 This occurs and signals invalid-operation if division by zero was
286 attempted (during a divide-integer, divide, or remainder operation), and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000287 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000288 """
289
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000290 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000291 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000292
293class Inexact(DecimalException):
294 """Had to round, losing information.
295
296 This occurs and signals inexact whenever the result of an operation is
297 not exact (that is, it needed to be rounded and any discarded digits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000298 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000299 result in all cases is unchanged.
300
301 The inexact signal may be tested (or trapped) to determine if a given
302 operation (or sequence of operations) was inexact.
303 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000304
305class InvalidContext(InvalidOperation):
306 """Invalid context. Unknown rounding, for example.
307
308 This occurs and signals invalid-operation if an invalid context was
Guido van Rossumd8faa362007-04-27 19:54:29 +0000309 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000310 on creation and either the precision exceeds the capability of the
311 underlying concrete representation or an unknown or unsupported rounding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000312 was specified. These aspects of the context need only be checked when
313 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000314 """
315
316 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000317 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000318
319class Rounded(DecimalException):
320 """Number got rounded (not necessarily changed during rounding).
321
322 This occurs and signals rounded whenever the result of an operation is
323 rounded (that is, some zero or non-zero digits were discarded from the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000324 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000325 result in all cases is unchanged.
326
327 The rounded signal may be tested (or trapped) to determine if a given
328 operation (or sequence of operations) caused a loss of precision.
329 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000330
331class Subnormal(DecimalException):
332 """Exponent < Emin before rounding.
333
334 This occurs and signals subnormal whenever the result of a conversion or
335 operation is subnormal (that is, its adjusted exponent is less than
Guido van Rossumd8faa362007-04-27 19:54:29 +0000336 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337
338 The subnormal signal may be tested (or trapped) to determine if a given
339 or operation (or sequence of operations) yielded a subnormal result.
340 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000341
342class Overflow(Inexact, Rounded):
343 """Numerical overflow.
344
345 This occurs and signals overflow if the adjusted exponent of a result
346 (from a conversion or from an operation that is not an attempt to divide
347 by zero), after rounding, would be greater than the largest value that
348 can be handled by the implementation (the value Emax).
349
350 The result depends on the rounding mode:
351
352 For round-half-up and round-half-even (and for round-half-down and
353 round-up, if implemented), the result of the operation is [sign,inf],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000354 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000355 result is the largest finite number that can be represented in the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000356 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000357 round-ceiling, the result is the same as for round-down if the sign of
Guido van Rossumd8faa362007-04-27 19:54:29 +0000358 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000359 the result is the same as for round-down if the sign of the intermediate
Guido van Rossumd8faa362007-04-27 19:54:29 +0000360 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000361 will also be raised.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000362 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000363
364 def handle(self, context, sign, *args):
365 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000366 ROUND_HALF_DOWN, ROUND_UP):
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000367 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000368 if sign == 0:
369 if context.rounding == ROUND_CEILING:
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000370 return _SignedInfinity[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000371 return _dec_from_triple(sign, '9'*context.prec,
372 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000373 if sign == 1:
374 if context.rounding == ROUND_FLOOR:
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000375 return _SignedInfinity[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000376 return _dec_from_triple(sign, '9'*context.prec,
377 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000378
379
380class Underflow(Inexact, Rounded, Subnormal):
381 """Numerical underflow with result rounded to 0.
382
383 This occurs and signals underflow if a result is inexact and the
384 adjusted exponent of the result would be smaller (more negative) than
385 the smallest value that can be handled by the implementation (the value
Guido van Rossumd8faa362007-04-27 19:54:29 +0000386 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000387
388 The result after an underflow will be a subnormal number rounded, if
Guido van Rossumd8faa362007-04-27 19:54:29 +0000389 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000390 in 0 with the sign of the intermediate result and an exponent of Etiny.
391
392 In all cases, Inexact, Rounded, and Subnormal will also be raised.
393 """
394
Stefan Krahb6405ef2012-03-23 14:46:48 +0100395class FloatOperation(DecimalException, TypeError):
Stefan Krah1919b7e2012-03-21 18:25:23 +0100396 """Enable stricter semantics for mixing floats and Decimals.
397
398 If the signal is not trapped (default), mixing floats and Decimals is
399 permitted in the Decimal() constructor, context.create_decimal() and
400 all comparison operators. Both conversion and comparisons are exact.
401 Any occurrence of a mixed operation is silently recorded by setting
402 FloatOperation in the context flags. Explicit conversions with
403 Decimal.from_float() or context.create_decimal_from_float() do not
404 set the flag.
405
406 Otherwise (the signal is trapped), only equality comparisons and explicit
407 conversions are silent. All other mixed operations raise FloatOperation.
408 """
409
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000410# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000411_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Stefan Krah1919b7e2012-03-21 18:25:23 +0100412 Underflow, InvalidOperation, Subnormal, FloatOperation]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000413
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000414# Map conditions (per the spec) to signals
415_condition_map = {ConversionSyntax:InvalidOperation,
416 DivisionImpossible:InvalidOperation,
417 DivisionUndefined:InvalidOperation,
418 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000419
Stefan Krah1919b7e2012-03-21 18:25:23 +0100420# Valid rounding modes
421_rounding_modes = (ROUND_DOWN, ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_CEILING,
422 ROUND_FLOOR, ROUND_UP, ROUND_HALF_DOWN, ROUND_05UP)
423
Guido van Rossumd8faa362007-04-27 19:54:29 +0000424##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000425
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000426# The getcontext() and setcontext() function manage access to a thread-local
427# current context. Py2.4 offers direct support for thread locals. If that
Georg Brandlf9926402008-06-13 06:32:25 +0000428# is not available, use threading.current_thread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000429# work for older Pythons. If threads are not part of the build, create a
430# mock threading object with threading.local() returning the module namespace.
431
432try:
433 import threading
434except ImportError:
435 # Python was compiled without threads; create a mock object instead
Guido van Rossumd8faa362007-04-27 19:54:29 +0000436 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000437 def local(self, sys=sys):
438 return sys.modules[__name__]
439 threading = MockThreading()
Stefan Krah1919b7e2012-03-21 18:25:23 +0100440 del MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000441
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000442try:
443 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000444
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000445except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000446
Guido van Rossumd8faa362007-04-27 19:54:29 +0000447 # To fix reloading, force it to create a new context
448 # Old contexts have different exceptions in their dicts, making problems.
Georg Brandlf9926402008-06-13 06:32:25 +0000449 if hasattr(threading.current_thread(), '__decimal_context__'):
450 del threading.current_thread().__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000451
452 def setcontext(context):
453 """Set this thread's context to context."""
454 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000455 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000456 context.clear_flags()
Georg Brandlf9926402008-06-13 06:32:25 +0000457 threading.current_thread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000458
459 def getcontext():
460 """Returns this thread's context.
461
462 If this thread does not yet have a context, returns
463 a new context and sets this thread's context.
464 New contexts are copies of DefaultContext.
465 """
466 try:
Georg Brandlf9926402008-06-13 06:32:25 +0000467 return threading.current_thread().__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000468 except AttributeError:
469 context = Context()
Georg Brandlf9926402008-06-13 06:32:25 +0000470 threading.current_thread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000471 return context
472
473else:
474
475 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000476 if hasattr(local, '__decimal_context__'):
477 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000478
479 def getcontext(_local=local):
480 """Returns this thread's context.
481
482 If this thread does not yet have a context, returns
483 a new context and sets this thread's context.
484 New contexts are copies of DefaultContext.
485 """
486 try:
487 return _local.__decimal_context__
488 except AttributeError:
489 context = Context()
490 _local.__decimal_context__ = context
491 return context
492
493 def setcontext(context, _local=local):
494 """Set this thread's context to context."""
495 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000496 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000497 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000498 _local.__decimal_context__ = context
499
500 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000501
Thomas Wouters89f507f2006-12-13 04:49:30 +0000502def localcontext(ctx=None):
503 """Return a context manager for a copy of the supplied context
504
505 Uses a copy of the current context if no context is specified
506 The returned context manager creates a local decimal context
507 in a with statement:
508 def sin(x):
509 with localcontext() as ctx:
510 ctx.prec += 2
511 # Rest of sin calculation algorithm
512 # uses a precision 2 greater than normal
Guido van Rossumd8faa362007-04-27 19:54:29 +0000513 return +s # Convert result to normal precision
Thomas Wouters89f507f2006-12-13 04:49:30 +0000514
515 def sin(x):
516 with localcontext(ExtendedContext):
517 # Rest of sin calculation algorithm
518 # uses the Extended Context from the
519 # General Decimal Arithmetic Specification
Guido van Rossumd8faa362007-04-27 19:54:29 +0000520 return +s # Convert result to normal context
Thomas Wouters89f507f2006-12-13 04:49:30 +0000521
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000522 >>> setcontext(DefaultContext)
Guido van Rossum7131f842007-02-09 20:13:25 +0000523 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000524 28
525 >>> with localcontext():
526 ... ctx = getcontext()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000527 ... ctx.prec += 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000528 ... print(ctx.prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000529 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000530 30
531 >>> with localcontext(ExtendedContext):
Guido van Rossum7131f842007-02-09 20:13:25 +0000532 ... print(getcontext().prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000533 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000534 9
Guido van Rossum7131f842007-02-09 20:13:25 +0000535 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000536 28
537 """
538 if ctx is None: ctx = getcontext()
539 return _ContextManager(ctx)
540
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000541
Guido van Rossumd8faa362007-04-27 19:54:29 +0000542##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000543
Raymond Hettingera0fd8882009-01-20 07:24:44 +0000544# Do not subclass Decimal from numbers.Real and do not register it as such
545# (because Decimals are not interoperable with floats). See the notes in
546# numbers.py for more detail.
547
548class Decimal(object):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000549 """Floating point class for decimal arithmetic."""
550
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000551 __slots__ = ('_exp','_int','_sign', '_is_special')
552 # Generally, the value of the Decimal instance is given by
553 # (-1)**_sign * _int * 10**_exp
554 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000555
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000556 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000557 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000558 """Create a decimal point instance.
559
560 >>> Decimal('3.14') # string input
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000561 Decimal('3.14')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000562 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000563 Decimal('3.14')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000564 >>> Decimal(314) # int
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000565 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000566 >>> Decimal(Decimal(314)) # another decimal instance
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000567 Decimal('314')
Christian Heimesa62da1d2008-01-12 19:39:10 +0000568 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000569 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000570 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000571
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000572 # Note that the coefficient, self._int, is actually stored as
573 # a string rather than as a tuple of digits. This speeds up
574 # the "digits to integer" and "integer to digits" conversions
575 # that are used in almost every arithmetic operation on
576 # Decimals. This is an internal detail: the as_tuple function
577 # and the Decimal constructor still deal with tuples of
578 # digits.
579
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000580 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000581
Christian Heimesd59c64c2007-11-30 19:27:20 +0000582 # From a string
583 # REs insist on real strings, so we can too.
584 if isinstance(value, str):
Christian Heimesa62da1d2008-01-12 19:39:10 +0000585 m = _parser(value.strip())
Christian Heimesd59c64c2007-11-30 19:27:20 +0000586 if m is None:
587 if context is None:
588 context = getcontext()
589 return context._raise_error(ConversionSyntax,
590 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000591
Christian Heimesd59c64c2007-11-30 19:27:20 +0000592 if m.group('sign') == "-":
593 self._sign = 1
594 else:
595 self._sign = 0
596 intpart = m.group('int')
597 if intpart is not None:
598 # finite number
Mark Dickinson345adc42009-08-02 10:14:23 +0000599 fracpart = m.group('frac') or ''
Christian Heimesd59c64c2007-11-30 19:27:20 +0000600 exp = int(m.group('exp') or '0')
Mark Dickinson345adc42009-08-02 10:14:23 +0000601 self._int = str(int(intpart+fracpart))
602 self._exp = exp - len(fracpart)
Christian Heimesd59c64c2007-11-30 19:27:20 +0000603 self._is_special = False
604 else:
605 diag = m.group('diag')
606 if diag is not None:
607 # NaN
Mark Dickinson345adc42009-08-02 10:14:23 +0000608 self._int = str(int(diag or '0')).lstrip('0')
Christian Heimesd59c64c2007-11-30 19:27:20 +0000609 if m.group('signal'):
610 self._exp = 'N'
611 else:
612 self._exp = 'n'
613 else:
614 # infinity
615 self._int = '0'
616 self._exp = 'F'
617 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000618 return self
619
620 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000621 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000622 if value >= 0:
623 self._sign = 0
624 else:
625 self._sign = 1
626 self._exp = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000627 self._int = str(abs(value))
Christian Heimesd59c64c2007-11-30 19:27:20 +0000628 self._is_special = False
629 return self
630
631 # From another decimal
632 if isinstance(value, Decimal):
633 self._exp = value._exp
634 self._sign = value._sign
635 self._int = value._int
636 self._is_special = value._is_special
637 return self
638
639 # From an internal working value
640 if isinstance(value, _WorkRep):
641 self._sign = value.sign
642 self._int = str(value.int)
643 self._exp = int(value.exp)
644 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000645 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000646
647 # tuple/list conversion (possibly from as_tuple())
648 if isinstance(value, (list,tuple)):
649 if len(value) != 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000650 raise ValueError('Invalid tuple size in creation of Decimal '
651 'from list or tuple. The list or tuple '
652 'should have exactly three elements.')
653 # process sign. The isinstance test rejects floats
654 if not (isinstance(value[0], int) and value[0] in (0,1)):
655 raise ValueError("Invalid sign. The first value in the tuple "
656 "should be an integer; either 0 for a "
657 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000658 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000659 if value[2] == 'F':
660 # infinity: value[1] is ignored
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000661 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000662 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000663 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000664 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000665 # process and validate the digits in value[1]
666 digits = []
667 for digit in value[1]:
668 if isinstance(digit, int) and 0 <= digit <= 9:
669 # skip leading zeros
670 if digits or digit != 0:
671 digits.append(digit)
672 else:
673 raise ValueError("The second value in the tuple must "
674 "be composed of integers in the range "
675 "0 through 9.")
676 if value[2] in ('n', 'N'):
677 # NaN: digits form the diagnostic
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000678 self._int = ''.join(map(str, digits))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000679 self._exp = value[2]
680 self._is_special = True
681 elif isinstance(value[2], int):
682 # finite number: digits give the coefficient
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000683 self._int = ''.join(map(str, digits or [0]))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000684 self._exp = value[2]
685 self._is_special = False
686 else:
687 raise ValueError("The third value in the tuple must "
688 "be an integer, or one of the "
689 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000690 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000691
Raymond Hettingerbf440692004-07-10 14:14:37 +0000692 if isinstance(value, float):
Stefan Krah1919b7e2012-03-21 18:25:23 +0100693 if context is None:
694 context = getcontext()
695 context._raise_error(FloatOperation,
696 "strict semantics for mixing floats and Decimals are "
697 "enabled")
Raymond Hettinger96798592010-04-02 16:58:27 +0000698 value = Decimal.from_float(value)
699 self._exp = value._exp
700 self._sign = value._sign
701 self._int = value._int
702 self._is_special = value._is_special
703 return self
Raymond Hettingerbf440692004-07-10 14:14:37 +0000704
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000705 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000706
Mark Dickinsonba298e42009-01-04 21:17:43 +0000707 # @classmethod, but @decorator is not valid Python 2.3 syntax, so
708 # don't use it (see notes on Py2.3 compatibility at top of file)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000709 def from_float(cls, f):
710 """Converts a float to a decimal number, exactly.
711
712 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
713 Since 0.1 is not exactly representable in binary floating point, the
714 value is stored as the nearest representable value which is
715 0x1.999999999999ap-4. The exact equivalent of the value in decimal
716 is 0.1000000000000000055511151231257827021181583404541015625.
717
718 >>> Decimal.from_float(0.1)
719 Decimal('0.1000000000000000055511151231257827021181583404541015625')
720 >>> Decimal.from_float(float('nan'))
721 Decimal('NaN')
722 >>> Decimal.from_float(float('inf'))
723 Decimal('Infinity')
724 >>> Decimal.from_float(-float('inf'))
725 Decimal('-Infinity')
726 >>> Decimal.from_float(-0.0)
727 Decimal('-0')
728
729 """
730 if isinstance(f, int): # handle integer inputs
731 return cls(f)
Stefan Krah1919b7e2012-03-21 18:25:23 +0100732 if not isinstance(f, float):
733 raise TypeError("argument must be int or float.")
734 if _math.isinf(f) or _math.isnan(f):
Raymond Hettinger771ed762009-01-03 19:20:32 +0000735 return cls(repr(f))
Mark Dickinsonba298e42009-01-04 21:17:43 +0000736 if _math.copysign(1.0, f) == 1.0:
737 sign = 0
738 else:
739 sign = 1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000740 n, d = abs(f).as_integer_ratio()
741 k = d.bit_length() - 1
742 result = _dec_from_triple(sign, str(n*5**k), -k)
Mark Dickinsonba298e42009-01-04 21:17:43 +0000743 if cls is Decimal:
744 return result
745 else:
746 return cls(result)
747 from_float = classmethod(from_float)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000748
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000749 def _isnan(self):
750 """Returns whether the number is not actually one.
751
752 0 if a number
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000753 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000754 2 if sNaN
755 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000756 if self._is_special:
757 exp = self._exp
758 if exp == 'n':
759 return 1
760 elif exp == 'N':
761 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000762 return 0
763
764 def _isinfinity(self):
765 """Returns whether the number is infinite
766
767 0 if finite or not a number
768 1 if +INF
769 -1 if -INF
770 """
771 if self._exp == 'F':
772 if self._sign:
773 return -1
774 return 1
775 return 0
776
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000777 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000778 """Returns whether the number is not actually one.
779
780 if self, other are sNaN, signal
781 if self, other are NaN return nan
782 return 0
783
784 Done before operations.
785 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000786
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000787 self_is_nan = self._isnan()
788 if other is None:
789 other_is_nan = False
790 else:
791 other_is_nan = other._isnan()
792
793 if self_is_nan or other_is_nan:
794 if context is None:
795 context = getcontext()
796
797 if self_is_nan == 2:
798 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000799 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000800 if other_is_nan == 2:
801 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000802 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000803 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000804 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000805
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000806 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000807 return 0
808
Christian Heimes77c02eb2008-02-09 02:18:51 +0000809 def _compare_check_nans(self, other, context):
810 """Version of _check_nans used for the signaling comparisons
811 compare_signal, __le__, __lt__, __ge__, __gt__.
812
813 Signal InvalidOperation if either self or other is a (quiet
814 or signaling) NaN. Signaling NaNs take precedence over quiet
815 NaNs.
816
817 Return 0 if neither operand is a NaN.
818
819 """
820 if context is None:
821 context = getcontext()
822
823 if self._is_special or other._is_special:
824 if self.is_snan():
825 return context._raise_error(InvalidOperation,
826 'comparison involving sNaN',
827 self)
828 elif other.is_snan():
829 return context._raise_error(InvalidOperation,
830 'comparison involving sNaN',
831 other)
832 elif self.is_qnan():
833 return context._raise_error(InvalidOperation,
834 'comparison involving NaN',
835 self)
836 elif other.is_qnan():
837 return context._raise_error(InvalidOperation,
838 'comparison involving NaN',
839 other)
840 return 0
841
Jack Diederich4dafcc42006-11-28 19:15:13 +0000842 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000843 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000844
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000845 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000846 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000847 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000848
Christian Heimes77c02eb2008-02-09 02:18:51 +0000849 def _cmp(self, other):
850 """Compare the two non-NaN decimal instances self and other.
851
852 Returns -1 if self < other, 0 if self == other and 1
853 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000854
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000855 if self._is_special or other._is_special:
Mark Dickinsone6aad752009-01-25 10:48:51 +0000856 self_inf = self._isinfinity()
857 other_inf = other._isinfinity()
858 if self_inf == other_inf:
859 return 0
860 elif self_inf < other_inf:
861 return -1
862 else:
863 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000864
Mark Dickinsone6aad752009-01-25 10:48:51 +0000865 # check for zeros; Decimal('0') == Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000866 if not self:
867 if not other:
868 return 0
869 else:
870 return -((-1)**other._sign)
871 if not other:
872 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000873
Guido van Rossumd8faa362007-04-27 19:54:29 +0000874 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000875 if other._sign < self._sign:
876 return -1
877 if self._sign < other._sign:
878 return 1
879
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000880 self_adjusted = self.adjusted()
881 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000882 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000883 self_padded = self._int + '0'*(self._exp - other._exp)
884 other_padded = other._int + '0'*(other._exp - self._exp)
Mark Dickinsone6aad752009-01-25 10:48:51 +0000885 if self_padded == other_padded:
886 return 0
887 elif self_padded < other_padded:
888 return -(-1)**self._sign
889 else:
890 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000891 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000892 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000893 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000894 return -((-1)**self._sign)
895
Christian Heimes77c02eb2008-02-09 02:18:51 +0000896 # Note: The Decimal standard doesn't cover rich comparisons for
897 # Decimals. In particular, the specification is silent on the
898 # subject of what should happen for a comparison involving a NaN.
899 # We take the following approach:
900 #
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000901 # == comparisons involving a quiet NaN always return False
902 # != comparisons involving a quiet NaN always return True
903 # == or != comparisons involving a signaling NaN signal
904 # InvalidOperation, and return False or True as above if the
905 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000906 # <, >, <= and >= comparisons involving a (quiet or signaling)
907 # NaN signal InvalidOperation, and return False if the
Christian Heimes3feef612008-02-11 06:19:17 +0000908 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000909 #
910 # This behavior is designed to conform as closely as possible to
911 # that specified by IEEE 754.
912
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000913 def __eq__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000914 self, other = _convert_for_comparison(self, other, equality_op=True)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000915 if other is NotImplemented:
916 return other
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000917 if self._check_nans(other, context):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000918 return False
919 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000920
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000921 def __ne__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000922 self, other = _convert_for_comparison(self, other, equality_op=True)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000923 if other is NotImplemented:
924 return other
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000925 if self._check_nans(other, context):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000926 return True
927 return self._cmp(other) != 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000928
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000929
Christian Heimes77c02eb2008-02-09 02:18:51 +0000930 def __lt__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000931 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000932 if other is NotImplemented:
933 return other
934 ans = self._compare_check_nans(other, context)
935 if ans:
936 return False
937 return self._cmp(other) < 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000938
Christian Heimes77c02eb2008-02-09 02:18:51 +0000939 def __le__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000940 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000941 if other is NotImplemented:
942 return other
943 ans = self._compare_check_nans(other, context)
944 if ans:
945 return False
946 return self._cmp(other) <= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000947
Christian Heimes77c02eb2008-02-09 02:18:51 +0000948 def __gt__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000949 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000950 if other is NotImplemented:
951 return other
952 ans = self._compare_check_nans(other, context)
953 if ans:
954 return False
955 return self._cmp(other) > 0
956
957 def __ge__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000958 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000959 if other is NotImplemented:
960 return other
961 ans = self._compare_check_nans(other, context)
962 if ans:
963 return False
964 return self._cmp(other) >= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000965
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000966 def compare(self, other, context=None):
967 """Compares one to another.
968
969 -1 => a < b
970 0 => a = b
971 1 => a > b
972 NaN => one is NaN
973 Like __cmp__, but returns Decimal instances.
974 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000975 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000976
Guido van Rossumd8faa362007-04-27 19:54:29 +0000977 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000978 if (self._is_special or other and other._is_special):
979 ans = self._check_nans(other, context)
980 if ans:
981 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000982
Christian Heimes77c02eb2008-02-09 02:18:51 +0000983 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000984
985 def __hash__(self):
986 """x.__hash__() <==> hash(x)"""
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000987
Mark Dickinsondc787d22010-05-23 13:33:13 +0000988 # In order to make sure that the hash of a Decimal instance
989 # agrees with the hash of a numerically equal integer, float
990 # or Fraction, we follow the rules for numeric hashes outlined
991 # in the documentation. (See library docs, 'Built-in Types').
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000992 if self._is_special:
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000993 if self.is_snan():
Raymond Hettingerd325c4b2010-11-21 04:08:28 +0000994 raise TypeError('Cannot hash a signaling NaN value.')
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000995 elif self.is_nan():
Mark Dickinsondc787d22010-05-23 13:33:13 +0000996 return _PyHASH_NAN
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000997 else:
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000998 if self._sign:
Mark Dickinsondc787d22010-05-23 13:33:13 +0000999 return -_PyHASH_INF
Mark Dickinsonac256ab2010-04-03 11:08:14 +00001000 else:
Mark Dickinsondc787d22010-05-23 13:33:13 +00001001 return _PyHASH_INF
Mark Dickinsonac256ab2010-04-03 11:08:14 +00001002
Mark Dickinsondc787d22010-05-23 13:33:13 +00001003 if self._exp >= 0:
1004 exp_hash = pow(10, self._exp, _PyHASH_MODULUS)
1005 else:
1006 exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS)
1007 hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS
Stefan Krahdc817b22010-11-17 11:16:34 +00001008 ans = hash_ if self >= 0 else -hash_
1009 return -2 if ans == -1 else ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001010
1011 def as_tuple(self):
1012 """Represents the number as a triple tuple.
1013
1014 To show the internals exactly as they are.
1015 """
Christian Heimes25bb7832008-01-11 16:17:00 +00001016 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001017
1018 def __repr__(self):
1019 """Represents the number as an instance of Decimal."""
1020 # Invariant: eval(repr(d)) == d
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001021 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001022
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001023 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001024 """Return string representation of the number in scientific notation.
1025
1026 Captures all of the information in the underlying representation.
1027 """
1028
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001029 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +00001030 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001031 if self._exp == 'F':
1032 return sign + 'Infinity'
1033 elif self._exp == 'n':
1034 return sign + 'NaN' + self._int
1035 else: # self._exp == 'N'
1036 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001037
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001038 # number of digits of self._int to left of decimal point
1039 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001040
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001041 # dotplace is number of digits of self._int to the left of the
1042 # decimal point in the mantissa of the output string (that is,
1043 # after adjusting the exponent)
1044 if self._exp <= 0 and leftdigits > -6:
1045 # no exponent required
1046 dotplace = leftdigits
1047 elif not eng:
1048 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001049 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001050 elif self._int == '0':
1051 # engineering notation, zero
1052 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001053 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001054 # engineering notation, nonzero
1055 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001056
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001057 if dotplace <= 0:
1058 intpart = '0'
1059 fracpart = '.' + '0'*(-dotplace) + self._int
1060 elif dotplace >= len(self._int):
1061 intpart = self._int+'0'*(dotplace-len(self._int))
1062 fracpart = ''
1063 else:
1064 intpart = self._int[:dotplace]
1065 fracpart = '.' + self._int[dotplace:]
1066 if leftdigits == dotplace:
1067 exp = ''
1068 else:
1069 if context is None:
1070 context = getcontext()
1071 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1072
1073 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001074
1075 def to_eng_string(self, context=None):
1076 """Convert to engineering-type string.
1077
1078 Engineering notation has an exponent which is a multiple of 3, so there
1079 are up to 3 digits left of the decimal place.
1080
1081 Same rules for when in exponential and when as a value as in __str__.
1082 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001083 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001084
1085 def __neg__(self, context=None):
1086 """Returns a copy with the sign switched.
1087
1088 Rounds, if it has reason.
1089 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001090 if self._is_special:
1091 ans = self._check_nans(context=context)
1092 if ans:
1093 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001094
Mark Dickinson37a79fb2011-03-12 11:12:52 +00001095 if context is None:
1096 context = getcontext()
1097
1098 if not self and context.rounding != ROUND_FLOOR:
1099 # -Decimal('0') is Decimal('0'), not Decimal('-0'), except
1100 # in ROUND_FLOOR rounding mode.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001101 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001102 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001103 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001104
Christian Heimes2c181612007-12-17 20:04:13 +00001105 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001106
1107 def __pos__(self, context=None):
1108 """Returns a copy, unless it is a sNaN.
1109
1110 Rounds the number (if more then precision digits)
1111 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001112 if self._is_special:
1113 ans = self._check_nans(context=context)
1114 if ans:
1115 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001116
Mark Dickinson37a79fb2011-03-12 11:12:52 +00001117 if context is None:
1118 context = getcontext()
1119
1120 if not self and context.rounding != ROUND_FLOOR:
1121 # + (-0) = 0, except in ROUND_FLOOR rounding mode.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001122 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001123 else:
1124 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001125
Christian Heimes2c181612007-12-17 20:04:13 +00001126 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001127
Christian Heimes2c181612007-12-17 20:04:13 +00001128 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001129 """Returns the absolute value of self.
1130
Christian Heimes2c181612007-12-17 20:04:13 +00001131 If the keyword argument 'round' is false, do not round. The
1132 expression self.__abs__(round=False) is equivalent to
1133 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001134 """
Christian Heimes2c181612007-12-17 20:04:13 +00001135 if not round:
1136 return self.copy_abs()
1137
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001138 if self._is_special:
1139 ans = self._check_nans(context=context)
1140 if ans:
1141 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001142
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001143 if self._sign:
1144 ans = self.__neg__(context=context)
1145 else:
1146 ans = self.__pos__(context=context)
1147
1148 return ans
1149
1150 def __add__(self, other, context=None):
1151 """Returns self + other.
1152
1153 -INF + INF (or the reverse) cause InvalidOperation errors.
1154 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001155 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001156 if other is NotImplemented:
1157 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001158
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001159 if context is None:
1160 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001161
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001162 if self._is_special or other._is_special:
1163 ans = self._check_nans(other, context)
1164 if ans:
1165 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001166
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001167 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001168 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001169 if self._sign != other._sign and other._isinfinity():
1170 return context._raise_error(InvalidOperation, '-INF + INF')
1171 return Decimal(self)
1172 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001173 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001174
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001175 exp = min(self._exp, other._exp)
1176 negativezero = 0
1177 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001178 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001179 negativezero = 1
1180
1181 if not self and not other:
1182 sign = min(self._sign, other._sign)
1183 if negativezero:
1184 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001185 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001186 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001187 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001188 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001189 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001190 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001191 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001192 return ans
1193 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001194 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001195 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001196 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001197 return ans
1198
1199 op1 = _WorkRep(self)
1200 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001201 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001202
1203 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001204 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001205 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001206 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001207 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001208 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001209 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001210 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001211 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001212 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001213 if op1.sign == 1:
1214 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001215 op1.sign, op2.sign = op2.sign, op1.sign
1216 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001217 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001218 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001219 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001220 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001221 op1.sign, op2.sign = (0, 0)
1222 else:
1223 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001224 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001225
Raymond Hettinger17931de2004-10-27 06:21:46 +00001226 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001227 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001228 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001229 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001230
1231 result.exp = op1.exp
1232 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001233 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001234 return ans
1235
1236 __radd__ = __add__
1237
1238 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001239 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001240 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001241 if other is NotImplemented:
1242 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001243
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001244 if self._is_special or other._is_special:
1245 ans = self._check_nans(other, context=context)
1246 if ans:
1247 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001248
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001249 # self - other is computed as self + other.copy_negate()
1250 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001251
1252 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001253 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001254 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001255 if other is NotImplemented:
1256 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001257
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001258 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001259
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001260 def __mul__(self, other, context=None):
1261 """Return self * other.
1262
1263 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1264 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001265 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001266 if other is NotImplemented:
1267 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001268
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001269 if context is None:
1270 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001271
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001272 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001273
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001274 if self._is_special or other._is_special:
1275 ans = self._check_nans(other, context)
1276 if ans:
1277 return ans
1278
1279 if self._isinfinity():
1280 if not other:
1281 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001282 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001283
1284 if other._isinfinity():
1285 if not self:
1286 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001287 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001288
1289 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001290
1291 # Special case for multiplying by zero
1292 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001293 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001294 # Fixing in case the exponent is out of bounds
1295 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001296 return ans
1297
1298 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001299 if self._int == '1':
1300 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001301 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001302 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001303 if other._int == '1':
1304 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001305 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001306 return ans
1307
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001308 op1 = _WorkRep(self)
1309 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001310
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001311 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001312 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001313
1314 return ans
1315 __rmul__ = __mul__
1316
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001317 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001318 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001319 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001320 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001321 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001322
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001323 if context is None:
1324 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001325
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001326 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001327
1328 if self._is_special or other._is_special:
1329 ans = self._check_nans(other, context)
1330 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001331 return ans
1332
1333 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001334 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001335
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001336 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001337 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001338
1339 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001340 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001341 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001342
1343 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001344 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001345 if not self:
1346 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001347 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001348
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001349 if not self:
1350 exp = self._exp - other._exp
1351 coeff = 0
1352 else:
1353 # OK, so neither = 0, INF or NaN
1354 shift = len(other._int) - len(self._int) + context.prec + 1
1355 exp = self._exp - other._exp - shift
1356 op1 = _WorkRep(self)
1357 op2 = _WorkRep(other)
1358 if shift >= 0:
1359 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1360 else:
1361 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1362 if remainder:
1363 # result is not exact; adjust to ensure correct rounding
1364 if coeff % 5 == 0:
1365 coeff += 1
1366 else:
1367 # result is exact; get as close to ideal exponent as possible
1368 ideal_exp = self._exp - other._exp
1369 while exp < ideal_exp and coeff % 10 == 0:
1370 coeff //= 10
1371 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001372
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001373 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001374 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001375
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001376 def _divide(self, other, context):
1377 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001378
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001379 Assumes that neither self nor other is a NaN, that self is not
1380 infinite and that other is nonzero.
1381 """
1382 sign = self._sign ^ other._sign
1383 if other._isinfinity():
1384 ideal_exp = self._exp
1385 else:
1386 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001387
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001388 expdiff = self.adjusted() - other.adjusted()
1389 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001390 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001391 self._rescale(ideal_exp, context.rounding))
1392 if expdiff <= context.prec:
1393 op1 = _WorkRep(self)
1394 op2 = _WorkRep(other)
1395 if op1.exp >= op2.exp:
1396 op1.int *= 10**(op1.exp - op2.exp)
1397 else:
1398 op2.int *= 10**(op2.exp - op1.exp)
1399 q, r = divmod(op1.int, op2.int)
1400 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001401 return (_dec_from_triple(sign, str(q), 0),
1402 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001403
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001404 # Here the quotient is too large to be representable
1405 ans = context._raise_error(DivisionImpossible,
1406 'quotient too large in //, % or divmod')
1407 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001408
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001409 def __rtruediv__(self, other, context=None):
1410 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001411 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001412 if other is NotImplemented:
1413 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001414 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001415
1416 def __divmod__(self, other, context=None):
1417 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001418 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001419 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001420 other = _convert_other(other)
1421 if other is NotImplemented:
1422 return other
1423
1424 if context is None:
1425 context = getcontext()
1426
1427 ans = self._check_nans(other, context)
1428 if ans:
1429 return (ans, ans)
1430
1431 sign = self._sign ^ other._sign
1432 if self._isinfinity():
1433 if other._isinfinity():
1434 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1435 return ans, ans
1436 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001437 return (_SignedInfinity[sign],
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001438 context._raise_error(InvalidOperation, 'INF % x'))
1439
1440 if not other:
1441 if not self:
1442 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1443 return ans, ans
1444 else:
1445 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1446 context._raise_error(InvalidOperation, 'x % 0'))
1447
1448 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001449 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001450 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001451
1452 def __rdivmod__(self, other, context=None):
1453 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001454 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001455 if other is NotImplemented:
1456 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001457 return other.__divmod__(self, context=context)
1458
1459 def __mod__(self, other, context=None):
1460 """
1461 self % other
1462 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001463 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001464 if other is NotImplemented:
1465 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001466
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001467 if context is None:
1468 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001469
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001470 ans = self._check_nans(other, context)
1471 if ans:
1472 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001473
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001474 if self._isinfinity():
1475 return context._raise_error(InvalidOperation, 'INF % x')
1476 elif not other:
1477 if self:
1478 return context._raise_error(InvalidOperation, 'x % 0')
1479 else:
1480 return context._raise_error(DivisionUndefined, '0 % 0')
1481
1482 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001483 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001484 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001485
1486 def __rmod__(self, other, context=None):
1487 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001488 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001489 if other is NotImplemented:
1490 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001491 return other.__mod__(self, context=context)
1492
1493 def remainder_near(self, other, context=None):
1494 """
1495 Remainder nearest to 0- abs(remainder-near) <= other/2
1496 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001497 if context is None:
1498 context = getcontext()
1499
1500 other = _convert_other(other, raiseit=True)
1501
1502 ans = self._check_nans(other, context)
1503 if ans:
1504 return ans
1505
1506 # self == +/-infinity -> InvalidOperation
1507 if self._isinfinity():
1508 return context._raise_error(InvalidOperation,
1509 'remainder_near(infinity, x)')
1510
1511 # other == 0 -> either InvalidOperation or DivisionUndefined
1512 if not other:
1513 if self:
1514 return context._raise_error(InvalidOperation,
1515 'remainder_near(x, 0)')
1516 else:
1517 return context._raise_error(DivisionUndefined,
1518 'remainder_near(0, 0)')
1519
1520 # other = +/-infinity -> remainder = self
1521 if other._isinfinity():
1522 ans = Decimal(self)
1523 return ans._fix(context)
1524
1525 # self = 0 -> remainder = self, with ideal exponent
1526 ideal_exponent = min(self._exp, other._exp)
1527 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001528 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001529 return ans._fix(context)
1530
1531 # catch most cases of large or small quotient
1532 expdiff = self.adjusted() - other.adjusted()
1533 if expdiff >= context.prec + 1:
1534 # expdiff >= prec+1 => abs(self/other) > 10**prec
1535 return context._raise_error(DivisionImpossible)
1536 if expdiff <= -2:
1537 # expdiff <= -2 => abs(self/other) < 0.1
1538 ans = self._rescale(ideal_exponent, context.rounding)
1539 return ans._fix(context)
1540
1541 # adjust both arguments to have the same exponent, then divide
1542 op1 = _WorkRep(self)
1543 op2 = _WorkRep(other)
1544 if op1.exp >= op2.exp:
1545 op1.int *= 10**(op1.exp - op2.exp)
1546 else:
1547 op2.int *= 10**(op2.exp - op1.exp)
1548 q, r = divmod(op1.int, op2.int)
1549 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1550 # 10**ideal_exponent. Apply correction to ensure that
1551 # abs(remainder) <= abs(other)/2
1552 if 2*r + (q&1) > op2.int:
1553 r -= op2.int
1554 q += 1
1555
1556 if q >= 10**context.prec:
1557 return context._raise_error(DivisionImpossible)
1558
1559 # result has same sign as self unless r is negative
1560 sign = self._sign
1561 if r < 0:
1562 sign = 1-sign
1563 r = -r
1564
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001565 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001566 return ans._fix(context)
1567
1568 def __floordiv__(self, other, context=None):
1569 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001570 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001571 if other is NotImplemented:
1572 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001573
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001574 if context is None:
1575 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001576
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001577 ans = self._check_nans(other, context)
1578 if ans:
1579 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001580
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001581 if self._isinfinity():
1582 if other._isinfinity():
1583 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001584 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001585 return _SignedInfinity[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001586
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001587 if not other:
1588 if self:
1589 return context._raise_error(DivisionByZero, 'x // 0',
1590 self._sign ^ other._sign)
1591 else:
1592 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001593
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001594 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001595
1596 def __rfloordiv__(self, other, context=None):
1597 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001598 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001599 if other is NotImplemented:
1600 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001601 return other.__floordiv__(self, context=context)
1602
1603 def __float__(self):
1604 """Float representation."""
Mark Dickinsonfc33d4c2012-08-24 18:53:10 +01001605 if self._isnan():
1606 if self.is_snan():
1607 raise ValueError("Cannot convert signaling NaN to float")
1608 s = "-nan" if self._sign else "nan"
1609 else:
1610 s = str(self)
1611 return float(s)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001612
1613 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001614 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001615 if self._is_special:
1616 if self._isnan():
Mark Dickinson825fce32009-09-07 18:08:12 +00001617 raise ValueError("Cannot convert NaN to integer")
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001618 elif self._isinfinity():
Mark Dickinson825fce32009-09-07 18:08:12 +00001619 raise OverflowError("Cannot convert infinity to integer")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001620 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001621 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001622 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001623 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001624 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001625
Christian Heimes969fe572008-01-25 11:23:10 +00001626 __trunc__ = __int__
1627
Christian Heimes0bd4e112008-02-12 22:59:25 +00001628 def real(self):
1629 return self
Mark Dickinson315a20a2009-01-04 21:34:18 +00001630 real = property(real)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001631
Christian Heimes0bd4e112008-02-12 22:59:25 +00001632 def imag(self):
1633 return Decimal(0)
Mark Dickinson315a20a2009-01-04 21:34:18 +00001634 imag = property(imag)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001635
1636 def conjugate(self):
1637 return self
1638
1639 def __complex__(self):
1640 return complex(float(self))
1641
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001642 def _fix_nan(self, context):
1643 """Decapitate the payload of a NaN to fit the context"""
1644 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001645
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001646 # maximum length of payload is precision if clamp=0,
1647 # precision-1 if clamp=1.
1648 max_payload_len = context.prec - context.clamp
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001649 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001650 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1651 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001652 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001653
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001654 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001655 """Round if it is necessary to keep self within prec precision.
1656
1657 Rounds and fixes the exponent. Does not raise on a sNaN.
1658
1659 Arguments:
1660 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001661 context - context used.
1662 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001663
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001664 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001665 if self._isnan():
1666 # decapitate payload if necessary
1667 return self._fix_nan(context)
1668 else:
1669 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001670 return Decimal(self)
1671
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001672 # if self is zero then exponent should be between Etiny and
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001673 # Emax if clamp==0, and between Etiny and Etop if clamp==1.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001674 Etiny = context.Etiny()
1675 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001676 if not self:
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001677 exp_max = [context.Emax, Etop][context.clamp]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001678 new_exp = min(max(self._exp, Etiny), exp_max)
1679 if new_exp != self._exp:
1680 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001681 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001682 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001683 return Decimal(self)
1684
1685 # exp_min is the smallest allowable exponent of the result,
1686 # equal to max(self.adjusted()-context.prec+1, Etiny)
1687 exp_min = len(self._int) + self._exp - context.prec
1688 if exp_min > Etop:
1689 # overflow: exp_min > Etop iff self.adjusted() > Emax
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001690 ans = context._raise_error(Overflow, 'above Emax', self._sign)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001691 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001692 context._raise_error(Rounded)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001693 return ans
1694
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001695 self_is_subnormal = exp_min < Etiny
1696 if self_is_subnormal:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001697 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001698
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001699 # round if self has too many digits
1700 if self._exp < exp_min:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001701 digits = len(self._int) + self._exp - exp_min
1702 if digits < 0:
1703 self = _dec_from_triple(self._sign, '1', exp_min-1)
1704 digits = 0
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001705 rounding_method = self._pick_rounding_function[context.rounding]
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04001706 changed = rounding_method(self, digits)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001707 coeff = self._int[:digits] or '0'
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001708 if changed > 0:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001709 coeff = str(int(coeff)+1)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001710 if len(coeff) > context.prec:
1711 coeff = coeff[:-1]
1712 exp_min += 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001713
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001714 # check whether the rounding pushed the exponent out of range
1715 if exp_min > Etop:
1716 ans = context._raise_error(Overflow, 'above Emax', self._sign)
1717 else:
1718 ans = _dec_from_triple(self._sign, coeff, exp_min)
1719
1720 # raise the appropriate signals, taking care to respect
1721 # the precedence described in the specification
1722 if changed and self_is_subnormal:
1723 context._raise_error(Underflow)
1724 if self_is_subnormal:
1725 context._raise_error(Subnormal)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001726 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001727 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001728 context._raise_error(Rounded)
1729 if not ans:
1730 # raise Clamped on underflow to 0
1731 context._raise_error(Clamped)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001732 return ans
1733
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001734 if self_is_subnormal:
1735 context._raise_error(Subnormal)
1736
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001737 # fold down if clamp == 1 and self has too few digits
1738 if context.clamp == 1 and self._exp > Etop:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001739 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001740 self_padded = self._int + '0'*(self._exp - Etop)
1741 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001742
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001743 # here self was representable to begin with; return unchanged
1744 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001745
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001746 # for each of the rounding functions below:
1747 # self is a finite, nonzero Decimal
1748 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001749 #
1750 # each function returns either -1, 0, or 1, as follows:
1751 # 1 indicates that self should be rounded up (away from zero)
1752 # 0 indicates that self should be truncated, and that all the
1753 # digits to be truncated are zeros (so the value is unchanged)
1754 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001755
1756 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001757 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001758 if _all_zeros(self._int, prec):
1759 return 0
1760 else:
1761 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001762
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001763 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001764 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001765 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001766
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001767 def _round_half_up(self, prec):
1768 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001769 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001770 return 1
1771 elif _all_zeros(self._int, prec):
1772 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001773 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001774 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001775
1776 def _round_half_down(self, prec):
1777 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001778 if _exact_half(self._int, prec):
1779 return -1
1780 else:
1781 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001782
1783 def _round_half_even(self, prec):
1784 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001785 if _exact_half(self._int, prec) and \
1786 (prec == 0 or self._int[prec-1] in '02468'):
1787 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001788 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001789 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001790
1791 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001792 """Rounds up (not away from 0 if negative.)"""
1793 if 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_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001799 """Rounds down (not towards 0 if negative)"""
1800 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001801 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001802 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001803 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001804
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001805 def _round_05up(self, prec):
1806 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001807 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001808 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001809 else:
1810 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001811
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04001812 _pick_rounding_function = dict(
1813 ROUND_DOWN = _round_down,
1814 ROUND_UP = _round_up,
1815 ROUND_HALF_UP = _round_half_up,
1816 ROUND_HALF_DOWN = _round_half_down,
1817 ROUND_HALF_EVEN = _round_half_even,
1818 ROUND_CEILING = _round_ceiling,
1819 ROUND_FLOOR = _round_floor,
1820 ROUND_05UP = _round_05up,
1821 )
1822
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001823 def __round__(self, n=None):
1824 """Round self to the nearest integer, or to a given precision.
1825
1826 If only one argument is supplied, round a finite Decimal
1827 instance self to the nearest integer. If self is infinite or
1828 a NaN then a Python exception is raised. If self is finite
1829 and lies exactly halfway between two integers then it is
1830 rounded to the integer with even last digit.
1831
1832 >>> round(Decimal('123.456'))
1833 123
1834 >>> round(Decimal('-456.789'))
1835 -457
1836 >>> round(Decimal('-3.0'))
1837 -3
1838 >>> round(Decimal('2.5'))
1839 2
1840 >>> round(Decimal('3.5'))
1841 4
1842 >>> round(Decimal('Inf'))
1843 Traceback (most recent call last):
1844 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001845 OverflowError: cannot round an infinity
1846 >>> round(Decimal('NaN'))
1847 Traceback (most recent call last):
1848 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001849 ValueError: cannot round a NaN
1850
1851 If a second argument n is supplied, self is rounded to n
1852 decimal places using the rounding mode for the current
1853 context.
1854
1855 For an integer n, round(self, -n) is exactly equivalent to
1856 self.quantize(Decimal('1En')).
1857
1858 >>> round(Decimal('123.456'), 0)
1859 Decimal('123')
1860 >>> round(Decimal('123.456'), 2)
1861 Decimal('123.46')
1862 >>> round(Decimal('123.456'), -2)
1863 Decimal('1E+2')
1864 >>> round(Decimal('-Infinity'), 37)
1865 Decimal('NaN')
1866 >>> round(Decimal('sNaN123'), 0)
1867 Decimal('NaN123')
1868
1869 """
1870 if n is not None:
1871 # two-argument form: use the equivalent quantize call
1872 if not isinstance(n, int):
1873 raise TypeError('Second argument to round should be integral')
1874 exp = _dec_from_triple(0, '1', -n)
1875 return self.quantize(exp)
1876
1877 # one-argument form
1878 if self._is_special:
1879 if self.is_nan():
1880 raise ValueError("cannot round a NaN")
1881 else:
1882 raise OverflowError("cannot round an infinity")
1883 return int(self._rescale(0, ROUND_HALF_EVEN))
1884
1885 def __floor__(self):
1886 """Return the floor of self, as an integer.
1887
1888 For a finite Decimal instance self, return the greatest
1889 integer n such that n <= self. If self is infinite or a NaN
1890 then a Python exception is raised.
1891
1892 """
1893 if self._is_special:
1894 if self.is_nan():
1895 raise ValueError("cannot round a NaN")
1896 else:
1897 raise OverflowError("cannot round an infinity")
1898 return int(self._rescale(0, ROUND_FLOOR))
1899
1900 def __ceil__(self):
1901 """Return the ceiling of self, as an integer.
1902
1903 For a finite Decimal instance self, return the least integer n
1904 such that n >= self. If self is infinite or a NaN then a
1905 Python exception is raised.
1906
1907 """
1908 if self._is_special:
1909 if self.is_nan():
1910 raise ValueError("cannot round a NaN")
1911 else:
1912 raise OverflowError("cannot round an infinity")
1913 return int(self._rescale(0, ROUND_CEILING))
1914
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001915 def fma(self, other, third, context=None):
1916 """Fused multiply-add.
1917
1918 Returns self*other+third with no rounding of the intermediate
1919 product self*other.
1920
1921 self and other are multiplied together, with no rounding of
1922 the result. The third operand is then added to the result,
1923 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001924 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001925
1926 other = _convert_other(other, raiseit=True)
Mark Dickinsonb455e582011-05-22 12:53:18 +01001927 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001928
1929 # compute product; raise InvalidOperation if either operand is
1930 # a signaling NaN or if the product is zero times infinity.
1931 if self._is_special or other._is_special:
1932 if context is None:
1933 context = getcontext()
1934 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001935 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001936 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001937 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001938 if self._exp == 'n':
1939 product = self
1940 elif other._exp == 'n':
1941 product = other
1942 elif self._exp == 'F':
1943 if not other:
1944 return context._raise_error(InvalidOperation,
1945 'INF * 0 in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001946 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001947 elif other._exp == 'F':
1948 if not self:
1949 return context._raise_error(InvalidOperation,
1950 '0 * INF in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001951 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001952 else:
1953 product = _dec_from_triple(self._sign ^ other._sign,
1954 str(int(self._int) * int(other._int)),
1955 self._exp + other._exp)
1956
Christian Heimes8b0facf2007-12-04 19:30:01 +00001957 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001958
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001959 def _power_modulo(self, other, modulo, context=None):
1960 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001961
Stefan Krah1919b7e2012-03-21 18:25:23 +01001962 other = _convert_other(other)
1963 if other is NotImplemented:
1964 return other
1965 modulo = _convert_other(modulo)
1966 if modulo is NotImplemented:
1967 return modulo
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001968
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001969 if context is None:
1970 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001971
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001972 # deal with NaNs: if there are any sNaNs then first one wins,
1973 # (i.e. behaviour for NaNs is identical to that of fma)
1974 self_is_nan = self._isnan()
1975 other_is_nan = other._isnan()
1976 modulo_is_nan = modulo._isnan()
1977 if self_is_nan or other_is_nan or modulo_is_nan:
1978 if self_is_nan == 2:
1979 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001980 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001981 if other_is_nan == 2:
1982 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001983 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001984 if modulo_is_nan == 2:
1985 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001986 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001987 if self_is_nan:
1988 return self._fix_nan(context)
1989 if other_is_nan:
1990 return other._fix_nan(context)
1991 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001992
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001993 # check inputs: we apply same restrictions as Python's pow()
1994 if not (self._isinteger() and
1995 other._isinteger() and
1996 modulo._isinteger()):
1997 return context._raise_error(InvalidOperation,
1998 'pow() 3rd argument not allowed '
1999 'unless all arguments are integers')
2000 if other < 0:
2001 return context._raise_error(InvalidOperation,
2002 'pow() 2nd argument cannot be '
2003 'negative when 3rd argument specified')
2004 if not modulo:
2005 return context._raise_error(InvalidOperation,
2006 'pow() 3rd argument cannot be 0')
2007
2008 # additional restriction for decimal: the modulus must be less
2009 # than 10**prec in absolute value
2010 if modulo.adjusted() >= context.prec:
2011 return context._raise_error(InvalidOperation,
2012 'insufficient precision: pow() 3rd '
2013 'argument must not have more than '
2014 'precision digits')
2015
2016 # define 0**0 == NaN, for consistency with two-argument pow
2017 # (even though it hurts!)
2018 if not other and not self:
2019 return context._raise_error(InvalidOperation,
2020 'at least one of pow() 1st argument '
2021 'and 2nd argument must be nonzero ;'
2022 '0**0 is not defined')
2023
2024 # compute sign of result
2025 if other._iseven():
2026 sign = 0
2027 else:
2028 sign = self._sign
2029
2030 # convert modulo to a Python integer, and self and other to
2031 # Decimal integers (i.e. force their exponents to be >= 0)
2032 modulo = abs(int(modulo))
2033 base = _WorkRep(self.to_integral_value())
2034 exponent = _WorkRep(other.to_integral_value())
2035
2036 # compute result using integer pow()
2037 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
2038 for i in range(exponent.exp):
2039 base = pow(base, 10, modulo)
2040 base = pow(base, exponent.int, modulo)
2041
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002042 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002043
2044 def _power_exact(self, other, p):
2045 """Attempt to compute self**other exactly.
2046
2047 Given Decimals self and other and an integer p, attempt to
2048 compute an exact result for the power self**other, with p
2049 digits of precision. Return None if self**other is not
2050 exactly representable in p digits.
2051
2052 Assumes that elimination of special cases has already been
2053 performed: self and other must both be nonspecial; self must
2054 be positive and not numerically equal to 1; other must be
2055 nonzero. For efficiency, other._exp should not be too large,
2056 so that 10**abs(other._exp) is a feasible calculation."""
2057
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002058 # In the comments below, we write x for the value of self and y for the
2059 # value of other. Write x = xc*10**xe and abs(y) = yc*10**ye, with xc
2060 # and yc positive integers not divisible by 10.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002061
2062 # The main purpose of this method is to identify the *failure*
2063 # of x**y to be exactly representable with as little effort as
2064 # possible. So we look for cheap and easy tests that
2065 # eliminate the possibility of x**y being exact. Only if all
2066 # these tests are passed do we go on to actually compute x**y.
2067
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002068 # Here's the main idea. Express y as a rational number m/n, with m and
2069 # n relatively prime and n>0. Then for x**y to be exactly
2070 # representable (at *any* precision), xc must be the nth power of a
2071 # positive integer and xe must be divisible by n. If y is negative
2072 # then additionally xc must be a power of either 2 or 5, hence a power
2073 # of 2**n or 5**n.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002074 #
2075 # There's a limit to how small |y| can be: if y=m/n as above
2076 # then:
2077 #
2078 # (1) if xc != 1 then for the result to be representable we
2079 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
2080 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
2081 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
2082 # representable.
2083 #
2084 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
2085 # |y| < 1/|xe| then the result is not representable.
2086 #
2087 # Note that since x is not equal to 1, at least one of (1) and
2088 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
2089 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
2090 #
2091 # There's also a limit to how large y can be, at least if it's
2092 # positive: the normalized result will have coefficient xc**y,
2093 # so if it's representable then xc**y < 10**p, and y <
2094 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
2095 # not exactly representable.
2096
2097 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
2098 # so |y| < 1/xe and the result is not representable.
2099 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
2100 # < 1/nbits(xc).
2101
2102 x = _WorkRep(self)
2103 xc, xe = x.int, x.exp
2104 while xc % 10 == 0:
2105 xc //= 10
2106 xe += 1
2107
2108 y = _WorkRep(other)
2109 yc, ye = y.int, y.exp
2110 while yc % 10 == 0:
2111 yc //= 10
2112 ye += 1
2113
2114 # case where xc == 1: result is 10**(xe*y), with xe*y
2115 # required to be an integer
2116 if xc == 1:
Mark Dickinsona1236312010-07-08 19:03:34 +00002117 xe *= yc
2118 # result is now 10**(xe * 10**ye); xe * 10**ye must be integral
2119 while xe % 10 == 0:
2120 xe //= 10
2121 ye += 1
2122 if ye < 0:
2123 return None
2124 exponent = xe * 10**ye
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002125 if y.sign == 1:
2126 exponent = -exponent
2127 # if other is a nonnegative integer, use ideal exponent
2128 if other._isinteger() and other._sign == 0:
2129 ideal_exponent = self._exp*int(other)
2130 zeros = min(exponent-ideal_exponent, p-1)
2131 else:
2132 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002133 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002134
2135 # case where y is negative: xc must be either a power
2136 # of 2 or a power of 5.
2137 if y.sign == 1:
2138 last_digit = xc % 10
2139 if last_digit in (2,4,6,8):
2140 # quick test for power of 2
2141 if xc & -xc != xc:
2142 return None
2143 # now xc is a power of 2; e is its exponent
2144 e = _nbits(xc)-1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002145
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002146 # We now have:
2147 #
2148 # x = 2**e * 10**xe, e > 0, and y < 0.
2149 #
2150 # The exact result is:
2151 #
2152 # x**y = 5**(-e*y) * 10**(e*y + xe*y)
2153 #
2154 # provided that both e*y and xe*y are integers. Note that if
2155 # 5**(-e*y) >= 10**p, then the result can't be expressed
2156 # exactly with p digits of precision.
2157 #
2158 # Using the above, we can guard against large values of ye.
2159 # 93/65 is an upper bound for log(10)/log(5), so if
2160 #
2161 # ye >= len(str(93*p//65))
2162 #
2163 # then
2164 #
2165 # -e*y >= -y >= 10**ye > 93*p/65 > p*log(10)/log(5),
2166 #
2167 # so 5**(-e*y) >= 10**p, and the coefficient of the result
2168 # can't be expressed in p digits.
2169
2170 # emax >= largest e such that 5**e < 10**p.
2171 emax = p*93//65
2172 if ye >= len(str(emax)):
2173 return None
2174
2175 # Find -e*y and -xe*y; both must be integers
2176 e = _decimal_lshift_exact(e * yc, ye)
2177 xe = _decimal_lshift_exact(xe * yc, ye)
2178 if e is None or xe is None:
2179 return None
2180
2181 if e > emax:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002182 return None
2183 xc = 5**e
2184
2185 elif last_digit == 5:
2186 # e >= log_5(xc) if xc is a power of 5; we have
2187 # equality all the way up to xc=5**2658
2188 e = _nbits(xc)*28//65
2189 xc, remainder = divmod(5**e, xc)
2190 if remainder:
2191 return None
2192 while xc % 5 == 0:
2193 xc //= 5
2194 e -= 1
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002195
2196 # Guard against large values of ye, using the same logic as in
2197 # the 'xc is a power of 2' branch. 10/3 is an upper bound for
2198 # log(10)/log(2).
2199 emax = p*10//3
2200 if ye >= len(str(emax)):
2201 return None
2202
2203 e = _decimal_lshift_exact(e * yc, ye)
2204 xe = _decimal_lshift_exact(xe * yc, ye)
2205 if e is None or xe is None:
2206 return None
2207
2208 if e > emax:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002209 return None
2210 xc = 2**e
2211 else:
2212 return None
2213
2214 if xc >= 10**p:
2215 return None
2216 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002217 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002218
2219 # now y is positive; find m and n such that y = m/n
2220 if ye >= 0:
2221 m, n = yc*10**ye, 1
2222 else:
2223 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2224 return None
2225 xc_bits = _nbits(xc)
2226 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2227 return None
2228 m, n = yc, 10**(-ye)
2229 while m % 2 == n % 2 == 0:
2230 m //= 2
2231 n //= 2
2232 while m % 5 == n % 5 == 0:
2233 m //= 5
2234 n //= 5
2235
2236 # compute nth root of xc*10**xe
2237 if n > 1:
2238 # if 1 < xc < 2**n then xc isn't an nth power
2239 if xc != 1 and xc_bits <= n:
2240 return None
2241
2242 xe, rem = divmod(xe, n)
2243 if rem != 0:
2244 return None
2245
2246 # compute nth root of xc using Newton's method
2247 a = 1 << -(-_nbits(xc)//n) # initial estimate
2248 while True:
2249 q, r = divmod(xc, a**(n-1))
2250 if a <= q:
2251 break
2252 else:
2253 a = (a*(n-1) + q)//n
2254 if not (a == q and r == 0):
2255 return None
2256 xc = a
2257
2258 # now xc*10**xe is the nth root of the original xc*10**xe
2259 # compute mth power of xc*10**xe
2260
2261 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2262 # 10**p and the result is not representable.
2263 if xc > 1 and m > p*100//_log10_lb(xc):
2264 return None
2265 xc = xc**m
2266 xe *= m
2267 if xc > 10**p:
2268 return None
2269
2270 # by this point the result *is* exactly representable
2271 # adjust the exponent to get as close as possible to the ideal
2272 # exponent, if necessary
2273 str_xc = str(xc)
2274 if other._isinteger() and other._sign == 0:
2275 ideal_exponent = self._exp*int(other)
2276 zeros = min(xe-ideal_exponent, p-len(str_xc))
2277 else:
2278 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002279 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002280
2281 def __pow__(self, other, modulo=None, context=None):
2282 """Return self ** other [ % modulo].
2283
2284 With two arguments, compute self**other.
2285
2286 With three arguments, compute (self**other) % modulo. For the
2287 three argument form, the following restrictions on the
2288 arguments hold:
2289
2290 - all three arguments must be integral
2291 - other must be nonnegative
2292 - either self or other (or both) must be nonzero
2293 - modulo must be nonzero and must have at most p digits,
2294 where p is the context precision.
2295
2296 If any of these restrictions is violated the InvalidOperation
2297 flag is raised.
2298
2299 The result of pow(self, other, modulo) is identical to the
2300 result that would be obtained by computing (self**other) %
2301 modulo with unbounded precision, but is computed more
2302 efficiently. It is always exact.
2303 """
2304
2305 if modulo is not None:
2306 return self._power_modulo(other, modulo, context)
2307
2308 other = _convert_other(other)
2309 if other is NotImplemented:
2310 return other
2311
2312 if context is None:
2313 context = getcontext()
2314
2315 # either argument is a NaN => result is NaN
2316 ans = self._check_nans(other, context)
2317 if ans:
2318 return ans
2319
2320 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2321 if not other:
2322 if not self:
2323 return context._raise_error(InvalidOperation, '0 ** 0')
2324 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002325 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002326
2327 # result has sign 1 iff self._sign is 1 and other is an odd integer
2328 result_sign = 0
2329 if self._sign == 1:
2330 if other._isinteger():
2331 if not other._iseven():
2332 result_sign = 1
2333 else:
2334 # -ve**noninteger = NaN
2335 # (-0)**noninteger = 0**noninteger
2336 if self:
2337 return context._raise_error(InvalidOperation,
2338 'x ** y with x negative and y not an integer')
2339 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002340 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002341
2342 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2343 if not self:
2344 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002345 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002346 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002347 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002348
2349 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002350 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002351 if other._sign == 0:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002352 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002353 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002354 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002355
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002356 # 1**other = 1, but the choice of exponent and the flags
2357 # depend on the exponent of self, and on whether other is a
2358 # positive integer, a negative integer, or neither
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002359 if self == _One:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002360 if other._isinteger():
2361 # exp = max(self._exp*max(int(other), 0),
2362 # 1-context.prec) but evaluating int(other) directly
2363 # is dangerous until we know other is small (other
2364 # could be 1e999999999)
2365 if other._sign == 1:
2366 multiplier = 0
2367 elif other > context.prec:
2368 multiplier = context.prec
2369 else:
2370 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002371
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002372 exp = self._exp * multiplier
2373 if exp < 1-context.prec:
2374 exp = 1-context.prec
2375 context._raise_error(Rounded)
2376 else:
2377 context._raise_error(Inexact)
2378 context._raise_error(Rounded)
2379 exp = 1-context.prec
2380
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002381 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002382
2383 # compute adjusted exponent of self
2384 self_adj = self.adjusted()
2385
2386 # self ** infinity is infinity if self > 1, 0 if self < 1
2387 # self ** -infinity is infinity if self < 1, 0 if self > 1
2388 if other._isinfinity():
2389 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002390 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002391 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002392 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002393
2394 # from here on, the result always goes through the call
2395 # to _fix at the end of this function.
2396 ans = None
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002397 exact = False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002398
2399 # crude test to catch cases of extreme overflow/underflow. If
2400 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2401 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2402 # self**other >= 10**(Emax+1), so overflow occurs. The test
2403 # for underflow is similar.
2404 bound = self._log10_exp_bound() + other.adjusted()
2405 if (self_adj >= 0) == (other._sign == 0):
2406 # self > 1 and other +ve, or self < 1 and other -ve
2407 # possibility of overflow
2408 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002409 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002410 else:
2411 # self > 1 and other -ve, or self < 1 and other +ve
2412 # possibility of underflow to 0
2413 Etiny = context.Etiny()
2414 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002415 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002416
2417 # try for an exact result with precision +1
2418 if ans is None:
2419 ans = self._power_exact(other, context.prec + 1)
Mark Dickinsone42f1bb2010-07-08 19:09:16 +00002420 if ans is not None:
2421 if result_sign == 1:
2422 ans = _dec_from_triple(1, ans._int, ans._exp)
2423 exact = True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002424
2425 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2426 if ans is None:
2427 p = context.prec
2428 x = _WorkRep(self)
2429 xc, xe = x.int, x.exp
2430 y = _WorkRep(other)
2431 yc, ye = y.int, y.exp
2432 if y.sign == 1:
2433 yc = -yc
2434
2435 # compute correctly rounded result: start with precision +3,
2436 # then increase precision until result is unambiguously roundable
2437 extra = 3
2438 while True:
2439 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2440 if coeff % (5*10**(len(str(coeff))-p-1)):
2441 break
2442 extra += 3
2443
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002444 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002445
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002446 # unlike exp, ln and log10, the power function respects the
2447 # rounding mode; no need to switch to ROUND_HALF_EVEN here
2448
2449 # There's a difficulty here when 'other' is not an integer and
2450 # the result is exact. In this case, the specification
2451 # requires that the Inexact flag be raised (in spite of
2452 # exactness), but since the result is exact _fix won't do this
2453 # for us. (Correspondingly, the Underflow signal should also
2454 # be raised for subnormal results.) We can't directly raise
2455 # these signals either before or after calling _fix, since
2456 # that would violate the precedence for signals. So we wrap
2457 # the ._fix call in a temporary context, and reraise
2458 # afterwards.
2459 if exact and not other._isinteger():
2460 # pad with zeros up to length context.prec+1 if necessary; this
2461 # ensures that the Rounded signal will be raised.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002462 if len(ans._int) <= context.prec:
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002463 expdiff = context.prec + 1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002464 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2465 ans._exp-expdiff)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002466
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002467 # create a copy of the current context, with cleared flags/traps
2468 newcontext = context.copy()
2469 newcontext.clear_flags()
2470 for exception in _signals:
2471 newcontext.traps[exception] = 0
2472
2473 # round in the new context
2474 ans = ans._fix(newcontext)
2475
2476 # raise Inexact, and if necessary, Underflow
2477 newcontext._raise_error(Inexact)
2478 if newcontext.flags[Subnormal]:
2479 newcontext._raise_error(Underflow)
2480
2481 # propagate signals to the original context; _fix could
2482 # have raised any of Overflow, Underflow, Subnormal,
2483 # Inexact, Rounded, Clamped. Overflow needs the correct
2484 # arguments. Note that the order of the exceptions is
2485 # important here.
2486 if newcontext.flags[Overflow]:
2487 context._raise_error(Overflow, 'above Emax', ans._sign)
2488 for exception in Underflow, Subnormal, Inexact, Rounded, Clamped:
2489 if newcontext.flags[exception]:
2490 context._raise_error(exception)
2491
2492 else:
2493 ans = ans._fix(context)
2494
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002495 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002496
2497 def __rpow__(self, other, context=None):
2498 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002499 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002500 if other is NotImplemented:
2501 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002502 return other.__pow__(self, context=context)
2503
2504 def normalize(self, context=None):
2505 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002506
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002507 if context is None:
2508 context = getcontext()
2509
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002510 if self._is_special:
2511 ans = self._check_nans(context=context)
2512 if ans:
2513 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002514
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002515 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002516 if dup._isinfinity():
2517 return dup
2518
2519 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002520 return _dec_from_triple(dup._sign, '0', 0)
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00002521 exp_max = [context.Emax, context.Etop()][context.clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002522 end = len(dup._int)
2523 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002524 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002525 exp += 1
2526 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002527 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002528
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002529 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002530 """Quantize self so its exponent is the same as that of exp.
2531
2532 Similar to self._rescale(exp._exp) but with error checking.
2533 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002534 exp = _convert_other(exp, raiseit=True)
2535
2536 if context is None:
2537 context = getcontext()
2538 if rounding is None:
2539 rounding = context.rounding
2540
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002541 if self._is_special or exp._is_special:
2542 ans = self._check_nans(exp, context)
2543 if ans:
2544 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002545
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002546 if exp._isinfinity() or self._isinfinity():
2547 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002548 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002549 return context._raise_error(InvalidOperation,
2550 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002551
2552 # if we're not watching exponents, do a simple rescale
2553 if not watchexp:
2554 ans = self._rescale(exp._exp, rounding)
2555 # raise Inexact and Rounded where appropriate
2556 if ans._exp > self._exp:
2557 context._raise_error(Rounded)
2558 if ans != self:
2559 context._raise_error(Inexact)
2560 return ans
2561
2562 # exp._exp should be between Etiny and Emax
2563 if not (context.Etiny() <= exp._exp <= context.Emax):
2564 return context._raise_error(InvalidOperation,
2565 'target exponent out of bounds in quantize')
2566
2567 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002568 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002569 return ans._fix(context)
2570
2571 self_adjusted = self.adjusted()
2572 if self_adjusted > context.Emax:
2573 return context._raise_error(InvalidOperation,
2574 'exponent of quantize result too large for current context')
2575 if self_adjusted - exp._exp + 1 > context.prec:
2576 return context._raise_error(InvalidOperation,
2577 'quantize result has too many digits for current context')
2578
2579 ans = self._rescale(exp._exp, rounding)
2580 if ans.adjusted() > context.Emax:
2581 return context._raise_error(InvalidOperation,
2582 'exponent of quantize result too large for current context')
2583 if len(ans._int) > context.prec:
2584 return context._raise_error(InvalidOperation,
2585 'quantize result has too many digits for current context')
2586
2587 # raise appropriate flags
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002588 if ans and ans.adjusted() < context.Emin:
2589 context._raise_error(Subnormal)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002590 if ans._exp > self._exp:
2591 if ans != self:
2592 context._raise_error(Inexact)
2593 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002594
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002595 # call to fix takes care of any necessary folddown, and
2596 # signals Clamped if necessary
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002597 ans = ans._fix(context)
2598 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002599
Stefan Krah040e3112012-12-15 22:33:33 +01002600 def same_quantum(self, other, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002601 """Return True if self and other have the same exponent; otherwise
2602 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002603
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002604 If either operand is a special value, the following rules are used:
2605 * return True if both operands are infinities
2606 * return True if both operands are NaNs
2607 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002608 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002609 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002610 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002611 return (self.is_nan() and other.is_nan() or
2612 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002613 return self._exp == other._exp
2614
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002615 def _rescale(self, exp, rounding):
2616 """Rescale self so that the exponent is exp, either by padding with zeros
2617 or by truncating digits, using the given rounding mode.
2618
2619 Specials are returned without change. This operation is
2620 quiet: it raises no flags, and uses no information from the
2621 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002622
2623 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002624 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002625 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002626 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002627 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002628 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002629 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002630
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002631 if self._exp >= exp:
2632 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002633 return _dec_from_triple(self._sign,
2634 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002635
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002636 # too many digits; round and lose data. If self.adjusted() <
2637 # exp-1, replace self by 10**(exp-1) before rounding
2638 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002639 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002640 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002641 digits = 0
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04002642 this_function = self._pick_rounding_function[rounding]
2643 changed = this_function(self, digits)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002644 coeff = self._int[:digits] or '0'
2645 if changed == 1:
2646 coeff = str(int(coeff)+1)
2647 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002648
Christian Heimesf16baeb2008-02-29 14:57:44 +00002649 def _round(self, places, rounding):
2650 """Round a nonzero, nonspecial Decimal to a fixed number of
2651 significant figures, using the given rounding mode.
2652
2653 Infinities, NaNs and zeros are returned unaltered.
2654
2655 This operation is quiet: it raises no flags, and uses no
2656 information from the context.
2657
2658 """
2659 if places <= 0:
2660 raise ValueError("argument should be at least 1 in _round")
2661 if self._is_special or not self:
2662 return Decimal(self)
2663 ans = self._rescale(self.adjusted()+1-places, rounding)
2664 # it can happen that the rescale alters the adjusted exponent;
2665 # for example when rounding 99.97 to 3 significant figures.
2666 # When this happens we end up with an extra 0 at the end of
2667 # the number; a second rescale fixes this.
2668 if ans.adjusted() != self.adjusted():
2669 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2670 return ans
2671
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002672 def to_integral_exact(self, rounding=None, context=None):
2673 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002674
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002675 If no rounding mode is specified, take the rounding mode from
2676 the context. This method raises the Rounded and Inexact flags
2677 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002678
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002679 See also: to_integral_value, which does exactly the same as
2680 this method except that it doesn't raise Inexact or Rounded.
2681 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002682 if self._is_special:
2683 ans = self._check_nans(context=context)
2684 if ans:
2685 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002686 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002687 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002688 return Decimal(self)
2689 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002690 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002691 if context is None:
2692 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002693 if rounding is None:
2694 rounding = context.rounding
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002695 ans = self._rescale(0, rounding)
2696 if ans != self:
2697 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002698 context._raise_error(Rounded)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002699 return ans
2700
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002701 def to_integral_value(self, rounding=None, context=None):
2702 """Rounds to the nearest integer, without raising inexact, rounded."""
2703 if context is None:
2704 context = getcontext()
2705 if rounding is None:
2706 rounding = context.rounding
2707 if self._is_special:
2708 ans = self._check_nans(context=context)
2709 if ans:
2710 return ans
2711 return Decimal(self)
2712 if self._exp >= 0:
2713 return Decimal(self)
2714 else:
2715 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002716
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002717 # the method name changed, but we provide also the old one, for compatibility
2718 to_integral = to_integral_value
2719
2720 def sqrt(self, context=None):
2721 """Return the square root of self."""
Christian Heimes0348fb62008-03-26 12:55:56 +00002722 if context is None:
2723 context = getcontext()
2724
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002725 if self._is_special:
2726 ans = self._check_nans(context=context)
2727 if ans:
2728 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002729
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002730 if self._isinfinity() and self._sign == 0:
2731 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002732
2733 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002734 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002735 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002736 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002737
2738 if self._sign == 1:
2739 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2740
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002741 # At this point self represents a positive number. Let p be
2742 # the desired precision and express self in the form c*100**e
2743 # with c a positive real number and e an integer, c and e
2744 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2745 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2746 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2747 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2748 # the closest integer to sqrt(c) with the even integer chosen
2749 # in the case of a tie.
2750 #
2751 # To ensure correct rounding in all cases, we use the
2752 # following trick: we compute the square root to an extra
2753 # place (precision p+1 instead of precision p), rounding down.
2754 # Then, if the result is inexact and its last digit is 0 or 5,
2755 # we increase the last digit to 1 or 6 respectively; if it's
2756 # exact we leave the last digit alone. Now the final round to
2757 # p places (or fewer in the case of underflow) will round
2758 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002759
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002760 # use an extra digit of precision
2761 prec = context.prec+1
2762
2763 # write argument in the form c*100**e where e = self._exp//2
2764 # is the 'ideal' exponent, to be used if the square root is
2765 # exactly representable. l is the number of 'digits' of c in
2766 # base 100, so that 100**(l-1) <= c < 100**l.
2767 op = _WorkRep(self)
2768 e = op.exp >> 1
2769 if op.exp & 1:
2770 c = op.int * 10
2771 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002772 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002773 c = op.int
2774 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002775
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002776 # rescale so that c has exactly prec base 100 'digits'
2777 shift = prec-l
2778 if shift >= 0:
2779 c *= 100**shift
2780 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002781 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002782 c, remainder = divmod(c, 100**-shift)
2783 exact = not remainder
2784 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002785
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002786 # find n = floor(sqrt(c)) using Newton's method
2787 n = 10**prec
2788 while True:
2789 q = c//n
2790 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002791 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002792 else:
2793 n = n + q >> 1
2794 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002795
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002796 if exact:
2797 # result is exact; rescale to use ideal exponent e
2798 if shift >= 0:
2799 # assert n % 10**shift == 0
2800 n //= 10**shift
2801 else:
2802 n *= 10**-shift
2803 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002804 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002805 # result is not exact; fix last digit as described above
2806 if n % 5 == 0:
2807 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002808
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002809 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002810
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002811 # round, and fit to current context
2812 context = context._shallow_copy()
2813 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002814 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002815 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002816
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002817 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002818
2819 def max(self, other, context=None):
2820 """Returns the larger value.
2821
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002822 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002823 NaN (and signals if one is sNaN). Also rounds.
2824 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002825 other = _convert_other(other, raiseit=True)
2826
2827 if context is None:
2828 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002829
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002830 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002831 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002832 # number is always returned
2833 sn = self._isnan()
2834 on = other._isnan()
2835 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002836 if on == 1 and sn == 0:
2837 return self._fix(context)
2838 if sn == 1 and on == 0:
2839 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002840 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002841
Christian Heimes77c02eb2008-02-09 02:18:51 +00002842 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002843 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002844 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002845 # then an ordering is applied:
2846 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002847 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002848 # positive sign and min returns the operand with the negative sign
2849 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002850 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002851 # the result. This is exactly the ordering used in compare_total.
2852 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002853
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002854 if c == -1:
2855 ans = other
2856 else:
2857 ans = self
2858
Christian Heimes2c181612007-12-17 20:04:13 +00002859 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002860
2861 def min(self, other, context=None):
2862 """Returns the smaller value.
2863
Guido van Rossumd8faa362007-04-27 19:54:29 +00002864 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002865 NaN (and signals if one is sNaN). Also rounds.
2866 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002867 other = _convert_other(other, raiseit=True)
2868
2869 if context is None:
2870 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002871
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002872 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002873 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002874 # number is always returned
2875 sn = self._isnan()
2876 on = other._isnan()
2877 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002878 if on == 1 and sn == 0:
2879 return self._fix(context)
2880 if sn == 1 and on == 0:
2881 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002882 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002883
Christian Heimes77c02eb2008-02-09 02:18:51 +00002884 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002885 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002886 c = self.compare_total(other)
2887
2888 if c == -1:
2889 ans = self
2890 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002891 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002892
Christian Heimes2c181612007-12-17 20:04:13 +00002893 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002894
2895 def _isinteger(self):
2896 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002897 if self._is_special:
2898 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002899 if self._exp >= 0:
2900 return True
2901 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002902 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002903
2904 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002905 """Returns True if self is even. Assumes self is an integer."""
2906 if not self or self._exp > 0:
2907 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002908 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002909
2910 def adjusted(self):
2911 """Return the adjusted exponent of self"""
2912 try:
2913 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002914 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002915 except TypeError:
2916 return 0
2917
Stefan Krah040e3112012-12-15 22:33:33 +01002918 def canonical(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002919 """Returns the same Decimal object.
2920
2921 As we do not have different encodings for the same number, the
2922 received object already is in its canonical form.
2923 """
2924 return self
2925
2926 def compare_signal(self, other, context=None):
2927 """Compares self to the other operand numerically.
2928
2929 It's pretty much like compare(), but all NaNs signal, with signaling
2930 NaNs taking precedence over quiet NaNs.
2931 """
Christian Heimes77c02eb2008-02-09 02:18:51 +00002932 other = _convert_other(other, raiseit = True)
2933 ans = self._compare_check_nans(other, context)
2934 if ans:
2935 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002936 return self.compare(other, context=context)
2937
Stefan Krah040e3112012-12-15 22:33:33 +01002938 def compare_total(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002939 """Compares self to other using the abstract representations.
2940
2941 This is not like the standard compare, which use their numerical
2942 value. Note that a total ordering is defined for all possible abstract
2943 representations.
2944 """
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00002945 other = _convert_other(other, raiseit=True)
2946
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002947 # if one is negative and the other is positive, it's easy
2948 if self._sign and not other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002949 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002950 if not self._sign and other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002951 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002952 sign = self._sign
2953
2954 # let's handle both NaN types
2955 self_nan = self._isnan()
2956 other_nan = other._isnan()
2957 if self_nan or other_nan:
2958 if self_nan == other_nan:
Mark Dickinsond314e1b2009-08-28 13:39:53 +00002959 # compare payloads as though they're integers
2960 self_key = len(self._int), self._int
2961 other_key = len(other._int), other._int
2962 if self_key < other_key:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002963 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002964 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002965 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002966 return _NegativeOne
Mark Dickinsond314e1b2009-08-28 13:39:53 +00002967 if self_key > other_key:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002968 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002969 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002970 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002971 return _One
2972 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002973
2974 if sign:
2975 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002976 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002977 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002978 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002979 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002980 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002981 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002982 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002983 else:
2984 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002985 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002986 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002987 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002988 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002989 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002990 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002991 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002992
2993 if self < other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002994 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002995 if self > other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002996 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002997
2998 if self._exp < other._exp:
2999 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003000 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003001 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003002 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003003 if self._exp > other._exp:
3004 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003005 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003006 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003007 return _One
3008 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003009
3010
Stefan Krah040e3112012-12-15 22:33:33 +01003011 def compare_total_mag(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003012 """Compares self to other using abstract repr., ignoring sign.
3013
3014 Like compare_total, but with operand's sign ignored and assumed to be 0.
3015 """
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003016 other = _convert_other(other, raiseit=True)
3017
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003018 s = self.copy_abs()
3019 o = other.copy_abs()
3020 return s.compare_total(o)
3021
3022 def copy_abs(self):
3023 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003024 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003025
3026 def copy_negate(self):
3027 """Returns a copy with the sign inverted."""
3028 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003029 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003030 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003031 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003032
Stefan Krah040e3112012-12-15 22:33:33 +01003033 def copy_sign(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003034 """Returns self with the sign of other."""
Mark Dickinson84230a12010-02-18 14:49:50 +00003035 other = _convert_other(other, raiseit=True)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003036 return _dec_from_triple(other._sign, self._int,
3037 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003038
3039 def exp(self, context=None):
3040 """Returns e ** self."""
3041
3042 if context is None:
3043 context = getcontext()
3044
3045 # exp(NaN) = NaN
3046 ans = self._check_nans(context=context)
3047 if ans:
3048 return ans
3049
3050 # exp(-Infinity) = 0
3051 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003052 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003053
3054 # exp(0) = 1
3055 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003056 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003057
3058 # exp(Infinity) = Infinity
3059 if self._isinfinity() == 1:
3060 return Decimal(self)
3061
3062 # the result is now guaranteed to be inexact (the true
3063 # mathematical result is transcendental). There's no need to
3064 # raise Rounded and Inexact here---they'll always be raised as
3065 # a result of the call to _fix.
3066 p = context.prec
3067 adj = self.adjusted()
3068
3069 # we only need to do any computation for quite a small range
3070 # of adjusted exponents---for example, -29 <= adj <= 10 for
3071 # the default context. For smaller exponent the result is
3072 # indistinguishable from 1 at the given precision, while for
3073 # larger exponent the result either overflows or underflows.
3074 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
3075 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003076 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003077 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
3078 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003079 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003080 elif self._sign == 0 and adj < -p:
3081 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003082 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003083 elif self._sign == 1 and adj < -p-1:
3084 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003085 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003086 # general case
3087 else:
3088 op = _WorkRep(self)
3089 c, e = op.int, op.exp
3090 if op.sign == 1:
3091 c = -c
3092
3093 # compute correctly rounded result: increase precision by
3094 # 3 digits at a time until we get an unambiguously
3095 # roundable result
3096 extra = 3
3097 while True:
3098 coeff, exp = _dexp(c, e, p+extra)
3099 if coeff % (5*10**(len(str(coeff))-p-1)):
3100 break
3101 extra += 3
3102
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003103 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003104
3105 # at this stage, ans should round correctly with *any*
3106 # rounding mode, not just with ROUND_HALF_EVEN
3107 context = context._shallow_copy()
3108 rounding = context._set_rounding(ROUND_HALF_EVEN)
3109 ans = ans._fix(context)
3110 context.rounding = rounding
3111
3112 return ans
3113
3114 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003115 """Return True if self is canonical; otherwise return False.
3116
3117 Currently, the encoding of a Decimal instance is always
3118 canonical, so this method returns True for any Decimal.
3119 """
3120 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003121
3122 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003123 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003124
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003125 A Decimal instance is considered finite if it is neither
3126 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003127 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003128 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003129
3130 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003131 """Return True if self is infinite; otherwise return False."""
3132 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003133
3134 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003135 """Return True if self is a qNaN or sNaN; otherwise return False."""
3136 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003137
3138 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003139 """Return True if self is a normal number; otherwise return False."""
3140 if self._is_special or not self:
3141 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003142 if context is None:
3143 context = getcontext()
Mark Dickinson06bb6742009-10-20 13:38:04 +00003144 return context.Emin <= self.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003145
3146 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003147 """Return True if self is a quiet NaN; otherwise return False."""
3148 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003149
3150 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003151 """Return True if self is negative; otherwise return False."""
3152 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003153
3154 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003155 """Return True if self is a signaling NaN; otherwise return False."""
3156 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003157
3158 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003159 """Return True if self is subnormal; otherwise return False."""
3160 if self._is_special or not self:
3161 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003162 if context is None:
3163 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003164 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003165
3166 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003167 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003168 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003169
3170 def _ln_exp_bound(self):
3171 """Compute a lower bound for the adjusted exponent of self.ln().
3172 In other words, compute r such that self.ln() >= 10**r. Assumes
3173 that self is finite and positive and that self != 1.
3174 """
3175
3176 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
3177 adj = self._exp + len(self._int) - 1
3178 if adj >= 1:
3179 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
3180 return len(str(adj*23//10)) - 1
3181 if adj <= -2:
3182 # argument <= 0.1
3183 return len(str((-1-adj)*23//10)) - 1
3184 op = _WorkRep(self)
3185 c, e = op.int, op.exp
3186 if adj == 0:
3187 # 1 < self < 10
3188 num = str(c-10**-e)
3189 den = str(c)
3190 return len(num) - len(den) - (num < den)
3191 # adj == -1, 0.1 <= self < 1
3192 return e + len(str(10**-e - c)) - 1
3193
3194
3195 def ln(self, context=None):
3196 """Returns the natural (base e) logarithm of self."""
3197
3198 if context is None:
3199 context = getcontext()
3200
3201 # ln(NaN) = NaN
3202 ans = self._check_nans(context=context)
3203 if ans:
3204 return ans
3205
3206 # ln(0.0) == -Infinity
3207 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003208 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003209
3210 # ln(Infinity) = Infinity
3211 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003212 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003213
3214 # ln(1.0) == 0.0
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003215 if self == _One:
3216 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003217
3218 # ln(negative) raises InvalidOperation
3219 if self._sign == 1:
3220 return context._raise_error(InvalidOperation,
3221 'ln of a negative value')
3222
3223 # result is irrational, so necessarily inexact
3224 op = _WorkRep(self)
3225 c, e = op.int, op.exp
3226 p = context.prec
3227
3228 # correctly rounded result: repeatedly increase precision by 3
3229 # until we get an unambiguously roundable result
3230 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3231 while True:
3232 coeff = _dlog(c, e, places)
3233 # assert len(str(abs(coeff)))-p >= 1
3234 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3235 break
3236 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003237 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003238
3239 context = context._shallow_copy()
3240 rounding = context._set_rounding(ROUND_HALF_EVEN)
3241 ans = ans._fix(context)
3242 context.rounding = rounding
3243 return ans
3244
3245 def _log10_exp_bound(self):
3246 """Compute a lower bound for the adjusted exponent of self.log10().
3247 In other words, find r such that self.log10() >= 10**r.
3248 Assumes that self is finite and positive and that self != 1.
3249 """
3250
3251 # For x >= 10 or x < 0.1 we only need a bound on the integer
3252 # part of log10(self), and this comes directly from the
3253 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3254 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3255 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3256
3257 adj = self._exp + len(self._int) - 1
3258 if adj >= 1:
3259 # self >= 10
3260 return len(str(adj))-1
3261 if adj <= -2:
3262 # self < 0.1
3263 return len(str(-1-adj))-1
3264 op = _WorkRep(self)
3265 c, e = op.int, op.exp
3266 if adj == 0:
3267 # 1 < self < 10
3268 num = str(c-10**-e)
3269 den = str(231*c)
3270 return len(num) - len(den) - (num < den) + 2
3271 # adj == -1, 0.1 <= self < 1
3272 num = str(10**-e-c)
3273 return len(num) + e - (num < "231") - 1
3274
3275 def log10(self, context=None):
3276 """Returns the base 10 logarithm of self."""
3277
3278 if context is None:
3279 context = getcontext()
3280
3281 # log10(NaN) = NaN
3282 ans = self._check_nans(context=context)
3283 if ans:
3284 return ans
3285
3286 # log10(0.0) == -Infinity
3287 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003288 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003289
3290 # log10(Infinity) = Infinity
3291 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003292 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003293
3294 # log10(negative or -Infinity) raises InvalidOperation
3295 if self._sign == 1:
3296 return context._raise_error(InvalidOperation,
3297 'log10 of a negative value')
3298
3299 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003300 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003301 # answer may need rounding
3302 ans = Decimal(self._exp + len(self._int) - 1)
3303 else:
3304 # result is irrational, so necessarily inexact
3305 op = _WorkRep(self)
3306 c, e = op.int, op.exp
3307 p = context.prec
3308
3309 # correctly rounded result: repeatedly increase precision
3310 # until result is unambiguously roundable
3311 places = p-self._log10_exp_bound()+2
3312 while True:
3313 coeff = _dlog10(c, e, places)
3314 # assert len(str(abs(coeff)))-p >= 1
3315 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3316 break
3317 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003318 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003319
3320 context = context._shallow_copy()
3321 rounding = context._set_rounding(ROUND_HALF_EVEN)
3322 ans = ans._fix(context)
3323 context.rounding = rounding
3324 return ans
3325
3326 def logb(self, context=None):
3327 """ Returns the exponent of the magnitude of self's MSD.
3328
3329 The result is the integer which is the exponent of the magnitude
3330 of the most significant digit of self (as though it were truncated
3331 to a single digit while maintaining the value of that digit and
3332 without limiting the resulting exponent).
3333 """
3334 # logb(NaN) = NaN
3335 ans = self._check_nans(context=context)
3336 if ans:
3337 return ans
3338
3339 if context is None:
3340 context = getcontext()
3341
3342 # logb(+/-Inf) = +Inf
3343 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003344 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003345
3346 # logb(0) = -Inf, DivisionByZero
3347 if not self:
3348 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3349
3350 # otherwise, simply return the adjusted exponent of self, as a
3351 # Decimal. Note that no attempt is made to fit the result
3352 # into the current context.
Mark Dickinson56df8872009-10-07 19:23:50 +00003353 ans = Decimal(self.adjusted())
3354 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003355
3356 def _islogical(self):
3357 """Return True if self is a logical operand.
3358
Christian Heimes679db4a2008-01-18 09:56:22 +00003359 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003360 an exponent of 0, and a coefficient whose digits must all be
3361 either 0 or 1.
3362 """
3363 if self._sign != 0 or self._exp != 0:
3364 return False
3365 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003366 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003367 return False
3368 return True
3369
3370 def _fill_logical(self, context, opa, opb):
3371 dif = context.prec - len(opa)
3372 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003373 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003374 elif dif < 0:
3375 opa = opa[-context.prec:]
3376 dif = context.prec - len(opb)
3377 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003378 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003379 elif dif < 0:
3380 opb = opb[-context.prec:]
3381 return opa, opb
3382
3383 def logical_and(self, other, context=None):
3384 """Applies an 'and' operation between self and other's digits."""
3385 if context is None:
3386 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003387
3388 other = _convert_other(other, raiseit=True)
3389
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003390 if not self._islogical() or not other._islogical():
3391 return context._raise_error(InvalidOperation)
3392
3393 # fill to context.prec
3394 (opa, opb) = self._fill_logical(context, self._int, other._int)
3395
3396 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003397 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3398 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003399
3400 def logical_invert(self, context=None):
3401 """Invert all its digits."""
3402 if context is None:
3403 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003404 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3405 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003406
3407 def logical_or(self, other, context=None):
3408 """Applies an 'or' operation between self and other's digits."""
3409 if context is None:
3410 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003411
3412 other = _convert_other(other, raiseit=True)
3413
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003414 if not self._islogical() or not other._islogical():
3415 return context._raise_error(InvalidOperation)
3416
3417 # fill to context.prec
3418 (opa, opb) = self._fill_logical(context, self._int, other._int)
3419
3420 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003421 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003422 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003423
3424 def logical_xor(self, other, context=None):
3425 """Applies an 'xor' operation between self and other's digits."""
3426 if context is None:
3427 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003428
3429 other = _convert_other(other, raiseit=True)
3430
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003431 if not self._islogical() or not other._islogical():
3432 return context._raise_error(InvalidOperation)
3433
3434 # fill to context.prec
3435 (opa, opb) = self._fill_logical(context, self._int, other._int)
3436
3437 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003438 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003439 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003440
3441 def max_mag(self, other, context=None):
3442 """Compares the values numerically with their sign ignored."""
3443 other = _convert_other(other, raiseit=True)
3444
3445 if context is None:
3446 context = getcontext()
3447
3448 if self._is_special or other._is_special:
3449 # If one operand is a quiet NaN and the other is number, then the
3450 # number is always returned
3451 sn = self._isnan()
3452 on = other._isnan()
3453 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003454 if on == 1 and sn == 0:
3455 return self._fix(context)
3456 if sn == 1 and on == 0:
3457 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003458 return self._check_nans(other, context)
3459
Christian Heimes77c02eb2008-02-09 02:18:51 +00003460 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003461 if c == 0:
3462 c = self.compare_total(other)
3463
3464 if c == -1:
3465 ans = other
3466 else:
3467 ans = self
3468
Christian Heimes2c181612007-12-17 20:04:13 +00003469 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003470
3471 def min_mag(self, other, context=None):
3472 """Compares the values numerically with their sign ignored."""
3473 other = _convert_other(other, raiseit=True)
3474
3475 if context is None:
3476 context = getcontext()
3477
3478 if self._is_special or other._is_special:
3479 # If one operand is a quiet NaN and the other is number, then the
3480 # number is always returned
3481 sn = self._isnan()
3482 on = other._isnan()
3483 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003484 if on == 1 and sn == 0:
3485 return self._fix(context)
3486 if sn == 1 and on == 0:
3487 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003488 return self._check_nans(other, context)
3489
Christian Heimes77c02eb2008-02-09 02:18:51 +00003490 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003491 if c == 0:
3492 c = self.compare_total(other)
3493
3494 if c == -1:
3495 ans = self
3496 else:
3497 ans = other
3498
Christian Heimes2c181612007-12-17 20:04:13 +00003499 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003500
3501 def next_minus(self, context=None):
3502 """Returns the largest representable number smaller than itself."""
3503 if context is None:
3504 context = getcontext()
3505
3506 ans = self._check_nans(context=context)
3507 if ans:
3508 return ans
3509
3510 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003511 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003512 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003513 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003514
3515 context = context.copy()
3516 context._set_rounding(ROUND_FLOOR)
3517 context._ignore_all_flags()
3518 new_self = self._fix(context)
3519 if new_self != self:
3520 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003521 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3522 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003523
3524 def next_plus(self, context=None):
3525 """Returns the smallest representable number larger than itself."""
3526 if context is None:
3527 context = getcontext()
3528
3529 ans = self._check_nans(context=context)
3530 if ans:
3531 return ans
3532
3533 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003534 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003535 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003536 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003537
3538 context = context.copy()
3539 context._set_rounding(ROUND_CEILING)
3540 context._ignore_all_flags()
3541 new_self = self._fix(context)
3542 if new_self != self:
3543 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003544 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3545 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003546
3547 def next_toward(self, other, context=None):
3548 """Returns the number closest to self, in the direction towards other.
3549
3550 The result is the closest representable number to self
3551 (excluding self) that is in the direction towards other,
3552 unless both have the same value. If the two operands are
3553 numerically equal, then the result is a copy of self with the
3554 sign set to be the same as the sign of other.
3555 """
3556 other = _convert_other(other, raiseit=True)
3557
3558 if context is None:
3559 context = getcontext()
3560
3561 ans = self._check_nans(other, context)
3562 if ans:
3563 return ans
3564
Christian Heimes77c02eb2008-02-09 02:18:51 +00003565 comparison = self._cmp(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003566 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003567 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003568
3569 if comparison == -1:
3570 ans = self.next_plus(context)
3571 else: # comparison == 1
3572 ans = self.next_minus(context)
3573
3574 # decide which flags to raise using value of ans
3575 if ans._isinfinity():
3576 context._raise_error(Overflow,
3577 'Infinite result from next_toward',
3578 ans._sign)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003579 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00003580 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003581 elif ans.adjusted() < context.Emin:
3582 context._raise_error(Underflow)
3583 context._raise_error(Subnormal)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003584 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00003585 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003586 # if precision == 1 then we don't raise Clamped for a
3587 # result 0E-Etiny.
3588 if not ans:
3589 context._raise_error(Clamped)
3590
3591 return ans
3592
3593 def number_class(self, context=None):
3594 """Returns an indication of the class of self.
3595
3596 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003597 sNaN
3598 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003599 -Infinity
3600 -Normal
3601 -Subnormal
3602 -Zero
3603 +Zero
3604 +Subnormal
3605 +Normal
3606 +Infinity
3607 """
3608 if self.is_snan():
3609 return "sNaN"
3610 if self.is_qnan():
3611 return "NaN"
3612 inf = self._isinfinity()
3613 if inf == 1:
3614 return "+Infinity"
3615 if inf == -1:
3616 return "-Infinity"
3617 if self.is_zero():
3618 if self._sign:
3619 return "-Zero"
3620 else:
3621 return "+Zero"
3622 if context is None:
3623 context = getcontext()
3624 if self.is_subnormal(context=context):
3625 if self._sign:
3626 return "-Subnormal"
3627 else:
3628 return "+Subnormal"
3629 # just a normal, regular, boring number, :)
3630 if self._sign:
3631 return "-Normal"
3632 else:
3633 return "+Normal"
3634
3635 def radix(self):
3636 """Just returns 10, as this is Decimal, :)"""
3637 return Decimal(10)
3638
3639 def rotate(self, other, context=None):
3640 """Returns a rotated copy of self, value-of-other times."""
3641 if context is None:
3642 context = getcontext()
3643
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003644 other = _convert_other(other, raiseit=True)
3645
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003646 ans = self._check_nans(other, context)
3647 if ans:
3648 return ans
3649
3650 if other._exp != 0:
3651 return context._raise_error(InvalidOperation)
3652 if not (-context.prec <= int(other) <= context.prec):
3653 return context._raise_error(InvalidOperation)
3654
3655 if self._isinfinity():
3656 return Decimal(self)
3657
3658 # get values, pad if necessary
3659 torot = int(other)
3660 rotdig = self._int
3661 topad = context.prec - len(rotdig)
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003662 if topad > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003663 rotdig = '0'*topad + rotdig
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003664 elif topad < 0:
3665 rotdig = rotdig[-topad:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003666
3667 # let's rotate!
3668 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003669 return _dec_from_triple(self._sign,
3670 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003671
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003672 def scaleb(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003673 """Returns self operand after adding the second value to its exp."""
3674 if context is None:
3675 context = getcontext()
3676
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003677 other = _convert_other(other, raiseit=True)
3678
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003679 ans = self._check_nans(other, context)
3680 if ans:
3681 return ans
3682
3683 if other._exp != 0:
3684 return context._raise_error(InvalidOperation)
3685 liminf = -2 * (context.Emax + context.prec)
3686 limsup = 2 * (context.Emax + context.prec)
3687 if not (liminf <= int(other) <= limsup):
3688 return context._raise_error(InvalidOperation)
3689
3690 if self._isinfinity():
3691 return Decimal(self)
3692
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003693 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003694 d = d._fix(context)
3695 return d
3696
3697 def shift(self, other, context=None):
3698 """Returns a shifted copy of self, value-of-other times."""
3699 if context is None:
3700 context = getcontext()
3701
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003702 other = _convert_other(other, raiseit=True)
3703
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003704 ans = self._check_nans(other, context)
3705 if ans:
3706 return ans
3707
3708 if other._exp != 0:
3709 return context._raise_error(InvalidOperation)
3710 if not (-context.prec <= int(other) <= context.prec):
3711 return context._raise_error(InvalidOperation)
3712
3713 if self._isinfinity():
3714 return Decimal(self)
3715
3716 # get values, pad if necessary
3717 torot = int(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003718 rotdig = self._int
3719 topad = context.prec - len(rotdig)
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003720 if topad > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003721 rotdig = '0'*topad + rotdig
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003722 elif topad < 0:
3723 rotdig = rotdig[-topad:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003724
3725 # let's shift!
3726 if torot < 0:
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003727 shifted = rotdig[:torot]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003728 else:
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003729 shifted = rotdig + '0'*torot
3730 shifted = shifted[-context.prec:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003731
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003732 return _dec_from_triple(self._sign,
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003733 shifted.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003734
Guido van Rossumd8faa362007-04-27 19:54:29 +00003735 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003736 def __reduce__(self):
3737 return (self.__class__, (str(self),))
3738
3739 def __copy__(self):
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00003740 if type(self) is Decimal:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003741 return self # I'm immutable; therefore I am my own clone
3742 return self.__class__(str(self))
3743
3744 def __deepcopy__(self, memo):
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00003745 if type(self) is Decimal:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003746 return self # My components are also immutable
3747 return self.__class__(str(self))
3748
Mark Dickinson79f52032009-03-17 23:12:51 +00003749 # PEP 3101 support. the _localeconv keyword argument should be
3750 # considered private: it's provided for ease of testing only.
3751 def __format__(self, specifier, context=None, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00003752 """Format a Decimal instance according to the given specifier.
3753
3754 The specifier should be a standard format specifier, with the
3755 form described in PEP 3101. Formatting types 'e', 'E', 'f',
Mark Dickinson79f52032009-03-17 23:12:51 +00003756 'F', 'g', 'G', 'n' and '%' are supported. If the formatting
3757 type is omitted it defaults to 'g' or 'G', depending on the
3758 value of context.capitals.
Christian Heimesf16baeb2008-02-29 14:57:44 +00003759 """
3760
3761 # Note: PEP 3101 says that if the type is not present then
3762 # there should be at least one digit after the decimal point.
3763 # We take the liberty of ignoring this requirement for
3764 # Decimal---it's presumably there to make sure that
3765 # format(float, '') behaves similarly to str(float).
3766 if context is None:
3767 context = getcontext()
3768
Mark Dickinson79f52032009-03-17 23:12:51 +00003769 spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003770
Mark Dickinson79f52032009-03-17 23:12:51 +00003771 # special values don't care about the type or precision
Christian Heimesf16baeb2008-02-29 14:57:44 +00003772 if self._is_special:
Mark Dickinson79f52032009-03-17 23:12:51 +00003773 sign = _format_sign(self._sign, spec)
3774 body = str(self.copy_abs())
3775 return _format_align(sign, body, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003776
3777 # a type of None defaults to 'g' or 'G', depending on context
Christian Heimesf16baeb2008-02-29 14:57:44 +00003778 if spec['type'] is None:
3779 spec['type'] = ['g', 'G'][context.capitals]
Mark Dickinson79f52032009-03-17 23:12:51 +00003780
3781 # if type is '%', adjust exponent of self accordingly
3782 if spec['type'] == '%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003783 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3784
3785 # round if necessary, taking rounding mode from the context
3786 rounding = context.rounding
3787 precision = spec['precision']
3788 if precision is not None:
3789 if spec['type'] in 'eE':
3790 self = self._round(precision+1, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003791 elif spec['type'] in 'fF%':
3792 self = self._rescale(-precision, rounding)
Mark Dickinson79f52032009-03-17 23:12:51 +00003793 elif spec['type'] in 'gG' and len(self._int) > precision:
3794 self = self._round(precision, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003795 # special case: zeros with a positive exponent can't be
3796 # represented in fixed point; rescale them to 0e0.
Mark Dickinson79f52032009-03-17 23:12:51 +00003797 if not self and self._exp > 0 and spec['type'] in 'fF%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003798 self = self._rescale(0, rounding)
3799
3800 # figure out placement of the decimal point
3801 leftdigits = self._exp + len(self._int)
Mark Dickinson79f52032009-03-17 23:12:51 +00003802 if spec['type'] in 'eE':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003803 if not self and precision is not None:
3804 dotplace = 1 - precision
3805 else:
3806 dotplace = 1
Mark Dickinson79f52032009-03-17 23:12:51 +00003807 elif spec['type'] in 'fF%':
3808 dotplace = leftdigits
Christian Heimesf16baeb2008-02-29 14:57:44 +00003809 elif spec['type'] in 'gG':
3810 if self._exp <= 0 and leftdigits > -6:
3811 dotplace = leftdigits
3812 else:
3813 dotplace = 1
3814
Mark Dickinson79f52032009-03-17 23:12:51 +00003815 # find digits before and after decimal point, and get exponent
3816 if dotplace < 0:
3817 intpart = '0'
3818 fracpart = '0'*(-dotplace) + self._int
3819 elif dotplace > len(self._int):
3820 intpart = self._int + '0'*(dotplace-len(self._int))
3821 fracpart = ''
Christian Heimesf16baeb2008-02-29 14:57:44 +00003822 else:
Mark Dickinson79f52032009-03-17 23:12:51 +00003823 intpart = self._int[:dotplace] or '0'
3824 fracpart = self._int[dotplace:]
3825 exp = leftdigits-dotplace
Christian Heimesf16baeb2008-02-29 14:57:44 +00003826
Mark Dickinson79f52032009-03-17 23:12:51 +00003827 # done with the decimal-specific stuff; hand over the rest
3828 # of the formatting to the _format_number function
3829 return _format_number(self._sign, intpart, fracpart, exp, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003830
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003831def _dec_from_triple(sign, coefficient, exponent, special=False):
3832 """Create a decimal instance directly, without any validation,
3833 normalization (e.g. removal of leading zeros) or argument
3834 conversion.
3835
3836 This function is for *internal use only*.
3837 """
3838
3839 self = object.__new__(Decimal)
3840 self._sign = sign
3841 self._int = coefficient
3842 self._exp = exponent
3843 self._is_special = special
3844
3845 return self
3846
Raymond Hettinger82417ca2009-02-03 03:54:28 +00003847# Register Decimal as a kind of Number (an abstract base class).
3848# However, do not register it as Real (because Decimals are not
3849# interoperable with floats).
3850_numbers.Number.register(Decimal)
3851
3852
Guido van Rossumd8faa362007-04-27 19:54:29 +00003853##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003854
Thomas Wouters89f507f2006-12-13 04:49:30 +00003855class _ContextManager(object):
3856 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003857
Thomas Wouters89f507f2006-12-13 04:49:30 +00003858 Sets a copy of the supplied context in __enter__() and restores
3859 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003860 """
3861 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003862 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003863 def __enter__(self):
3864 self.saved_context = getcontext()
3865 setcontext(self.new_context)
3866 return self.new_context
3867 def __exit__(self, t, v, tb):
3868 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003869
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003870class Context(object):
3871 """Contains the context for a Decimal instance.
3872
3873 Contains:
3874 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003875 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003876 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003877 raised when it is caused. Otherwise, a value is
3878 substituted in.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003879 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003880 (Whether or not the trap_enabler is set)
3881 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003882 Emin - Minimum exponent
3883 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003884 capitals - If 1, 1*10^1 is printed as 1E+1.
3885 If 0, printed as 1e1
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00003886 clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003887 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003888
Stefan Krah1919b7e2012-03-21 18:25:23 +01003889 def __init__(self, prec=None, rounding=None, Emin=None, Emax=None,
3890 capitals=None, clamp=None, flags=None, traps=None,
3891 _ignored_flags=None):
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003892 # Set defaults; for everything except flags and _ignored_flags,
3893 # inherit from DefaultContext.
3894 try:
3895 dc = DefaultContext
3896 except NameError:
3897 pass
3898
3899 self.prec = prec if prec is not None else dc.prec
3900 self.rounding = rounding if rounding is not None else dc.rounding
3901 self.Emin = Emin if Emin is not None else dc.Emin
3902 self.Emax = Emax if Emax is not None else dc.Emax
3903 self.capitals = capitals if capitals is not None else dc.capitals
3904 self.clamp = clamp if clamp is not None else dc.clamp
3905
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003906 if _ignored_flags is None:
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003907 self._ignored_flags = []
3908 else:
3909 self._ignored_flags = _ignored_flags
3910
3911 if traps is None:
3912 self.traps = dc.traps.copy()
3913 elif not isinstance(traps, dict):
Stefan Krah1919b7e2012-03-21 18:25:23 +01003914 self.traps = dict((s, int(s in traps)) for s in _signals + traps)
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003915 else:
3916 self.traps = traps
3917
3918 if flags is None:
3919 self.flags = dict.fromkeys(_signals, 0)
3920 elif not isinstance(flags, dict):
Stefan Krah1919b7e2012-03-21 18:25:23 +01003921 self.flags = dict((s, int(s in flags)) for s in _signals + flags)
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003922 else:
3923 self.flags = flags
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003924
Stefan Krah1919b7e2012-03-21 18:25:23 +01003925 def _set_integer_check(self, name, value, vmin, vmax):
3926 if not isinstance(value, int):
3927 raise TypeError("%s must be an integer" % name)
3928 if vmin == '-inf':
3929 if value > vmax:
3930 raise ValueError("%s must be in [%s, %d]. got: %s" % (name, vmin, vmax, value))
3931 elif vmax == 'inf':
3932 if value < vmin:
3933 raise ValueError("%s must be in [%d, %s]. got: %s" % (name, vmin, vmax, value))
3934 else:
3935 if value < vmin or value > vmax:
3936 raise ValueError("%s must be in [%d, %d]. got %s" % (name, vmin, vmax, value))
3937 return object.__setattr__(self, name, value)
3938
3939 def _set_signal_dict(self, name, d):
3940 if not isinstance(d, dict):
3941 raise TypeError("%s must be a signal dict" % d)
3942 for key in d:
3943 if not key in _signals:
3944 raise KeyError("%s is not a valid signal dict" % d)
3945 for key in _signals:
3946 if not key in d:
3947 raise KeyError("%s is not a valid signal dict" % d)
3948 return object.__setattr__(self, name, d)
3949
3950 def __setattr__(self, name, value):
3951 if name == 'prec':
3952 return self._set_integer_check(name, value, 1, 'inf')
3953 elif name == 'Emin':
3954 return self._set_integer_check(name, value, '-inf', 0)
3955 elif name == 'Emax':
3956 return self._set_integer_check(name, value, 0, 'inf')
3957 elif name == 'capitals':
3958 return self._set_integer_check(name, value, 0, 1)
3959 elif name == 'clamp':
3960 return self._set_integer_check(name, value, 0, 1)
3961 elif name == 'rounding':
3962 if not value in _rounding_modes:
3963 # raise TypeError even for strings to have consistency
3964 # among various implementations.
3965 raise TypeError("%s: invalid rounding mode" % value)
3966 return object.__setattr__(self, name, value)
3967 elif name == 'flags' or name == 'traps':
3968 return self._set_signal_dict(name, value)
3969 elif name == '_ignored_flags':
3970 return object.__setattr__(self, name, value)
3971 else:
3972 raise AttributeError(
3973 "'decimal.Context' object has no attribute '%s'" % name)
3974
3975 def __delattr__(self, name):
3976 raise AttributeError("%s cannot be deleted" % name)
3977
3978 # Support for pickling, copy, and deepcopy
3979 def __reduce__(self):
3980 flags = [sig for sig, v in self.flags.items() if v]
3981 traps = [sig for sig, v in self.traps.items() if v]
3982 return (self.__class__,
3983 (self.prec, self.rounding, self.Emin, self.Emax,
3984 self.capitals, self.clamp, flags, traps))
3985
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003986 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003987 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003988 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003989 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00003990 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d, '
3991 'clamp=%(clamp)d'
Guido van Rossumd8faa362007-04-27 19:54:29 +00003992 % vars(self))
3993 names = [f.__name__ for f, v in self.flags.items() if v]
3994 s.append('flags=[' + ', '.join(names) + ']')
3995 names = [t.__name__ for t, v in self.traps.items() if v]
3996 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003997 return ', '.join(s) + ')'
3998
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003999 def clear_flags(self):
4000 """Reset all flags to zero"""
4001 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00004002 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00004003
Stefan Krah1919b7e2012-03-21 18:25:23 +01004004 def clear_traps(self):
4005 """Reset all traps to zero"""
4006 for flag in self.traps:
4007 self.traps[flag] = 0
4008
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004009 def _shallow_copy(self):
4010 """Returns a shallow 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, self.flags, self.traps,
4013 self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004014 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004015
4016 def copy(self):
4017 """Returns a deep copy from self."""
Stefan Krah1919b7e2012-03-21 18:25:23 +01004018 nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
4019 self.capitals, self.clamp,
4020 self.flags.copy(), self.traps.copy(),
4021 self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004022 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004023 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004024
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004025 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004026 """Handles an error
4027
4028 If the flag is in _ignored_flags, returns the default response.
Raymond Hettinger86173da2008-02-01 20:38:12 +00004029 Otherwise, it sets the flag, then, if the corresponding
Stefan Krah2eb4a072010-05-19 15:52:31 +00004030 trap_enabler is set, it reraises the exception. Otherwise, it returns
Raymond Hettinger86173da2008-02-01 20:38:12 +00004031 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004032 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004033 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004034 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00004035 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004036 return error().handle(self, *args)
4037
Raymond Hettinger86173da2008-02-01 20:38:12 +00004038 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00004039 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00004040 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004041 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004042
4043 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00004044 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00004045 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004046
4047 def _ignore_all_flags(self):
4048 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00004049 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004050
4051 def _ignore_flags(self, *flags):
4052 """Ignore the flags, if they are raised"""
4053 # Do not mutate-- This way, copies of a context leave the original
4054 # alone.
4055 self._ignored_flags = (self._ignored_flags + list(flags))
4056 return list(flags)
4057
4058 def _regard_flags(self, *flags):
4059 """Stop ignoring the flags, if they are raised"""
4060 if flags and isinstance(flags[0], (tuple,list)):
4061 flags = flags[0]
4062 for flag in flags:
4063 self._ignored_flags.remove(flag)
4064
Nick Coghland1abd252008-07-15 15:46:38 +00004065 # We inherit object.__hash__, so we must deny this explicitly
4066 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004067
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004068 def Etiny(self):
4069 """Returns Etiny (= Emin - prec + 1)"""
4070 return int(self.Emin - self.prec + 1)
4071
4072 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004073 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004074 return int(self.Emax - self.prec + 1)
4075
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004076 def _set_rounding(self, type):
4077 """Sets the rounding type.
4078
4079 Sets the rounding type, and returns the current (previous)
4080 rounding type. Often used like:
4081
4082 context = context.copy()
4083 # so you don't change the calling context
4084 # if an error occurs in the middle.
4085 rounding = context._set_rounding(ROUND_UP)
4086 val = self.__sub__(other, context=context)
4087 context._set_rounding(rounding)
4088
4089 This will make it round up for that operation.
4090 """
4091 rounding = self.rounding
4092 self.rounding= type
4093 return rounding
4094
Raymond Hettingerfed52962004-07-14 15:41:57 +00004095 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00004096 """Creates a new Decimal instance but using self as context.
4097
4098 This method implements the to-number operation of the
4099 IBM Decimal specification."""
4100
4101 if isinstance(num, str) and num != num.strip():
4102 return self._raise_error(ConversionSyntax,
4103 "no trailing or leading whitespace is "
4104 "permitted.")
4105
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004106 d = Decimal(num, context=self)
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00004107 if d._isnan() and len(d._int) > self.prec - self.clamp:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004108 return self._raise_error(ConversionSyntax,
4109 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00004110 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004111
Raymond Hettinger771ed762009-01-03 19:20:32 +00004112 def create_decimal_from_float(self, f):
4113 """Creates a new Decimal instance from a float but rounding using self
4114 as the context.
4115
4116 >>> context = Context(prec=5, rounding=ROUND_DOWN)
4117 >>> context.create_decimal_from_float(3.1415926535897932)
4118 Decimal('3.1415')
4119 >>> context = Context(prec=5, traps=[Inexact])
4120 >>> context.create_decimal_from_float(3.1415926535897932)
4121 Traceback (most recent call last):
4122 ...
4123 decimal.Inexact: None
4124
4125 """
4126 d = Decimal.from_float(f) # An exact conversion
4127 return d._fix(self) # Apply the context rounding
4128
Guido van Rossumd8faa362007-04-27 19:54:29 +00004129 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004130 def abs(self, a):
4131 """Returns the absolute value of the operand.
4132
4133 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00004134 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004135 the plus operation on the operand.
4136
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004137 >>> ExtendedContext.abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004138 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004139 >>> ExtendedContext.abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004140 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004141 >>> ExtendedContext.abs(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004142 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004143 >>> ExtendedContext.abs(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004144 Decimal('101.5')
Mark Dickinson84230a12010-02-18 14:49:50 +00004145 >>> ExtendedContext.abs(-1)
4146 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004147 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004148 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004149 return a.__abs__(context=self)
4150
4151 def add(self, a, b):
4152 """Return the sum of the two operands.
4153
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004154 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004155 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004156 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004157 Decimal('1.02E+4')
Mark Dickinson84230a12010-02-18 14:49:50 +00004158 >>> ExtendedContext.add(1, Decimal(2))
4159 Decimal('3')
4160 >>> ExtendedContext.add(Decimal(8), 5)
4161 Decimal('13')
4162 >>> ExtendedContext.add(5, 5)
4163 Decimal('10')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004164 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004165 a = _convert_other(a, raiseit=True)
4166 r = a.__add__(b, context=self)
4167 if r is NotImplemented:
4168 raise TypeError("Unable to convert %s to Decimal" % b)
4169 else:
4170 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004171
4172 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00004173 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004174
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004175 def canonical(self, a):
4176 """Returns the same Decimal object.
4177
4178 As we do not have different encodings for the same number, the
4179 received object already is in its canonical form.
4180
4181 >>> ExtendedContext.canonical(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004182 Decimal('2.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004183 """
Stefan Krah1919b7e2012-03-21 18:25:23 +01004184 if not isinstance(a, Decimal):
4185 raise TypeError("canonical requires a Decimal as an argument.")
Stefan Krah040e3112012-12-15 22:33:33 +01004186 return a.canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004187
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004188 def compare(self, a, b):
4189 """Compares values numerically.
4190
4191 If the signs of the operands differ, a value representing each operand
4192 ('-1' if the operand is less than zero, '0' if the operand is zero or
4193 negative zero, or '1' if the operand is greater than zero) is used in
4194 place of that operand for the comparison instead of the actual
4195 operand.
4196
4197 The comparison is then effected by subtracting the second operand from
4198 the first and then returning a value according to the result of the
4199 subtraction: '-1' if the result is less than zero, '0' if the result is
4200 zero or negative zero, or '1' if the result is greater than zero.
4201
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004202 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004203 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004204 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004205 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004206 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004207 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004208 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004209 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004210 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004211 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004212 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004213 Decimal('-1')
Mark Dickinson84230a12010-02-18 14:49:50 +00004214 >>> ExtendedContext.compare(1, 2)
4215 Decimal('-1')
4216 >>> ExtendedContext.compare(Decimal(1), 2)
4217 Decimal('-1')
4218 >>> ExtendedContext.compare(1, Decimal(2))
4219 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004220 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004221 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004222 return a.compare(b, context=self)
4223
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004224 def compare_signal(self, a, b):
4225 """Compares the values of the two operands numerically.
4226
4227 It's pretty much like compare(), but all NaNs signal, with signaling
4228 NaNs taking precedence over quiet NaNs.
4229
4230 >>> c = ExtendedContext
4231 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004232 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004233 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004234 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004235 >>> c.flags[InvalidOperation] = 0
4236 >>> print(c.flags[InvalidOperation])
4237 0
4238 >>> c.compare_signal(Decimal('NaN'), 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
4242 >>> c.flags[InvalidOperation] = 0
4243 >>> print(c.flags[InvalidOperation])
4244 0
4245 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004246 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004247 >>> print(c.flags[InvalidOperation])
4248 1
Mark Dickinson84230a12010-02-18 14:49:50 +00004249 >>> c.compare_signal(-1, 2)
4250 Decimal('-1')
4251 >>> c.compare_signal(Decimal(-1), 2)
4252 Decimal('-1')
4253 >>> c.compare_signal(-1, Decimal(2))
4254 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004255 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004256 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004257 return a.compare_signal(b, context=self)
4258
4259 def compare_total(self, a, b):
4260 """Compares two operands using their abstract representation.
4261
4262 This is not like the standard compare, which use their numerical
4263 value. Note that a total ordering is defined for all possible abstract
4264 representations.
4265
4266 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004267 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004268 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004269 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004270 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004271 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004272 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004273 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004274 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004275 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004276 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004277 Decimal('-1')
Mark Dickinson84230a12010-02-18 14:49:50 +00004278 >>> ExtendedContext.compare_total(1, 2)
4279 Decimal('-1')
4280 >>> ExtendedContext.compare_total(Decimal(1), 2)
4281 Decimal('-1')
4282 >>> ExtendedContext.compare_total(1, Decimal(2))
4283 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004284 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004285 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004286 return a.compare_total(b)
4287
4288 def compare_total_mag(self, a, b):
4289 """Compares two operands using their abstract representation ignoring sign.
4290
4291 Like compare_total, but with operand's sign ignored and assumed to be 0.
4292 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004293 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004294 return a.compare_total_mag(b)
4295
4296 def copy_abs(self, a):
4297 """Returns a copy of the operand with the sign set to 0.
4298
4299 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004300 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004301 >>> ExtendedContext.copy_abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004302 Decimal('100')
Mark Dickinson84230a12010-02-18 14:49:50 +00004303 >>> ExtendedContext.copy_abs(-1)
4304 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004305 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004306 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004307 return a.copy_abs()
4308
4309 def copy_decimal(self, a):
Mark Dickinson84230a12010-02-18 14:49:50 +00004310 """Returns a copy of the decimal object.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004311
4312 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004313 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004314 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004315 Decimal('-1.00')
Mark Dickinson84230a12010-02-18 14:49:50 +00004316 >>> ExtendedContext.copy_decimal(1)
4317 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004318 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004319 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004320 return Decimal(a)
4321
4322 def copy_negate(self, a):
4323 """Returns a copy of the operand with the sign inverted.
4324
4325 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004326 Decimal('-101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004327 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004328 Decimal('101.5')
Mark Dickinson84230a12010-02-18 14:49:50 +00004329 >>> ExtendedContext.copy_negate(1)
4330 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004331 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004332 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004333 return a.copy_negate()
4334
4335 def copy_sign(self, a, b):
4336 """Copies the second operand's sign to the first one.
4337
4338 In detail, it returns a copy of the first operand with the sign
4339 equal to the sign of the second operand.
4340
4341 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004342 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004343 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004344 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004345 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004346 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004347 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004348 Decimal('-1.50')
Mark Dickinson84230a12010-02-18 14:49:50 +00004349 >>> ExtendedContext.copy_sign(1, -2)
4350 Decimal('-1')
4351 >>> ExtendedContext.copy_sign(Decimal(1), -2)
4352 Decimal('-1')
4353 >>> ExtendedContext.copy_sign(1, Decimal(-2))
4354 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004355 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004356 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004357 return a.copy_sign(b)
4358
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004359 def divide(self, a, b):
4360 """Decimal division in a specified context.
4361
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004362 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004363 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004364 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004365 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004366 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004367 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004368 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004369 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004370 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004371 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004372 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004373 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004374 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004375 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004376 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004377 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004378 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004379 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004380 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004381 Decimal('1.20E+6')
Mark Dickinson84230a12010-02-18 14:49:50 +00004382 >>> ExtendedContext.divide(5, 5)
4383 Decimal('1')
4384 >>> ExtendedContext.divide(Decimal(5), 5)
4385 Decimal('1')
4386 >>> ExtendedContext.divide(5, Decimal(5))
4387 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004388 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004389 a = _convert_other(a, raiseit=True)
4390 r = a.__truediv__(b, context=self)
4391 if r is NotImplemented:
4392 raise TypeError("Unable to convert %s to Decimal" % b)
4393 else:
4394 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004395
4396 def divide_int(self, a, b):
4397 """Divides two numbers and returns the integer part of the result.
4398
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004399 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004400 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004401 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004402 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004403 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004404 Decimal('3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004405 >>> ExtendedContext.divide_int(10, 3)
4406 Decimal('3')
4407 >>> ExtendedContext.divide_int(Decimal(10), 3)
4408 Decimal('3')
4409 >>> ExtendedContext.divide_int(10, Decimal(3))
4410 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004411 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004412 a = _convert_other(a, raiseit=True)
4413 r = a.__floordiv__(b, context=self)
4414 if r is NotImplemented:
4415 raise TypeError("Unable to convert %s to Decimal" % b)
4416 else:
4417 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004418
4419 def divmod(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004420 """Return (a // b, a % b).
Mark Dickinsonc53796e2010-01-06 16:22:15 +00004421
4422 >>> ExtendedContext.divmod(Decimal(8), Decimal(3))
4423 (Decimal('2'), Decimal('2'))
4424 >>> ExtendedContext.divmod(Decimal(8), Decimal(4))
4425 (Decimal('2'), Decimal('0'))
Mark Dickinson84230a12010-02-18 14:49:50 +00004426 >>> ExtendedContext.divmod(8, 4)
4427 (Decimal('2'), Decimal('0'))
4428 >>> ExtendedContext.divmod(Decimal(8), 4)
4429 (Decimal('2'), Decimal('0'))
4430 >>> ExtendedContext.divmod(8, Decimal(4))
4431 (Decimal('2'), Decimal('0'))
Mark Dickinsonc53796e2010-01-06 16:22:15 +00004432 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004433 a = _convert_other(a, raiseit=True)
4434 r = a.__divmod__(b, context=self)
4435 if r is NotImplemented:
4436 raise TypeError("Unable to convert %s to Decimal" % b)
4437 else:
4438 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004439
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004440 def exp(self, a):
4441 """Returns e ** a.
4442
4443 >>> c = ExtendedContext.copy()
4444 >>> c.Emin = -999
4445 >>> c.Emax = 999
4446 >>> c.exp(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004447 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004448 >>> c.exp(Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004449 Decimal('0.367879441')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004450 >>> c.exp(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004451 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004452 >>> c.exp(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004453 Decimal('2.71828183')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004454 >>> c.exp(Decimal('0.693147181'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004455 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004456 >>> c.exp(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004457 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004458 >>> c.exp(10)
4459 Decimal('22026.4658')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004460 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004461 a =_convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004462 return a.exp(context=self)
4463
4464 def fma(self, a, b, c):
4465 """Returns a multiplied by b, plus c.
4466
4467 The first two operands are multiplied together, using multiply,
4468 the third operand is then added to the result of that
4469 multiplication, using add, all with only one final rounding.
4470
4471 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004472 Decimal('22')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004473 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004474 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004475 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004476 Decimal('1.38435736E+12')
Mark Dickinson84230a12010-02-18 14:49:50 +00004477 >>> ExtendedContext.fma(1, 3, 4)
4478 Decimal('7')
4479 >>> ExtendedContext.fma(1, Decimal(3), 4)
4480 Decimal('7')
4481 >>> ExtendedContext.fma(1, 3, Decimal(4))
4482 Decimal('7')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004483 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004484 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004485 return a.fma(b, c, context=self)
4486
4487 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004488 """Return True if the operand is canonical; otherwise return False.
4489
4490 Currently, the encoding of a Decimal instance is always
4491 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004492
4493 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004494 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004495 """
Stefan Krah1919b7e2012-03-21 18:25:23 +01004496 if not isinstance(a, Decimal):
4497 raise TypeError("is_canonical requires a Decimal as an argument.")
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004498 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004499
4500 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004501 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004502
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004503 A Decimal instance is considered finite if it is neither
4504 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004505
4506 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004507 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004508 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004509 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004510 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004511 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004512 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004513 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004514 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004515 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004516 >>> ExtendedContext.is_finite(1)
4517 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004518 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004519 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004520 return a.is_finite()
4521
4522 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004523 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004524
4525 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004526 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004527 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004528 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004529 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004530 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004531 >>> ExtendedContext.is_infinite(1)
4532 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004533 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004534 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004535 return a.is_infinite()
4536
4537 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004538 """Return True if the operand is a qNaN or sNaN;
4539 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004540
4541 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004542 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004543 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004544 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004545 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004546 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004547 >>> ExtendedContext.is_nan(1)
4548 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004549 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004550 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004551 return a.is_nan()
4552
4553 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004554 """Return True if the operand is a normal number;
4555 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004556
4557 >>> c = ExtendedContext.copy()
4558 >>> c.Emin = -999
4559 >>> c.Emax = 999
4560 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004561 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004562 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004563 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004564 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004565 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004566 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004567 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004568 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004569 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004570 >>> c.is_normal(1)
4571 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004572 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004573 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004574 return a.is_normal(context=self)
4575
4576 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004577 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004578
4579 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004580 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004581 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004582 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004583 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004584 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004585 >>> ExtendedContext.is_qnan(1)
4586 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004587 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004588 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004589 return a.is_qnan()
4590
4591 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004592 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004593
4594 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004595 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004596 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004597 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004598 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004599 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004600 >>> ExtendedContext.is_signed(8)
4601 False
4602 >>> ExtendedContext.is_signed(-8)
4603 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004604 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004605 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004606 return a.is_signed()
4607
4608 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004609 """Return True if the operand is a signaling NaN;
4610 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004611
4612 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004613 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004614 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004615 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004616 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004617 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004618 >>> ExtendedContext.is_snan(1)
4619 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004620 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004621 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004622 return a.is_snan()
4623
4624 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004625 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004626
4627 >>> c = ExtendedContext.copy()
4628 >>> c.Emin = -999
4629 >>> c.Emax = 999
4630 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004631 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004632 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004633 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004634 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004635 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004636 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004637 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004638 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004639 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004640 >>> c.is_subnormal(1)
4641 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004642 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004643 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004644 return a.is_subnormal(context=self)
4645
4646 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004647 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004648
4649 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004650 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004651 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004652 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004653 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004654 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004655 >>> ExtendedContext.is_zero(1)
4656 False
4657 >>> ExtendedContext.is_zero(0)
4658 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004659 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004660 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004661 return a.is_zero()
4662
4663 def ln(self, a):
4664 """Returns the natural (base e) logarithm of the operand.
4665
4666 >>> c = ExtendedContext.copy()
4667 >>> c.Emin = -999
4668 >>> c.Emax = 999
4669 >>> c.ln(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004670 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004671 >>> c.ln(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004672 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004673 >>> c.ln(Decimal('2.71828183'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004674 Decimal('1.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004675 >>> c.ln(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004676 Decimal('2.30258509')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004677 >>> c.ln(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004678 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004679 >>> c.ln(1)
4680 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004681 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004682 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004683 return a.ln(context=self)
4684
4685 def log10(self, a):
4686 """Returns the base 10 logarithm of the operand.
4687
4688 >>> c = ExtendedContext.copy()
4689 >>> c.Emin = -999
4690 >>> c.Emax = 999
4691 >>> c.log10(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004692 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004693 >>> c.log10(Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004694 Decimal('-3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004695 >>> c.log10(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004696 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004697 >>> c.log10(Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004698 Decimal('0.301029996')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004699 >>> c.log10(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004700 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004701 >>> c.log10(Decimal('70'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004702 Decimal('1.84509804')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004703 >>> c.log10(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004704 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004705 >>> c.log10(0)
4706 Decimal('-Infinity')
4707 >>> c.log10(1)
4708 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004709 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004710 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004711 return a.log10(context=self)
4712
4713 def logb(self, a):
4714 """ Returns the exponent of the magnitude of the operand's MSD.
4715
4716 The result is the integer which is the exponent of the magnitude
4717 of the most significant digit of the operand (as though the
4718 operand were truncated to a single digit while maintaining the
4719 value of that digit and without limiting the resulting exponent).
4720
4721 >>> ExtendedContext.logb(Decimal('250'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004722 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004723 >>> ExtendedContext.logb(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004724 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004725 >>> ExtendedContext.logb(Decimal('0.03'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004726 Decimal('-2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004727 >>> ExtendedContext.logb(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004728 Decimal('-Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004729 >>> ExtendedContext.logb(1)
4730 Decimal('0')
4731 >>> ExtendedContext.logb(10)
4732 Decimal('1')
4733 >>> ExtendedContext.logb(100)
4734 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004735 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004736 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004737 return a.logb(context=self)
4738
4739 def logical_and(self, a, b):
4740 """Applies the logical operation 'and' between each operand's digits.
4741
4742 The operands must be both logical numbers.
4743
4744 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004745 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004746 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004747 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004748 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004749 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004750 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004751 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004752 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004753 Decimal('1000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004754 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004755 Decimal('10')
Mark Dickinson84230a12010-02-18 14:49:50 +00004756 >>> ExtendedContext.logical_and(110, 1101)
4757 Decimal('100')
4758 >>> ExtendedContext.logical_and(Decimal(110), 1101)
4759 Decimal('100')
4760 >>> ExtendedContext.logical_and(110, Decimal(1101))
4761 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004762 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004763 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004764 return a.logical_and(b, context=self)
4765
4766 def logical_invert(self, a):
4767 """Invert all the digits in the operand.
4768
4769 The operand must be a logical number.
4770
4771 >>> ExtendedContext.logical_invert(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004772 Decimal('111111111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004773 >>> ExtendedContext.logical_invert(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004774 Decimal('111111110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004775 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004776 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004777 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004778 Decimal('10101010')
Mark Dickinson84230a12010-02-18 14:49:50 +00004779 >>> ExtendedContext.logical_invert(1101)
4780 Decimal('111110010')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004781 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004782 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004783 return a.logical_invert(context=self)
4784
4785 def logical_or(self, a, b):
4786 """Applies the logical operation 'or' between each operand's digits.
4787
4788 The operands must be both logical numbers.
4789
4790 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004791 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004792 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004793 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004794 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004795 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004796 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004797 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004798 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004799 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004800 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004801 Decimal('1110')
Mark Dickinson84230a12010-02-18 14:49:50 +00004802 >>> ExtendedContext.logical_or(110, 1101)
4803 Decimal('1111')
4804 >>> ExtendedContext.logical_or(Decimal(110), 1101)
4805 Decimal('1111')
4806 >>> ExtendedContext.logical_or(110, Decimal(1101))
4807 Decimal('1111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004808 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004809 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004810 return a.logical_or(b, context=self)
4811
4812 def logical_xor(self, a, b):
4813 """Applies the logical operation 'xor' between each operand's digits.
4814
4815 The operands must be both logical numbers.
4816
4817 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004818 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004819 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004820 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004821 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004822 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004823 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004824 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004825 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004826 Decimal('110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004827 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004828 Decimal('1101')
Mark Dickinson84230a12010-02-18 14:49:50 +00004829 >>> ExtendedContext.logical_xor(110, 1101)
4830 Decimal('1011')
4831 >>> ExtendedContext.logical_xor(Decimal(110), 1101)
4832 Decimal('1011')
4833 >>> ExtendedContext.logical_xor(110, Decimal(1101))
4834 Decimal('1011')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004835 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004836 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004837 return a.logical_xor(b, context=self)
4838
Mark Dickinson84230a12010-02-18 14:49:50 +00004839 def max(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004840 """max compares two values numerically and returns the maximum.
4841
4842 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004843 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004844 operation. If they are numerically equal then the left-hand operand
4845 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004846 infinity) of the two operands is chosen as the result.
4847
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004848 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004849 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004850 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004851 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004852 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004853 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004854 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004855 Decimal('7')
Mark Dickinson84230a12010-02-18 14:49:50 +00004856 >>> ExtendedContext.max(1, 2)
4857 Decimal('2')
4858 >>> ExtendedContext.max(Decimal(1), 2)
4859 Decimal('2')
4860 >>> ExtendedContext.max(1, Decimal(2))
4861 Decimal('2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004862 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004863 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004864 return a.max(b, context=self)
4865
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004866 def max_mag(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004867 """Compares the values numerically with their sign ignored.
4868
4869 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
4870 Decimal('7')
4871 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
4872 Decimal('-10')
4873 >>> ExtendedContext.max_mag(1, -2)
4874 Decimal('-2')
4875 >>> ExtendedContext.max_mag(Decimal(1), -2)
4876 Decimal('-2')
4877 >>> ExtendedContext.max_mag(1, Decimal(-2))
4878 Decimal('-2')
4879 """
4880 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004881 return a.max_mag(b, context=self)
4882
Mark Dickinson84230a12010-02-18 14:49:50 +00004883 def min(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004884 """min compares two values numerically and returns the minimum.
4885
4886 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004887 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004888 operation. If they are numerically equal then the left-hand operand
4889 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004890 infinity) of the two operands is chosen as the result.
4891
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004892 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004893 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004894 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004895 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004896 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004897 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004898 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004899 Decimal('7')
Mark Dickinson84230a12010-02-18 14:49:50 +00004900 >>> ExtendedContext.min(1, 2)
4901 Decimal('1')
4902 >>> ExtendedContext.min(Decimal(1), 2)
4903 Decimal('1')
4904 >>> ExtendedContext.min(1, Decimal(29))
4905 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004906 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004907 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004908 return a.min(b, context=self)
4909
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004910 def min_mag(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004911 """Compares the values numerically with their sign ignored.
4912
4913 >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2'))
4914 Decimal('-2')
4915 >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN'))
4916 Decimal('-3')
4917 >>> ExtendedContext.min_mag(1, -2)
4918 Decimal('1')
4919 >>> ExtendedContext.min_mag(Decimal(1), -2)
4920 Decimal('1')
4921 >>> ExtendedContext.min_mag(1, Decimal(-2))
4922 Decimal('1')
4923 """
4924 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004925 return a.min_mag(b, context=self)
4926
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004927 def minus(self, a):
4928 """Minus corresponds to unary prefix minus in Python.
4929
4930 The operation is evaluated using the same rules as subtract; the
4931 operation minus(a) is calculated as subtract('0', a) where the '0'
4932 has the same exponent as the operand.
4933
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004934 >>> ExtendedContext.minus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004935 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004936 >>> ExtendedContext.minus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004937 Decimal('1.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004938 >>> ExtendedContext.minus(1)
4939 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004940 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004941 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004942 return a.__neg__(context=self)
4943
4944 def multiply(self, a, b):
4945 """multiply multiplies two operands.
4946
4947 If either operand is a special value then the general rules apply.
Mark Dickinson84230a12010-02-18 14:49:50 +00004948 Otherwise, the operands are multiplied together
4949 ('long multiplication'), resulting in a number which may be as long as
4950 the sum of the lengths of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004951
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004952 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004953 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004954 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004955 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004956 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004957 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004958 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004959 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004960 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004961 Decimal('4.28135971E+11')
Mark Dickinson84230a12010-02-18 14:49:50 +00004962 >>> ExtendedContext.multiply(7, 7)
4963 Decimal('49')
4964 >>> ExtendedContext.multiply(Decimal(7), 7)
4965 Decimal('49')
4966 >>> ExtendedContext.multiply(7, Decimal(7))
4967 Decimal('49')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004968 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004969 a = _convert_other(a, raiseit=True)
4970 r = a.__mul__(b, context=self)
4971 if r is NotImplemented:
4972 raise TypeError("Unable to convert %s to Decimal" % b)
4973 else:
4974 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004975
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004976 def next_minus(self, a):
4977 """Returns the largest representable number smaller than a.
4978
4979 >>> c = ExtendedContext.copy()
4980 >>> c.Emin = -999
4981 >>> c.Emax = 999
4982 >>> ExtendedContext.next_minus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004983 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004984 >>> c.next_minus(Decimal('1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004985 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004986 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004987 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004988 >>> c.next_minus(Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004989 Decimal('9.99999999E+999')
Mark Dickinson84230a12010-02-18 14:49:50 +00004990 >>> c.next_minus(1)
4991 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004992 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004993 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004994 return a.next_minus(context=self)
4995
4996 def next_plus(self, a):
4997 """Returns the smallest representable number larger than a.
4998
4999 >>> c = ExtendedContext.copy()
5000 >>> c.Emin = -999
5001 >>> c.Emax = 999
5002 >>> ExtendedContext.next_plus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005003 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005004 >>> c.next_plus(Decimal('-1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005005 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005006 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005007 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005008 >>> c.next_plus(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005009 Decimal('-9.99999999E+999')
Mark Dickinson84230a12010-02-18 14:49:50 +00005010 >>> c.next_plus(1)
5011 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005012 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005013 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005014 return a.next_plus(context=self)
5015
5016 def next_toward(self, a, b):
5017 """Returns the number closest to a, in direction towards b.
5018
5019 The result is the closest representable number from the first
5020 operand (but not the first operand) that is in the direction
5021 towards the second operand, unless the operands have the same
5022 value.
5023
5024 >>> c = ExtendedContext.copy()
5025 >>> c.Emin = -999
5026 >>> c.Emax = 999
5027 >>> c.next_toward(Decimal('1'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005028 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005029 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005030 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005031 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005032 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005033 >>> c.next_toward(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005034 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005035 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005036 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005037 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005038 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005039 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005040 Decimal('-0.00')
Mark Dickinson84230a12010-02-18 14:49:50 +00005041 >>> c.next_toward(0, 1)
5042 Decimal('1E-1007')
5043 >>> c.next_toward(Decimal(0), 1)
5044 Decimal('1E-1007')
5045 >>> c.next_toward(0, Decimal(1))
5046 Decimal('1E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005047 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005048 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005049 return a.next_toward(b, context=self)
5050
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005051 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00005052 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005053
5054 Essentially a plus operation with all trailing zeros removed from the
5055 result.
5056
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005057 >>> ExtendedContext.normalize(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005058 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005059 >>> ExtendedContext.normalize(Decimal('-2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005060 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005061 >>> ExtendedContext.normalize(Decimal('1.200'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005062 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005063 >>> ExtendedContext.normalize(Decimal('-120'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005064 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005065 >>> ExtendedContext.normalize(Decimal('120.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005066 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005067 >>> ExtendedContext.normalize(Decimal('0.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005068 Decimal('0')
Mark Dickinson84230a12010-02-18 14:49:50 +00005069 >>> ExtendedContext.normalize(6)
5070 Decimal('6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005071 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005072 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005073 return a.normalize(context=self)
5074
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005075 def number_class(self, a):
5076 """Returns an indication of the class of the operand.
5077
5078 The class is one of the following strings:
5079 -sNaN
5080 -NaN
5081 -Infinity
5082 -Normal
5083 -Subnormal
5084 -Zero
5085 +Zero
5086 +Subnormal
5087 +Normal
5088 +Infinity
5089
Stefan Krah1919b7e2012-03-21 18:25:23 +01005090 >>> c = ExtendedContext.copy()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005091 >>> c.Emin = -999
5092 >>> c.Emax = 999
5093 >>> c.number_class(Decimal('Infinity'))
5094 '+Infinity'
5095 >>> c.number_class(Decimal('1E-10'))
5096 '+Normal'
5097 >>> c.number_class(Decimal('2.50'))
5098 '+Normal'
5099 >>> c.number_class(Decimal('0.1E-999'))
5100 '+Subnormal'
5101 >>> c.number_class(Decimal('0'))
5102 '+Zero'
5103 >>> c.number_class(Decimal('-0'))
5104 '-Zero'
5105 >>> c.number_class(Decimal('-0.1E-999'))
5106 '-Subnormal'
5107 >>> c.number_class(Decimal('-1E-10'))
5108 '-Normal'
5109 >>> c.number_class(Decimal('-2.50'))
5110 '-Normal'
5111 >>> c.number_class(Decimal('-Infinity'))
5112 '-Infinity'
5113 >>> c.number_class(Decimal('NaN'))
5114 'NaN'
5115 >>> c.number_class(Decimal('-NaN'))
5116 'NaN'
5117 >>> c.number_class(Decimal('sNaN'))
5118 'sNaN'
Mark Dickinson84230a12010-02-18 14:49:50 +00005119 >>> c.number_class(123)
5120 '+Normal'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005121 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005122 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005123 return a.number_class(context=self)
5124
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005125 def plus(self, a):
5126 """Plus corresponds to unary prefix plus in Python.
5127
5128 The operation is evaluated using the same rules as add; the
5129 operation plus(a) is calculated as add('0', a) where the '0'
5130 has the same exponent as the operand.
5131
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005132 >>> ExtendedContext.plus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005133 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005134 >>> ExtendedContext.plus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005135 Decimal('-1.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005136 >>> ExtendedContext.plus(-1)
5137 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005138 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005139 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005140 return a.__pos__(context=self)
5141
5142 def power(self, a, b, modulo=None):
5143 """Raises a to the power of b, to modulo if given.
5144
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005145 With two arguments, compute a**b. If a is negative then b
5146 must be integral. The result will be inexact unless b is
5147 integral and the result is finite and can be expressed exactly
5148 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005149
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005150 With three arguments, compute (a**b) % modulo. For the
5151 three argument form, the following restrictions on the
5152 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005153
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005154 - all three arguments must be integral
5155 - b must be nonnegative
5156 - at least one of a or b must be nonzero
5157 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005158
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005159 The result of pow(a, b, modulo) is identical to the result
5160 that would be obtained by computing (a**b) % modulo with
5161 unbounded precision, but is computed more efficiently. It is
5162 always exact.
5163
5164 >>> c = ExtendedContext.copy()
5165 >>> c.Emin = -999
5166 >>> c.Emax = 999
5167 >>> c.power(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005168 Decimal('8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005169 >>> c.power(Decimal('-2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005170 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005171 >>> c.power(Decimal('2'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005172 Decimal('0.125')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005173 >>> c.power(Decimal('1.7'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005174 Decimal('69.7575744')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005175 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005176 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005177 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005178 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005179 >>> c.power(Decimal('Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005180 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005181 >>> c.power(Decimal('Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005182 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005183 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005184 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005185 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005186 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005187 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005188 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005189 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005190 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005191 >>> c.power(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005192 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005193
5194 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005195 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005196 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005197 Decimal('-11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005198 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005199 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005200 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005201 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005202 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005203 Decimal('11729830')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005204 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005205 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005206 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005207 Decimal('1')
Mark Dickinson84230a12010-02-18 14:49:50 +00005208 >>> ExtendedContext.power(7, 7)
5209 Decimal('823543')
5210 >>> ExtendedContext.power(Decimal(7), 7)
5211 Decimal('823543')
5212 >>> ExtendedContext.power(7, Decimal(7), 2)
5213 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005214 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005215 a = _convert_other(a, raiseit=True)
5216 r = a.__pow__(b, modulo, context=self)
5217 if r is NotImplemented:
5218 raise TypeError("Unable to convert %s to Decimal" % b)
5219 else:
5220 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005221
5222 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005223 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005224
5225 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00005226 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005227 exponent is being increased), multiplied by a positive power of ten (if
5228 the exponent is being decreased), or is unchanged (if the exponent is
5229 already equal to that of the right-hand operand).
5230
5231 Unlike other operations, if the length of the coefficient after the
5232 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00005233 operation condition is raised. This guarantees that, unless there is
5234 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005235 equal to that of the right-hand operand.
5236
5237 Also unlike other operations, quantize will never raise Underflow, even
5238 if the result is subnormal and inexact.
5239
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005240 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005241 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005242 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005243 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005244 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005245 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005246 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005247 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005248 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005249 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005250 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005251 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005252 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005253 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005254 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005255 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005256 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005257 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005258 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005259 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005260 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005261 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005262 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005263 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005264 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005265 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005266 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005267 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005268 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005269 Decimal('2E+2')
Mark Dickinson84230a12010-02-18 14:49:50 +00005270 >>> ExtendedContext.quantize(1, 2)
5271 Decimal('1')
5272 >>> ExtendedContext.quantize(Decimal(1), 2)
5273 Decimal('1')
5274 >>> ExtendedContext.quantize(1, Decimal(2))
5275 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005276 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005277 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005278 return a.quantize(b, context=self)
5279
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005280 def radix(self):
5281 """Just returns 10, as this is Decimal, :)
5282
5283 >>> ExtendedContext.radix()
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005284 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005285 """
5286 return Decimal(10)
5287
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005288 def remainder(self, a, b):
5289 """Returns the remainder from integer division.
5290
5291 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00005292 calculating integer division as described for divide-integer, rounded
5293 to precision digits if necessary. The sign of the result, if
5294 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005295
5296 This operation will fail under the same conditions as integer division
5297 (that is, if integer division on the same two operands would fail, the
5298 remainder cannot be calculated).
5299
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005300 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005301 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005302 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005303 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005304 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005305 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005306 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005307 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005308 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005309 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005310 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005311 Decimal('1.0')
Mark Dickinson84230a12010-02-18 14:49:50 +00005312 >>> ExtendedContext.remainder(22, 6)
5313 Decimal('4')
5314 >>> ExtendedContext.remainder(Decimal(22), 6)
5315 Decimal('4')
5316 >>> ExtendedContext.remainder(22, Decimal(6))
5317 Decimal('4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005318 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005319 a = _convert_other(a, raiseit=True)
5320 r = a.__mod__(b, context=self)
5321 if r is NotImplemented:
5322 raise TypeError("Unable to convert %s to Decimal" % b)
5323 else:
5324 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005325
5326 def remainder_near(self, a, b):
5327 """Returns to be "a - b * n", where n is the integer nearest the exact
5328 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00005329 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005330 sign of a.
5331
5332 This operation will fail under the same conditions as integer division
5333 (that is, if integer division on the same two operands would fail, the
5334 remainder cannot be calculated).
5335
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005336 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005337 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005338 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005339 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005340 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005341 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005342 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005343 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005344 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005345 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005346 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005347 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005348 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005349 Decimal('-0.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005350 >>> ExtendedContext.remainder_near(3, 11)
5351 Decimal('3')
5352 >>> ExtendedContext.remainder_near(Decimal(3), 11)
5353 Decimal('3')
5354 >>> ExtendedContext.remainder_near(3, Decimal(11))
5355 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005356 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005357 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005358 return a.remainder_near(b, context=self)
5359
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005360 def rotate(self, a, b):
5361 """Returns a rotated copy of a, b times.
5362
5363 The coefficient of the result is a rotated copy of the digits in
5364 the coefficient of the first operand. The number of places of
5365 rotation is taken from the absolute value of the second operand,
5366 with the rotation being to the left if the second operand is
5367 positive or to the right otherwise.
5368
5369 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005370 Decimal('400000003')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005371 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005372 Decimal('12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005373 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005374 Decimal('891234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005375 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005376 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005377 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005378 Decimal('345678912')
Mark Dickinson84230a12010-02-18 14:49:50 +00005379 >>> ExtendedContext.rotate(1333333, 1)
5380 Decimal('13333330')
5381 >>> ExtendedContext.rotate(Decimal(1333333), 1)
5382 Decimal('13333330')
5383 >>> ExtendedContext.rotate(1333333, Decimal(1))
5384 Decimal('13333330')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005385 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005386 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005387 return a.rotate(b, context=self)
5388
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005389 def same_quantum(self, a, b):
5390 """Returns True if the two operands have the same exponent.
5391
5392 The result is never affected by either the sign or the coefficient of
5393 either operand.
5394
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005395 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005396 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005397 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005398 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005399 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005400 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005401 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005402 True
Mark Dickinson84230a12010-02-18 14:49:50 +00005403 >>> ExtendedContext.same_quantum(10000, -1)
5404 True
5405 >>> ExtendedContext.same_quantum(Decimal(10000), -1)
5406 True
5407 >>> ExtendedContext.same_quantum(10000, Decimal(-1))
5408 True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005409 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005410 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005411 return a.same_quantum(b)
5412
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005413 def scaleb (self, a, b):
5414 """Returns the first operand after adding the second value its exp.
5415
5416 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005417 Decimal('0.0750')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005418 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005419 Decimal('7.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005420 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005421 Decimal('7.50E+3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005422 >>> ExtendedContext.scaleb(1, 4)
5423 Decimal('1E+4')
5424 >>> ExtendedContext.scaleb(Decimal(1), 4)
5425 Decimal('1E+4')
5426 >>> ExtendedContext.scaleb(1, Decimal(4))
5427 Decimal('1E+4')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005428 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005429 a = _convert_other(a, raiseit=True)
5430 return a.scaleb(b, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005431
5432 def shift(self, a, b):
5433 """Returns a shifted copy of a, b times.
5434
5435 The coefficient of the result is a shifted copy of the digits
5436 in the coefficient of the first operand. The number of places
5437 to shift is taken from the absolute value of the second operand,
5438 with the shift being to the left if the second operand is
5439 positive or to the right otherwise. Digits shifted into the
5440 coefficient are zeros.
5441
5442 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005443 Decimal('400000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005444 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005445 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005446 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005447 Decimal('1234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005448 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005449 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005450 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005451 Decimal('345678900')
Mark Dickinson84230a12010-02-18 14:49:50 +00005452 >>> ExtendedContext.shift(88888888, 2)
5453 Decimal('888888800')
5454 >>> ExtendedContext.shift(Decimal(88888888), 2)
5455 Decimal('888888800')
5456 >>> ExtendedContext.shift(88888888, Decimal(2))
5457 Decimal('888888800')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005458 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005459 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005460 return a.shift(b, context=self)
5461
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005462 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005463 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005464
5465 If the result must be inexact, it is rounded using the round-half-even
5466 algorithm.
5467
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005468 >>> ExtendedContext.sqrt(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005469 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005470 >>> ExtendedContext.sqrt(Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005471 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005472 >>> ExtendedContext.sqrt(Decimal('0.39'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005473 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005474 >>> ExtendedContext.sqrt(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005475 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005476 >>> ExtendedContext.sqrt(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005477 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005478 >>> ExtendedContext.sqrt(Decimal('1.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005479 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005480 >>> ExtendedContext.sqrt(Decimal('1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005481 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005482 >>> ExtendedContext.sqrt(Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005483 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005484 >>> ExtendedContext.sqrt(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005485 Decimal('3.16227766')
Mark Dickinson84230a12010-02-18 14:49:50 +00005486 >>> ExtendedContext.sqrt(2)
5487 Decimal('1.41421356')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005488 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005489 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005490 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005491 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005492 return a.sqrt(context=self)
5493
5494 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00005495 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005496
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005497 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005498 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005499 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005500 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005501 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005502 Decimal('-0.77')
Mark Dickinson84230a12010-02-18 14:49:50 +00005503 >>> ExtendedContext.subtract(8, 5)
5504 Decimal('3')
5505 >>> ExtendedContext.subtract(Decimal(8), 5)
5506 Decimal('3')
5507 >>> ExtendedContext.subtract(8, Decimal(5))
5508 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005509 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005510 a = _convert_other(a, raiseit=True)
5511 r = a.__sub__(b, context=self)
5512 if r is NotImplemented:
5513 raise TypeError("Unable to convert %s to Decimal" % b)
5514 else:
5515 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005516
5517 def to_eng_string(self, a):
5518 """Converts a number to a string, using scientific notation.
5519
5520 The operation is not affected by the context.
5521 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005522 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005523 return a.to_eng_string(context=self)
5524
5525 def to_sci_string(self, a):
5526 """Converts a number to a string, using scientific notation.
5527
5528 The operation is not affected by the context.
5529 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005530 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005531 return a.__str__(context=self)
5532
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005533 def to_integral_exact(self, a):
5534 """Rounds to an integer.
5535
5536 When the operand has a negative exponent, the result is the same
5537 as using the quantize() operation using the given operand as the
5538 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5539 of the operand as the precision setting; Inexact and Rounded flags
5540 are allowed in this operation. The rounding mode is taken from the
5541 context.
5542
5543 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005544 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005545 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005546 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005547 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005548 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005549 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005550 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005551 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005552 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005553 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005554 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005555 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005556 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005557 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005558 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005559 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005560 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005561 return a.to_integral_exact(context=self)
5562
5563 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005564 """Rounds to an integer.
5565
5566 When the operand has a negative exponent, the result is the same
5567 as using the quantize() operation using the given operand as the
5568 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5569 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00005570 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005571
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005572 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005573 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005574 >>> ExtendedContext.to_integral_value(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005575 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005576 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005577 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005578 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005579 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005580 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005581 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005582 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005583 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005584 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005585 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005586 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005587 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005588 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005589 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005590 return a.to_integral_value(context=self)
5591
5592 # the method name changed, but we provide also the old one, for compatibility
5593 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005594
5595class _WorkRep(object):
5596 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00005597 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005598 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005599 # exp: None, int, or string
5600
5601 def __init__(self, value=None):
5602 if value is None:
5603 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005604 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005605 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00005606 elif isinstance(value, Decimal):
5607 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005608 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005609 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00005610 else:
5611 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005612 self.sign = value[0]
5613 self.int = value[1]
5614 self.exp = value[2]
5615
5616 def __repr__(self):
5617 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5618
5619 __str__ = __repr__
5620
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005621
5622
Christian Heimes2c181612007-12-17 20:04:13 +00005623def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005624 """Normalizes op1, op2 to have the same exp and length of coefficient.
5625
5626 Done during addition.
5627 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005628 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005629 tmp = op2
5630 other = op1
5631 else:
5632 tmp = op1
5633 other = op2
5634
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005635 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5636 # Then adding 10**exp to tmp has the same effect (after rounding)
5637 # as adding any positive quantity smaller than 10**exp; similarly
5638 # for subtraction. So if other is smaller than 10**exp we replace
5639 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00005640 tmp_len = len(str(tmp.int))
5641 other_len = len(str(other.int))
5642 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5643 if other_len + other.exp - 1 < exp:
5644 other.int = 1
5645 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005646
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005647 tmp.int *= 10 ** (tmp.exp - other.exp)
5648 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005649 return op1, op2
5650
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005651##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005652
Raymond Hettingerdb213a22010-11-27 08:09:40 +00005653_nbits = int.bit_length
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005654
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01005655def _decimal_lshift_exact(n, e):
5656 """ Given integers n and e, return n * 10**e if it's an integer, else None.
5657
5658 The computation is designed to avoid computing large powers of 10
5659 unnecessarily.
5660
5661 >>> _decimal_lshift_exact(3, 4)
5662 30000
5663 >>> _decimal_lshift_exact(300, -999999999) # returns None
5664
5665 """
5666 if n == 0:
5667 return 0
5668 elif e >= 0:
5669 return n * 10**e
5670 else:
5671 # val_n = largest power of 10 dividing n.
5672 str_n = str(abs(n))
5673 val_n = len(str_n) - len(str_n.rstrip('0'))
5674 return None if val_n < -e else n // 10**-e
5675
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005676def _sqrt_nearest(n, a):
5677 """Closest integer to the square root of the positive integer n. a is
5678 an initial approximation to the square root. Any positive integer
5679 will do for a, but the closer a is to the square root of n the
5680 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005681
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005682 """
5683 if n <= 0 or a <= 0:
5684 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5685
5686 b=0
5687 while a != b:
5688 b, a = a, a--n//a>>1
5689 return a
5690
5691def _rshift_nearest(x, shift):
5692 """Given an integer x and a nonnegative integer shift, return closest
5693 integer to x / 2**shift; use round-to-even in case of a tie.
5694
5695 """
5696 b, q = 1 << shift, x >> shift
5697 return q + (2*(x & (b-1)) + (q&1) > b)
5698
5699def _div_nearest(a, b):
5700 """Closest integer to a/b, a and b positive integers; rounds to even
5701 in the case of a tie.
5702
5703 """
5704 q, r = divmod(a, b)
5705 return q + (2*r + (q&1) > b)
5706
5707def _ilog(x, M, L = 8):
5708 """Integer approximation to M*log(x/M), with absolute error boundable
5709 in terms only of x/M.
5710
5711 Given positive integers x and M, return an integer approximation to
5712 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5713 between the approximation and the exact result is at most 22. For
5714 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5715 both cases these are upper bounds on the error; it will usually be
5716 much smaller."""
5717
5718 # The basic algorithm is the following: let log1p be the function
5719 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5720 # the reduction
5721 #
5722 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5723 #
5724 # repeatedly until the argument to log1p is small (< 2**-L in
5725 # absolute value). For small y we can use the Taylor series
5726 # expansion
5727 #
5728 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5729 #
5730 # truncating at T such that y**T is small enough. The whole
5731 # computation is carried out in a form of fixed-point arithmetic,
5732 # with a real number z being represented by an integer
5733 # approximation to z*M. To avoid loss of precision, the y below
5734 # is actually an integer approximation to 2**R*y*M, where R is the
5735 # number of reductions performed so far.
5736
5737 y = x-M
5738 # argument reduction; R = number of reductions performed
5739 R = 0
5740 while (R <= L and abs(y) << L-R >= M or
5741 R > L and abs(y) >> R-L >= M):
5742 y = _div_nearest((M*y) << 1,
5743 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5744 R += 1
5745
5746 # Taylor series with T terms
5747 T = -int(-10*len(str(M))//(3*L))
5748 yshift = _rshift_nearest(y, R)
5749 w = _div_nearest(M, T)
5750 for k in range(T-1, 0, -1):
5751 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5752
5753 return _div_nearest(w*y, M)
5754
5755def _dlog10(c, e, p):
5756 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5757 approximation to 10**p * log10(c*10**e), with an absolute error of
5758 at most 1. Assumes that c*10**e is not exactly 1."""
5759
5760 # increase precision by 2; compensate for this by dividing
5761 # final result by 100
5762 p += 2
5763
5764 # write c*10**e as d*10**f with either:
5765 # f >= 0 and 1 <= d <= 10, or
5766 # f <= 0 and 0.1 <= d <= 1.
5767 # Thus for c*10**e close to 1, f = 0
5768 l = len(str(c))
5769 f = e+l - (e+l >= 1)
5770
5771 if p > 0:
5772 M = 10**p
5773 k = e+p-f
5774 if k >= 0:
5775 c *= 10**k
5776 else:
5777 c = _div_nearest(c, 10**-k)
5778
5779 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005780 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005781 log_d = _div_nearest(log_d*M, log_10)
5782 log_tenpower = f*M # exact
5783 else:
5784 log_d = 0 # error < 2.31
Neal Norwitz2f99b242008-08-24 05:48:10 +00005785 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005786
5787 return _div_nearest(log_tenpower+log_d, 100)
5788
5789def _dlog(c, e, p):
5790 """Given integers c, e and p with c > 0, compute an integer
5791 approximation to 10**p * log(c*10**e), with an absolute error of
5792 at most 1. Assumes that c*10**e is not exactly 1."""
5793
5794 # Increase precision by 2. The precision increase is compensated
5795 # for at the end with a division by 100.
5796 p += 2
5797
5798 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5799 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5800 # as 10**p * log(d) + 10**p*f * log(10).
5801 l = len(str(c))
5802 f = e+l - (e+l >= 1)
5803
5804 # compute approximation to 10**p*log(d), with error < 27
5805 if p > 0:
5806 k = e+p-f
5807 if k >= 0:
5808 c *= 10**k
5809 else:
5810 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5811
5812 # _ilog magnifies existing error in c by a factor of at most 10
5813 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5814 else:
5815 # p <= 0: just approximate the whole thing by 0; error < 2.31
5816 log_d = 0
5817
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005818 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005819 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005820 extra = len(str(abs(f)))-1
5821 if p + extra >= 0:
5822 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5823 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5824 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005825 else:
5826 f_log_ten = 0
5827 else:
5828 f_log_ten = 0
5829
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005830 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005831 return _div_nearest(f_log_ten + log_d, 100)
5832
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005833class _Log10Memoize(object):
5834 """Class to compute, store, and allow retrieval of, digits of the
5835 constant log(10) = 2.302585.... This constant is needed by
5836 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5837 def __init__(self):
5838 self.digits = "23025850929940456840179914546843642076011014886"
5839
5840 def getdigits(self, p):
5841 """Given an integer p >= 0, return floor(10**p)*log(10).
5842
5843 For example, self.getdigits(3) returns 2302.
5844 """
5845 # digits are stored as a string, for quick conversion to
5846 # integer in the case that we've already computed enough
5847 # digits; the stored digits should always be correct
5848 # (truncated, not rounded to nearest).
5849 if p < 0:
5850 raise ValueError("p should be nonnegative")
5851
5852 if p >= len(self.digits):
5853 # compute p+3, p+6, p+9, ... digits; continue until at
5854 # least one of the extra digits is nonzero
5855 extra = 3
5856 while True:
5857 # compute p+extra digits, correct to within 1ulp
5858 M = 10**(p+extra+2)
5859 digits = str(_div_nearest(_ilog(10*M, M), 100))
5860 if digits[-extra:] != '0'*extra:
5861 break
5862 extra += 3
5863 # keep all reliable digits so far; remove trailing zeros
5864 # and next nonzero digit
5865 self.digits = digits.rstrip('0')[:-1]
5866 return int(self.digits[:p+1])
5867
5868_log10_digits = _Log10Memoize().getdigits
5869
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005870def _iexp(x, M, L=8):
5871 """Given integers x and M, M > 0, such that x/M is small in absolute
5872 value, compute an integer approximation to M*exp(x/M). For 0 <=
5873 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5874 is usually much smaller)."""
5875
5876 # Algorithm: to compute exp(z) for a real number z, first divide z
5877 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5878 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5879 # series
5880 #
5881 # expm1(x) = x + x**2/2! + x**3/3! + ...
5882 #
5883 # Now use the identity
5884 #
5885 # expm1(2x) = expm1(x)*(expm1(x)+2)
5886 #
5887 # R times to compute the sequence expm1(z/2**R),
5888 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5889
5890 # Find R such that x/2**R/M <= 2**-L
5891 R = _nbits((x<<L)//M)
5892
5893 # Taylor series. (2**L)**T > M
5894 T = -int(-10*len(str(M))//(3*L))
5895 y = _div_nearest(x, T)
5896 Mshift = M<<R
5897 for i in range(T-1, 0, -1):
5898 y = _div_nearest(x*(Mshift + y), Mshift * i)
5899
5900 # Expansion
5901 for k in range(R-1, -1, -1):
5902 Mshift = M<<(k+2)
5903 y = _div_nearest(y*(y+Mshift), Mshift)
5904
5905 return M+y
5906
5907def _dexp(c, e, p):
5908 """Compute an approximation to exp(c*10**e), with p decimal places of
5909 precision.
5910
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005911 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005912
5913 10**(p-1) <= d <= 10**p, and
5914 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5915
5916 In other words, d*10**f is an approximation to exp(c*10**e) with p
5917 digits of precision, and with an error in d of at most 1. This is
5918 almost, but not quite, the same as the error being < 1ulp: when d
5919 = 10**(p-1) the error could be up to 10 ulp."""
5920
5921 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5922 p += 2
5923
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005924 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005925 extra = max(0, e + len(str(c)) - 1)
5926 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005927
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005928 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005929 # rounding down
5930 shift = e+q
5931 if shift >= 0:
5932 cshift = c*10**shift
5933 else:
5934 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005935 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005936
5937 # reduce remainder back to original precision
5938 rem = _div_nearest(rem, 10**extra)
5939
5940 # error in result of _iexp < 120; error after division < 0.62
5941 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5942
5943def _dpower(xc, xe, yc, ye, p):
5944 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5945 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5946
5947 10**(p-1) <= c <= 10**p, and
5948 (c-1)*10**e < x**y < (c+1)*10**e
5949
5950 in other words, c*10**e is an approximation to x**y with p digits
5951 of precision, and with an error in c of at most 1. (This is
5952 almost, but not quite, the same as the error being < 1ulp: when c
5953 == 10**(p-1) we can only guarantee error < 10ulp.)
5954
5955 We assume that: x is positive and not equal to 1, and y is nonzero.
5956 """
5957
5958 # Find b such that 10**(b-1) <= |y| <= 10**b
5959 b = len(str(abs(yc))) + ye
5960
5961 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5962 lxc = _dlog(xc, xe, p+b+1)
5963
5964 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5965 shift = ye-b
5966 if shift >= 0:
5967 pc = lxc*yc*10**shift
5968 else:
5969 pc = _div_nearest(lxc*yc, 10**-shift)
5970
5971 if pc == 0:
5972 # we prefer a result that isn't exactly 1; this makes it
5973 # easier to compute a correctly rounded result in __pow__
5974 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5975 coeff, exp = 10**(p-1)+1, 1-p
5976 else:
5977 coeff, exp = 10**p-1, -p
5978 else:
5979 coeff, exp = _dexp(pc, -(p+1), p+1)
5980 coeff = _div_nearest(coeff, 10)
5981 exp += 1
5982
5983 return coeff, exp
5984
5985def _log10_lb(c, correction = {
5986 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5987 '6': 23, '7': 16, '8': 10, '9': 5}):
5988 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5989 if c <= 0:
5990 raise ValueError("The argument to _log10_lb should be nonnegative.")
5991 str_c = str(c)
5992 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005993
Guido van Rossumd8faa362007-04-27 19:54:29 +00005994##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005995
Mark Dickinsonac256ab2010-04-03 11:08:14 +00005996def _convert_other(other, raiseit=False, allow_float=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005997 """Convert other to Decimal.
5998
5999 Verifies that it's ok to use in an implicit construction.
Mark Dickinsonac256ab2010-04-03 11:08:14 +00006000 If allow_float is true, allow conversion from float; this
6001 is used in the comparison methods (__eq__ and friends).
6002
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006003 """
6004 if isinstance(other, Decimal):
6005 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00006006 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006007 return Decimal(other)
Mark Dickinsonac256ab2010-04-03 11:08:14 +00006008 if allow_float and isinstance(other, float):
6009 return Decimal.from_float(other)
6010
Thomas Wouters1b7f8912007-09-19 03:06:30 +00006011 if raiseit:
6012 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00006013 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006014
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006015def _convert_for_comparison(self, other, equality_op=False):
6016 """Given a Decimal instance self and a Python object other, return
Mark Dickinson1c164a62010-06-11 16:49:20 +00006017 a pair (s, o) of Decimal instances such that "s op o" is
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006018 equivalent to "self op other" for any of the 6 comparison
6019 operators "op".
6020
6021 """
6022 if isinstance(other, Decimal):
6023 return self, other
6024
6025 # Comparison with a Rational instance (also includes integers):
6026 # self op n/d <=> self*d op n (for n and d integers, d positive).
6027 # A NaN or infinity can be left unchanged without affecting the
6028 # comparison result.
6029 if isinstance(other, _numbers.Rational):
6030 if not self._is_special:
6031 self = _dec_from_triple(self._sign,
6032 str(int(self._int) * other.denominator),
6033 self._exp)
6034 return self, Decimal(other.numerator)
6035
6036 # Comparisons with float and complex types. == and != comparisons
6037 # with complex numbers should succeed, returning either True or False
6038 # as appropriate. Other comparisons return NotImplemented.
6039 if equality_op and isinstance(other, _numbers.Complex) and other.imag == 0:
6040 other = other.real
6041 if isinstance(other, float):
Stefan Krah1919b7e2012-03-21 18:25:23 +01006042 context = getcontext()
6043 if equality_op:
6044 context.flags[FloatOperation] = 1
6045 else:
6046 context._raise_error(FloatOperation,
6047 "strict semantics for mixing floats and Decimals are enabled")
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006048 return self, Decimal.from_float(other)
6049 return NotImplemented, NotImplemented
6050
6051
Guido van Rossumd8faa362007-04-27 19:54:29 +00006052##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006053
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006054# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00006055# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006056
6057DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00006058 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006059 traps=[DivisionByZero, Overflow, InvalidOperation],
6060 flags=[],
Stefan Krah1919b7e2012-03-21 18:25:23 +01006061 Emax=999999,
6062 Emin=-999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00006063 capitals=1,
6064 clamp=0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006065)
6066
6067# Pre-made alternate contexts offered by the specification
6068# Don't change these; the user should be able to select these
6069# contexts and be able to reproduce results from other implementations
6070# of the spec.
6071
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00006072BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006073 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006074 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
6075 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006076)
6077
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00006078ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00006079 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006080 traps=[],
6081 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006082)
6083
6084
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006085##### crud for parsing strings #############################################
Christian Heimes23daade02008-02-25 12:39:23 +00006086#
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006087# Regular expression used for parsing numeric strings. Additional
6088# comments:
6089#
6090# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
6091# whitespace. But note that the specification disallows whitespace in
6092# a numeric string.
6093#
6094# 2. For finite numbers (not infinities and NaNs) the body of the
6095# number between the optional sign and the optional exponent must have
6096# at least one decimal digit, possibly after the decimal point. The
Mark Dickinson345adc42009-08-02 10:14:23 +00006097# lookahead expression '(?=\d|\.\d)' checks this.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006098
6099import re
Benjamin Peterson41181742008-07-02 20:22:54 +00006100_parser = re.compile(r""" # A numeric string consists of:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006101# \s*
Benjamin Peterson41181742008-07-02 20:22:54 +00006102 (?P<sign>[-+])? # an optional sign, followed by either...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006103 (
Mark Dickinson345adc42009-08-02 10:14:23 +00006104 (?=\d|\.\d) # ...a number (with at least one digit)
6105 (?P<int>\d*) # having a (possibly empty) integer part
6106 (\.(?P<frac>\d*))? # followed by an optional fractional part
6107 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006108 |
Benjamin Peterson41181742008-07-02 20:22:54 +00006109 Inf(inity)? # ...an infinity, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006110 |
Benjamin Peterson41181742008-07-02 20:22:54 +00006111 (?P<signal>s)? # ...an (optionally signaling)
6112 NaN # NaN
Mark Dickinson345adc42009-08-02 10:14:23 +00006113 (?P<diag>\d*) # with (possibly empty) diagnostic info.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006114 )
6115# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00006116 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006117""", re.VERBOSE | re.IGNORECASE).match
6118
Christian Heimescbf3b5c2007-12-03 21:02:03 +00006119_all_zeros = re.compile('0*$').match
6120_exact_half = re.compile('50*$').match
Christian Heimesf16baeb2008-02-29 14:57:44 +00006121
6122##### PEP3101 support functions ##############################################
Mark Dickinson79f52032009-03-17 23:12:51 +00006123# The functions in this section have little to do with the Decimal
6124# class, and could potentially be reused or adapted for other pure
Christian Heimesf16baeb2008-02-29 14:57:44 +00006125# Python numeric classes that want to implement __format__
6126#
6127# A format specifier for Decimal looks like:
6128#
Eric Smith984bb582010-11-25 16:08:06 +00006129# [[fill]align][sign][#][0][minimumwidth][,][.precision][type]
Christian Heimesf16baeb2008-02-29 14:57:44 +00006130
6131_parse_format_specifier_regex = re.compile(r"""\A
6132(?:
6133 (?P<fill>.)?
6134 (?P<align>[<>=^])
6135)?
6136(?P<sign>[-+ ])?
Eric Smith984bb582010-11-25 16:08:06 +00006137(?P<alt>\#)?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006138(?P<zeropad>0)?
6139(?P<minimumwidth>(?!0)\d+)?
Mark Dickinson79f52032009-03-17 23:12:51 +00006140(?P<thousands_sep>,)?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006141(?:\.(?P<precision>0|(?!0)\d+))?
Mark Dickinson79f52032009-03-17 23:12:51 +00006142(?P<type>[eEfFgGn%])?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006143\Z
Stefan Krah6edda142013-05-29 15:45:38 +02006144""", re.VERBOSE|re.DOTALL)
Christian Heimesf16baeb2008-02-29 14:57:44 +00006145
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006146del re
6147
Mark Dickinson79f52032009-03-17 23:12:51 +00006148# The locale module is only needed for the 'n' format specifier. The
6149# rest of the PEP 3101 code functions quite happily without it, so we
6150# don't care too much if locale isn't present.
6151try:
6152 import locale as _locale
6153except ImportError:
6154 pass
6155
6156def _parse_format_specifier(format_spec, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00006157 """Parse and validate a format specifier.
6158
6159 Turns a standard numeric format specifier into a dict, with the
6160 following entries:
6161
6162 fill: fill character to pad field to minimum width
6163 align: alignment type, either '<', '>', '=' or '^'
6164 sign: either '+', '-' or ' '
6165 minimumwidth: nonnegative integer giving minimum width
Mark Dickinson79f52032009-03-17 23:12:51 +00006166 zeropad: boolean, indicating whether to pad with zeros
6167 thousands_sep: string to use as thousands separator, or ''
6168 grouping: grouping for thousands separators, in format
6169 used by localeconv
6170 decimal_point: string to use for decimal point
Christian Heimesf16baeb2008-02-29 14:57:44 +00006171 precision: nonnegative integer giving precision, or None
6172 type: one of the characters 'eEfFgG%', or None
Christian Heimesf16baeb2008-02-29 14:57:44 +00006173
6174 """
6175 m = _parse_format_specifier_regex.match(format_spec)
6176 if m is None:
6177 raise ValueError("Invalid format specifier: " + format_spec)
6178
6179 # get the dictionary
6180 format_dict = m.groupdict()
6181
Mark Dickinson79f52032009-03-17 23:12:51 +00006182 # zeropad; defaults for fill and alignment. If zero padding
6183 # is requested, the fill and align fields should be absent.
Christian Heimesf16baeb2008-02-29 14:57:44 +00006184 fill = format_dict['fill']
6185 align = format_dict['align']
Mark Dickinson79f52032009-03-17 23:12:51 +00006186 format_dict['zeropad'] = (format_dict['zeropad'] is not None)
6187 if format_dict['zeropad']:
6188 if fill is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00006189 raise ValueError("Fill character conflicts with '0'"
6190 " in format specifier: " + format_spec)
Mark Dickinson79f52032009-03-17 23:12:51 +00006191 if align is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00006192 raise ValueError("Alignment conflicts with '0' in "
6193 "format specifier: " + format_spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00006194 format_dict['fill'] = fill or ' '
Mark Dickinson46ab5d02009-09-08 20:22:46 +00006195 # PEP 3101 originally specified that the default alignment should
6196 # be left; it was later agreed that right-aligned makes more sense
6197 # for numeric types. See http://bugs.python.org/issue6857.
6198 format_dict['align'] = align or '>'
Christian Heimesf16baeb2008-02-29 14:57:44 +00006199
Mark Dickinson79f52032009-03-17 23:12:51 +00006200 # default sign handling: '-' for negative, '' for positive
Christian Heimesf16baeb2008-02-29 14:57:44 +00006201 if format_dict['sign'] is None:
6202 format_dict['sign'] = '-'
6203
Christian Heimesf16baeb2008-02-29 14:57:44 +00006204 # minimumwidth defaults to 0; precision remains None if not given
6205 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
6206 if format_dict['precision'] is not None:
6207 format_dict['precision'] = int(format_dict['precision'])
6208
6209 # if format type is 'g' or 'G' then a precision of 0 makes little
6210 # sense; convert it to 1. Same if format type is unspecified.
6211 if format_dict['precision'] == 0:
Stefan Krah1919b7e2012-03-21 18:25:23 +01006212 if format_dict['type'] is None or format_dict['type'] in 'gGn':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006213 format_dict['precision'] = 1
6214
Mark Dickinson79f52032009-03-17 23:12:51 +00006215 # determine thousands separator, grouping, and decimal separator, and
6216 # add appropriate entries to format_dict
6217 if format_dict['type'] == 'n':
6218 # apart from separators, 'n' behaves just like 'g'
6219 format_dict['type'] = 'g'
6220 if _localeconv is None:
6221 _localeconv = _locale.localeconv()
6222 if format_dict['thousands_sep'] is not None:
6223 raise ValueError("Explicit thousands separator conflicts with "
6224 "'n' type in format specifier: " + format_spec)
6225 format_dict['thousands_sep'] = _localeconv['thousands_sep']
6226 format_dict['grouping'] = _localeconv['grouping']
6227 format_dict['decimal_point'] = _localeconv['decimal_point']
6228 else:
6229 if format_dict['thousands_sep'] is None:
6230 format_dict['thousands_sep'] = ''
6231 format_dict['grouping'] = [3, 0]
6232 format_dict['decimal_point'] = '.'
Christian Heimesf16baeb2008-02-29 14:57:44 +00006233
6234 return format_dict
6235
Mark Dickinson79f52032009-03-17 23:12:51 +00006236def _format_align(sign, body, spec):
6237 """Given an unpadded, non-aligned numeric string 'body' and sign
Ezio Melotti42da6632011-03-15 05:18:48 +02006238 string 'sign', add padding and alignment conforming to the given
Mark Dickinson79f52032009-03-17 23:12:51 +00006239 format specifier dictionary 'spec' (as produced by
6240 parse_format_specifier).
Christian Heimesf16baeb2008-02-29 14:57:44 +00006241
6242 """
Christian Heimesf16baeb2008-02-29 14:57:44 +00006243 # how much extra space do we have to play with?
Mark Dickinson79f52032009-03-17 23:12:51 +00006244 minimumwidth = spec['minimumwidth']
6245 fill = spec['fill']
6246 padding = fill*(minimumwidth - len(sign) - len(body))
Christian Heimesf16baeb2008-02-29 14:57:44 +00006247
Mark Dickinson79f52032009-03-17 23:12:51 +00006248 align = spec['align']
Christian Heimesf16baeb2008-02-29 14:57:44 +00006249 if align == '<':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006250 result = sign + body + padding
Mark Dickinsonad416342009-03-17 18:10:15 +00006251 elif align == '>':
6252 result = padding + sign + body
Christian Heimesf16baeb2008-02-29 14:57:44 +00006253 elif align == '=':
6254 result = sign + padding + body
Mark Dickinson79f52032009-03-17 23:12:51 +00006255 elif align == '^':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006256 half = len(padding)//2
6257 result = padding[:half] + sign + body + padding[half:]
Mark Dickinson79f52032009-03-17 23:12:51 +00006258 else:
6259 raise ValueError('Unrecognised alignment field')
Christian Heimesf16baeb2008-02-29 14:57:44 +00006260
Christian Heimesf16baeb2008-02-29 14:57:44 +00006261 return result
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006262
Mark Dickinson79f52032009-03-17 23:12:51 +00006263def _group_lengths(grouping):
6264 """Convert a localeconv-style grouping into a (possibly infinite)
6265 iterable of integers representing group lengths.
6266
6267 """
6268 # The result from localeconv()['grouping'], and the input to this
6269 # function, should be a list of integers in one of the
6270 # following three forms:
6271 #
6272 # (1) an empty list, or
6273 # (2) nonempty list of positive integers + [0]
6274 # (3) list of positive integers + [locale.CHAR_MAX], or
6275
6276 from itertools import chain, repeat
6277 if not grouping:
6278 return []
6279 elif grouping[-1] == 0 and len(grouping) >= 2:
6280 return chain(grouping[:-1], repeat(grouping[-2]))
6281 elif grouping[-1] == _locale.CHAR_MAX:
6282 return grouping[:-1]
6283 else:
6284 raise ValueError('unrecognised format for grouping')
6285
6286def _insert_thousands_sep(digits, spec, min_width=1):
6287 """Insert thousands separators into a digit string.
6288
6289 spec is a dictionary whose keys should include 'thousands_sep' and
6290 'grouping'; typically it's the result of parsing the format
6291 specifier using _parse_format_specifier.
6292
6293 The min_width keyword argument gives the minimum length of the
6294 result, which will be padded on the left with zeros if necessary.
6295
6296 If necessary, the zero padding adds an extra '0' on the left to
6297 avoid a leading thousands separator. For example, inserting
6298 commas every three digits in '123456', with min_width=8, gives
6299 '0,123,456', even though that has length 9.
6300
6301 """
6302
6303 sep = spec['thousands_sep']
6304 grouping = spec['grouping']
6305
6306 groups = []
6307 for l in _group_lengths(grouping):
Mark Dickinson79f52032009-03-17 23:12:51 +00006308 if l <= 0:
6309 raise ValueError("group length should be positive")
6310 # max(..., 1) forces at least 1 digit to the left of a separator
6311 l = min(max(len(digits), min_width, 1), l)
6312 groups.append('0'*(l - len(digits)) + digits[-l:])
6313 digits = digits[:-l]
6314 min_width -= l
6315 if not digits and min_width <= 0:
6316 break
Mark Dickinson7303b592009-03-18 08:25:36 +00006317 min_width -= len(sep)
Mark Dickinson79f52032009-03-17 23:12:51 +00006318 else:
6319 l = max(len(digits), min_width, 1)
6320 groups.append('0'*(l - len(digits)) + digits[-l:])
6321 return sep.join(reversed(groups))
6322
6323def _format_sign(is_negative, spec):
6324 """Determine sign character."""
6325
6326 if is_negative:
6327 return '-'
6328 elif spec['sign'] in ' +':
6329 return spec['sign']
6330 else:
6331 return ''
6332
6333def _format_number(is_negative, intpart, fracpart, exp, spec):
6334 """Format a number, given the following data:
6335
6336 is_negative: true if the number is negative, else false
6337 intpart: string of digits that must appear before the decimal point
6338 fracpart: string of digits that must come after the point
6339 exp: exponent, as an integer
6340 spec: dictionary resulting from parsing the format specifier
6341
6342 This function uses the information in spec to:
6343 insert separators (decimal separator and thousands separators)
6344 format the sign
6345 format the exponent
6346 add trailing '%' for the '%' type
6347 zero-pad if necessary
6348 fill and align if necessary
6349 """
6350
6351 sign = _format_sign(is_negative, spec)
6352
Eric Smith984bb582010-11-25 16:08:06 +00006353 if fracpart or spec['alt']:
Mark Dickinson79f52032009-03-17 23:12:51 +00006354 fracpart = spec['decimal_point'] + fracpart
6355
6356 if exp != 0 or spec['type'] in 'eE':
6357 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
6358 fracpart += "{0}{1:+}".format(echar, exp)
6359 if spec['type'] == '%':
6360 fracpart += '%'
6361
6362 if spec['zeropad']:
6363 min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
6364 else:
6365 min_width = 0
6366 intpart = _insert_thousands_sep(intpart, spec, min_width)
6367
6368 return _format_align(sign, intpart+fracpart, spec)
6369
6370
Guido van Rossumd8faa362007-04-27 19:54:29 +00006371##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006372
Guido van Rossumd8faa362007-04-27 19:54:29 +00006373# Reusable defaults
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006374_Infinity = Decimal('Inf')
6375_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonf9236412009-01-02 23:23:21 +00006376_NaN = Decimal('NaN')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006377_Zero = Decimal(0)
6378_One = Decimal(1)
6379_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006380
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006381# _SignedInfinity[sign] is infinity w/ that sign
6382_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006383
Mark Dickinsondc787d22010-05-23 13:33:13 +00006384# Constants related to the hash implementation; hash(x) is based
6385# on the reduction of x modulo _PyHASH_MODULUS
Mark Dickinsondc787d22010-05-23 13:33:13 +00006386_PyHASH_MODULUS = sys.hash_info.modulus
6387# hash values to use for positive and negative infinities, and nans
6388_PyHASH_INF = sys.hash_info.inf
6389_PyHASH_NAN = sys.hash_info.nan
Mark Dickinsondc787d22010-05-23 13:33:13 +00006390
6391# _PyHASH_10INV is the inverse of 10 modulo the prime _PyHASH_MODULUS
6392_PyHASH_10INV = pow(10, _PyHASH_MODULUS - 2, _PyHASH_MODULUS)
Stefan Krah1919b7e2012-03-21 18:25:23 +01006393del sys
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006394
Stefan Krah1919b7e2012-03-21 18:25:23 +01006395try:
6396 import _decimal
6397except ImportError:
6398 pass
6399else:
6400 s1 = set(dir())
6401 s2 = set(dir(_decimal))
6402 for name in s1 - s2:
6403 del globals()[name]
6404 del s1, s2, name
6405 from _decimal import *
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006406
6407if __name__ == '__main__':
Raymond Hettinger6d7e26e2011-02-01 23:54:43 +00006408 import doctest, decimal
6409 doctest.testmod(decimal)