blob: 7bc1c943b5b0aefba2f5894a2ead464a7f8fc33b [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')
Brett Cannoncd171c82013-07-04 17:43:24 -0400153except ImportError:
Christian Heimes25bb7832008-01-11 16:17:00 +0000154 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
Brett Cannoncd171c82013-07-04 17:43:24 -0400434except ImportError:
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000435 # 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 Dickinson9c3f5032012-10-31 17:53:27 +0000707 @classmethod
Raymond Hettinger771ed762009-01-03 19:20:32 +0000708 def from_float(cls, f):
709 """Converts a float to a decimal number, exactly.
710
711 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
712 Since 0.1 is not exactly representable in binary floating point, the
713 value is stored as the nearest representable value which is
714 0x1.999999999999ap-4. The exact equivalent of the value in decimal
715 is 0.1000000000000000055511151231257827021181583404541015625.
716
717 >>> Decimal.from_float(0.1)
718 Decimal('0.1000000000000000055511151231257827021181583404541015625')
719 >>> Decimal.from_float(float('nan'))
720 Decimal('NaN')
721 >>> Decimal.from_float(float('inf'))
722 Decimal('Infinity')
723 >>> Decimal.from_float(-float('inf'))
724 Decimal('-Infinity')
725 >>> Decimal.from_float(-0.0)
726 Decimal('-0')
727
728 """
729 if isinstance(f, int): # handle integer inputs
730 return cls(f)
Stefan Krah1919b7e2012-03-21 18:25:23 +0100731 if not isinstance(f, float):
732 raise TypeError("argument must be int or float.")
733 if _math.isinf(f) or _math.isnan(f):
Raymond Hettinger771ed762009-01-03 19:20:32 +0000734 return cls(repr(f))
Mark Dickinsonba298e42009-01-04 21:17:43 +0000735 if _math.copysign(1.0, f) == 1.0:
736 sign = 0
737 else:
738 sign = 1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000739 n, d = abs(f).as_integer_ratio()
740 k = d.bit_length() - 1
741 result = _dec_from_triple(sign, str(n*5**k), -k)
Mark Dickinsonba298e42009-01-04 21:17:43 +0000742 if cls is Decimal:
743 return result
744 else:
745 return cls(result)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000746
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000747 def _isnan(self):
748 """Returns whether the number is not actually one.
749
750 0 if a number
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000751 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000752 2 if sNaN
753 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000754 if self._is_special:
755 exp = self._exp
756 if exp == 'n':
757 return 1
758 elif exp == 'N':
759 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000760 return 0
761
762 def _isinfinity(self):
763 """Returns whether the number is infinite
764
765 0 if finite or not a number
766 1 if +INF
767 -1 if -INF
768 """
769 if self._exp == 'F':
770 if self._sign:
771 return -1
772 return 1
773 return 0
774
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000775 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000776 """Returns whether the number is not actually one.
777
778 if self, other are sNaN, signal
779 if self, other are NaN return nan
780 return 0
781
782 Done before operations.
783 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000784
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000785 self_is_nan = self._isnan()
786 if other is None:
787 other_is_nan = False
788 else:
789 other_is_nan = other._isnan()
790
791 if self_is_nan or other_is_nan:
792 if context is None:
793 context = getcontext()
794
795 if self_is_nan == 2:
796 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000797 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000798 if other_is_nan == 2:
799 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000800 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000801 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000802 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000803
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000804 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000805 return 0
806
Christian Heimes77c02eb2008-02-09 02:18:51 +0000807 def _compare_check_nans(self, other, context):
808 """Version of _check_nans used for the signaling comparisons
809 compare_signal, __le__, __lt__, __ge__, __gt__.
810
811 Signal InvalidOperation if either self or other is a (quiet
812 or signaling) NaN. Signaling NaNs take precedence over quiet
813 NaNs.
814
815 Return 0 if neither operand is a NaN.
816
817 """
818 if context is None:
819 context = getcontext()
820
821 if self._is_special or other._is_special:
822 if self.is_snan():
823 return context._raise_error(InvalidOperation,
824 'comparison involving sNaN',
825 self)
826 elif other.is_snan():
827 return context._raise_error(InvalidOperation,
828 'comparison involving sNaN',
829 other)
830 elif self.is_qnan():
831 return context._raise_error(InvalidOperation,
832 'comparison involving NaN',
833 self)
834 elif other.is_qnan():
835 return context._raise_error(InvalidOperation,
836 'comparison involving NaN',
837 other)
838 return 0
839
Jack Diederich4dafcc42006-11-28 19:15:13 +0000840 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000841 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000842
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000843 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000844 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000845 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000846
Christian Heimes77c02eb2008-02-09 02:18:51 +0000847 def _cmp(self, other):
848 """Compare the two non-NaN decimal instances self and other.
849
850 Returns -1 if self < other, 0 if self == other and 1
851 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000852
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000853 if self._is_special or other._is_special:
Mark Dickinsone6aad752009-01-25 10:48:51 +0000854 self_inf = self._isinfinity()
855 other_inf = other._isinfinity()
856 if self_inf == other_inf:
857 return 0
858 elif self_inf < other_inf:
859 return -1
860 else:
861 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000862
Mark Dickinsone6aad752009-01-25 10:48:51 +0000863 # check for zeros; Decimal('0') == Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000864 if not self:
865 if not other:
866 return 0
867 else:
868 return -((-1)**other._sign)
869 if not other:
870 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000871
Guido van Rossumd8faa362007-04-27 19:54:29 +0000872 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000873 if other._sign < self._sign:
874 return -1
875 if self._sign < other._sign:
876 return 1
877
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000878 self_adjusted = self.adjusted()
879 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000880 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000881 self_padded = self._int + '0'*(self._exp - other._exp)
882 other_padded = other._int + '0'*(other._exp - self._exp)
Mark Dickinsone6aad752009-01-25 10:48:51 +0000883 if self_padded == other_padded:
884 return 0
885 elif self_padded < other_padded:
886 return -(-1)**self._sign
887 else:
888 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000889 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000890 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000891 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000892 return -((-1)**self._sign)
893
Christian Heimes77c02eb2008-02-09 02:18:51 +0000894 # Note: The Decimal standard doesn't cover rich comparisons for
895 # Decimals. In particular, the specification is silent on the
896 # subject of what should happen for a comparison involving a NaN.
897 # We take the following approach:
898 #
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000899 # == comparisons involving a quiet NaN always return False
900 # != comparisons involving a quiet NaN always return True
901 # == or != comparisons involving a signaling NaN signal
902 # InvalidOperation, and return False or True as above if the
903 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000904 # <, >, <= and >= comparisons involving a (quiet or signaling)
905 # NaN signal InvalidOperation, and return False if the
Christian Heimes3feef612008-02-11 06:19:17 +0000906 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000907 #
908 # This behavior is designed to conform as closely as possible to
909 # that specified by IEEE 754.
910
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000911 def __eq__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000912 self, other = _convert_for_comparison(self, other, equality_op=True)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000913 if other is NotImplemented:
914 return other
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000915 if self._check_nans(other, context):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000916 return False
917 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000918
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000919 def __ne__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000920 self, other = _convert_for_comparison(self, other, equality_op=True)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000921 if other is NotImplemented:
922 return other
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000923 if self._check_nans(other, context):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000924 return True
925 return self._cmp(other) != 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000926
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000927
Christian Heimes77c02eb2008-02-09 02:18:51 +0000928 def __lt__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000929 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000930 if other is NotImplemented:
931 return other
932 ans = self._compare_check_nans(other, context)
933 if ans:
934 return False
935 return self._cmp(other) < 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000936
Christian Heimes77c02eb2008-02-09 02:18:51 +0000937 def __le__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000938 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000939 if other is NotImplemented:
940 return other
941 ans = self._compare_check_nans(other, context)
942 if ans:
943 return False
944 return self._cmp(other) <= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000945
Christian Heimes77c02eb2008-02-09 02:18:51 +0000946 def __gt__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000947 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000948 if other is NotImplemented:
949 return other
950 ans = self._compare_check_nans(other, context)
951 if ans:
952 return False
953 return self._cmp(other) > 0
954
955 def __ge__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000956 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000957 if other is NotImplemented:
958 return other
959 ans = self._compare_check_nans(other, context)
960 if ans:
961 return False
962 return self._cmp(other) >= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000963
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000964 def compare(self, other, context=None):
965 """Compares one to another.
966
967 -1 => a < b
968 0 => a = b
969 1 => a > b
970 NaN => one is NaN
971 Like __cmp__, but returns Decimal instances.
972 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000973 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000974
Guido van Rossumd8faa362007-04-27 19:54:29 +0000975 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000976 if (self._is_special or other and other._is_special):
977 ans = self._check_nans(other, context)
978 if ans:
979 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000980
Christian Heimes77c02eb2008-02-09 02:18:51 +0000981 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000982
983 def __hash__(self):
984 """x.__hash__() <==> hash(x)"""
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000985
Mark Dickinsondc787d22010-05-23 13:33:13 +0000986 # In order to make sure that the hash of a Decimal instance
987 # agrees with the hash of a numerically equal integer, float
988 # or Fraction, we follow the rules for numeric hashes outlined
989 # in the documentation. (See library docs, 'Built-in Types').
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000990 if self._is_special:
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000991 if self.is_snan():
Raymond Hettingerd325c4b2010-11-21 04:08:28 +0000992 raise TypeError('Cannot hash a signaling NaN value.')
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000993 elif self.is_nan():
Mark Dickinsondc787d22010-05-23 13:33:13 +0000994 return _PyHASH_NAN
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000995 else:
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000996 if self._sign:
Mark Dickinsondc787d22010-05-23 13:33:13 +0000997 return -_PyHASH_INF
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000998 else:
Mark Dickinsondc787d22010-05-23 13:33:13 +0000999 return _PyHASH_INF
Mark Dickinsonac256ab2010-04-03 11:08:14 +00001000
Mark Dickinsondc787d22010-05-23 13:33:13 +00001001 if self._exp >= 0:
1002 exp_hash = pow(10, self._exp, _PyHASH_MODULUS)
1003 else:
1004 exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS)
1005 hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS
Stefan Krahdc817b22010-11-17 11:16:34 +00001006 ans = hash_ if self >= 0 else -hash_
1007 return -2 if ans == -1 else ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001008
1009 def as_tuple(self):
1010 """Represents the number as a triple tuple.
1011
1012 To show the internals exactly as they are.
1013 """
Christian Heimes25bb7832008-01-11 16:17:00 +00001014 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001015
1016 def __repr__(self):
1017 """Represents the number as an instance of Decimal."""
1018 # Invariant: eval(repr(d)) == d
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001019 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001020
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001021 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001022 """Return string representation of the number in scientific notation.
1023
1024 Captures all of the information in the underlying representation.
1025 """
1026
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001027 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +00001028 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001029 if self._exp == 'F':
1030 return sign + 'Infinity'
1031 elif self._exp == 'n':
1032 return sign + 'NaN' + self._int
1033 else: # self._exp == 'N'
1034 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001035
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001036 # number of digits of self._int to left of decimal point
1037 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001038
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001039 # dotplace is number of digits of self._int to the left of the
1040 # decimal point in the mantissa of the output string (that is,
1041 # after adjusting the exponent)
1042 if self._exp <= 0 and leftdigits > -6:
1043 # no exponent required
1044 dotplace = leftdigits
1045 elif not eng:
1046 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001047 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001048 elif self._int == '0':
1049 # engineering notation, zero
1050 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001051 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001052 # engineering notation, nonzero
1053 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001054
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001055 if dotplace <= 0:
1056 intpart = '0'
1057 fracpart = '.' + '0'*(-dotplace) + self._int
1058 elif dotplace >= len(self._int):
1059 intpart = self._int+'0'*(dotplace-len(self._int))
1060 fracpart = ''
1061 else:
1062 intpart = self._int[:dotplace]
1063 fracpart = '.' + self._int[dotplace:]
1064 if leftdigits == dotplace:
1065 exp = ''
1066 else:
1067 if context is None:
1068 context = getcontext()
1069 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1070
1071 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001072
1073 def to_eng_string(self, context=None):
1074 """Convert to engineering-type string.
1075
1076 Engineering notation has an exponent which is a multiple of 3, so there
1077 are up to 3 digits left of the decimal place.
1078
1079 Same rules for when in exponential and when as a value as in __str__.
1080 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001081 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001082
1083 def __neg__(self, context=None):
1084 """Returns a copy with the sign switched.
1085
1086 Rounds, if it has reason.
1087 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001088 if self._is_special:
1089 ans = self._check_nans(context=context)
1090 if ans:
1091 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001092
Mark Dickinson37a79fb2011-03-12 11:12:52 +00001093 if context is None:
1094 context = getcontext()
1095
1096 if not self and context.rounding != ROUND_FLOOR:
1097 # -Decimal('0') is Decimal('0'), not Decimal('-0'), except
1098 # in ROUND_FLOOR rounding mode.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001099 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001100 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001101 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001102
Christian Heimes2c181612007-12-17 20:04:13 +00001103 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001104
1105 def __pos__(self, context=None):
1106 """Returns a copy, unless it is a sNaN.
1107
1108 Rounds the number (if more then precision digits)
1109 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001110 if self._is_special:
1111 ans = self._check_nans(context=context)
1112 if ans:
1113 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001114
Mark Dickinson37a79fb2011-03-12 11:12:52 +00001115 if context is None:
1116 context = getcontext()
1117
1118 if not self and context.rounding != ROUND_FLOOR:
1119 # + (-0) = 0, except in ROUND_FLOOR rounding mode.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001120 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001121 else:
1122 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001123
Christian Heimes2c181612007-12-17 20:04:13 +00001124 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001125
Christian Heimes2c181612007-12-17 20:04:13 +00001126 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001127 """Returns the absolute value of self.
1128
Christian Heimes2c181612007-12-17 20:04:13 +00001129 If the keyword argument 'round' is false, do not round. The
1130 expression self.__abs__(round=False) is equivalent to
1131 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001132 """
Christian Heimes2c181612007-12-17 20:04:13 +00001133 if not round:
1134 return self.copy_abs()
1135
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001136 if self._is_special:
1137 ans = self._check_nans(context=context)
1138 if ans:
1139 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001140
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141 if self._sign:
1142 ans = self.__neg__(context=context)
1143 else:
1144 ans = self.__pos__(context=context)
1145
1146 return ans
1147
1148 def __add__(self, other, context=None):
1149 """Returns self + other.
1150
1151 -INF + INF (or the reverse) cause InvalidOperation errors.
1152 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001153 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001154 if other is NotImplemented:
1155 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001156
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001157 if context is None:
1158 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001159
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001160 if self._is_special or other._is_special:
1161 ans = self._check_nans(other, context)
1162 if ans:
1163 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001164
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001165 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001166 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001167 if self._sign != other._sign and other._isinfinity():
1168 return context._raise_error(InvalidOperation, '-INF + INF')
1169 return Decimal(self)
1170 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001171 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001172
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001173 exp = min(self._exp, other._exp)
1174 negativezero = 0
1175 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001176 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001177 negativezero = 1
1178
1179 if not self and not other:
1180 sign = min(self._sign, other._sign)
1181 if negativezero:
1182 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001183 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001184 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001185 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001186 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001187 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001188 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001189 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001190 return ans
1191 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001192 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001193 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001194 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001195 return ans
1196
1197 op1 = _WorkRep(self)
1198 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001199 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001200
1201 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001202 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001203 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001204 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001205 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001206 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001207 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001208 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001209 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001210 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001211 if op1.sign == 1:
1212 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001213 op1.sign, op2.sign = op2.sign, op1.sign
1214 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001215 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001216 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001217 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001218 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001219 op1.sign, op2.sign = (0, 0)
1220 else:
1221 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001222 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001223
Raymond Hettinger17931de2004-10-27 06:21:46 +00001224 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001225 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001226 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001227 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001228
1229 result.exp = op1.exp
1230 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001231 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001232 return ans
1233
1234 __radd__ = __add__
1235
1236 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001237 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001238 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001239 if other is NotImplemented:
1240 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001241
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001242 if self._is_special or other._is_special:
1243 ans = self._check_nans(other, context=context)
1244 if ans:
1245 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001246
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001247 # self - other is computed as self + other.copy_negate()
1248 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001249
1250 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001251 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001252 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001253 if other is NotImplemented:
1254 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001255
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001256 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001257
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001258 def __mul__(self, other, context=None):
1259 """Return self * other.
1260
1261 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1262 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001263 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001264 if other is NotImplemented:
1265 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001266
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001267 if context is None:
1268 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001269
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001270 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001271
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001272 if self._is_special or other._is_special:
1273 ans = self._check_nans(other, context)
1274 if ans:
1275 return ans
1276
1277 if self._isinfinity():
1278 if not other:
1279 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001280 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001281
1282 if other._isinfinity():
1283 if not self:
1284 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001285 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001286
1287 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001288
1289 # Special case for multiplying by zero
1290 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001291 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001292 # Fixing in case the exponent is out of bounds
1293 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001294 return ans
1295
1296 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001297 if self._int == '1':
1298 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001299 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001300 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001301 if other._int == '1':
1302 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001303 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001304 return ans
1305
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001306 op1 = _WorkRep(self)
1307 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001308
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001309 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001310 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001311
1312 return ans
1313 __rmul__ = __mul__
1314
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001315 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001316 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001317 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001318 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001319 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001320
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001321 if context is None:
1322 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001323
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001324 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001325
1326 if self._is_special or other._is_special:
1327 ans = self._check_nans(other, context)
1328 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001329 return ans
1330
1331 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001332 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001333
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001334 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001335 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001336
1337 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001338 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001339 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001340
1341 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001342 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001343 if not self:
1344 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001345 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001346
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001347 if not self:
1348 exp = self._exp - other._exp
1349 coeff = 0
1350 else:
1351 # OK, so neither = 0, INF or NaN
1352 shift = len(other._int) - len(self._int) + context.prec + 1
1353 exp = self._exp - other._exp - shift
1354 op1 = _WorkRep(self)
1355 op2 = _WorkRep(other)
1356 if shift >= 0:
1357 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1358 else:
1359 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1360 if remainder:
1361 # result is not exact; adjust to ensure correct rounding
1362 if coeff % 5 == 0:
1363 coeff += 1
1364 else:
1365 # result is exact; get as close to ideal exponent as possible
1366 ideal_exp = self._exp - other._exp
1367 while exp < ideal_exp and coeff % 10 == 0:
1368 coeff //= 10
1369 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001370
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001371 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001372 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001373
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001374 def _divide(self, other, context):
1375 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001376
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001377 Assumes that neither self nor other is a NaN, that self is not
1378 infinite and that other is nonzero.
1379 """
1380 sign = self._sign ^ other._sign
1381 if other._isinfinity():
1382 ideal_exp = self._exp
1383 else:
1384 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001385
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001386 expdiff = self.adjusted() - other.adjusted()
1387 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001388 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001389 self._rescale(ideal_exp, context.rounding))
1390 if expdiff <= context.prec:
1391 op1 = _WorkRep(self)
1392 op2 = _WorkRep(other)
1393 if op1.exp >= op2.exp:
1394 op1.int *= 10**(op1.exp - op2.exp)
1395 else:
1396 op2.int *= 10**(op2.exp - op1.exp)
1397 q, r = divmod(op1.int, op2.int)
1398 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001399 return (_dec_from_triple(sign, str(q), 0),
1400 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001401
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001402 # Here the quotient is too large to be representable
1403 ans = context._raise_error(DivisionImpossible,
1404 'quotient too large in //, % or divmod')
1405 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001406
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001407 def __rtruediv__(self, other, context=None):
1408 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001409 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001410 if other is NotImplemented:
1411 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001412 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001413
1414 def __divmod__(self, other, context=None):
1415 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001416 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001417 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001418 other = _convert_other(other)
1419 if other is NotImplemented:
1420 return other
1421
1422 if context is None:
1423 context = getcontext()
1424
1425 ans = self._check_nans(other, context)
1426 if ans:
1427 return (ans, ans)
1428
1429 sign = self._sign ^ other._sign
1430 if self._isinfinity():
1431 if other._isinfinity():
1432 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1433 return ans, ans
1434 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001435 return (_SignedInfinity[sign],
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001436 context._raise_error(InvalidOperation, 'INF % x'))
1437
1438 if not other:
1439 if not self:
1440 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1441 return ans, ans
1442 else:
1443 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1444 context._raise_error(InvalidOperation, 'x % 0'))
1445
1446 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001447 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001448 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001449
1450 def __rdivmod__(self, other, context=None):
1451 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001452 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001453 if other is NotImplemented:
1454 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001455 return other.__divmod__(self, context=context)
1456
1457 def __mod__(self, other, context=None):
1458 """
1459 self % other
1460 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001461 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001462 if other is NotImplemented:
1463 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001464
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001465 if context is None:
1466 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001467
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001468 ans = self._check_nans(other, context)
1469 if ans:
1470 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001471
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001472 if self._isinfinity():
1473 return context._raise_error(InvalidOperation, 'INF % x')
1474 elif not other:
1475 if self:
1476 return context._raise_error(InvalidOperation, 'x % 0')
1477 else:
1478 return context._raise_error(DivisionUndefined, '0 % 0')
1479
1480 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001481 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001482 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001483
1484 def __rmod__(self, other, context=None):
1485 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001486 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001487 if other is NotImplemented:
1488 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001489 return other.__mod__(self, context=context)
1490
1491 def remainder_near(self, other, context=None):
1492 """
1493 Remainder nearest to 0- abs(remainder-near) <= other/2
1494 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001495 if context is None:
1496 context = getcontext()
1497
1498 other = _convert_other(other, raiseit=True)
1499
1500 ans = self._check_nans(other, context)
1501 if ans:
1502 return ans
1503
1504 # self == +/-infinity -> InvalidOperation
1505 if self._isinfinity():
1506 return context._raise_error(InvalidOperation,
1507 'remainder_near(infinity, x)')
1508
1509 # other == 0 -> either InvalidOperation or DivisionUndefined
1510 if not other:
1511 if self:
1512 return context._raise_error(InvalidOperation,
1513 'remainder_near(x, 0)')
1514 else:
1515 return context._raise_error(DivisionUndefined,
1516 'remainder_near(0, 0)')
1517
1518 # other = +/-infinity -> remainder = self
1519 if other._isinfinity():
1520 ans = Decimal(self)
1521 return ans._fix(context)
1522
1523 # self = 0 -> remainder = self, with ideal exponent
1524 ideal_exponent = min(self._exp, other._exp)
1525 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001526 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001527 return ans._fix(context)
1528
1529 # catch most cases of large or small quotient
1530 expdiff = self.adjusted() - other.adjusted()
1531 if expdiff >= context.prec + 1:
1532 # expdiff >= prec+1 => abs(self/other) > 10**prec
1533 return context._raise_error(DivisionImpossible)
1534 if expdiff <= -2:
1535 # expdiff <= -2 => abs(self/other) < 0.1
1536 ans = self._rescale(ideal_exponent, context.rounding)
1537 return ans._fix(context)
1538
1539 # adjust both arguments to have the same exponent, then divide
1540 op1 = _WorkRep(self)
1541 op2 = _WorkRep(other)
1542 if op1.exp >= op2.exp:
1543 op1.int *= 10**(op1.exp - op2.exp)
1544 else:
1545 op2.int *= 10**(op2.exp - op1.exp)
1546 q, r = divmod(op1.int, op2.int)
1547 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1548 # 10**ideal_exponent. Apply correction to ensure that
1549 # abs(remainder) <= abs(other)/2
1550 if 2*r + (q&1) > op2.int:
1551 r -= op2.int
1552 q += 1
1553
1554 if q >= 10**context.prec:
1555 return context._raise_error(DivisionImpossible)
1556
1557 # result has same sign as self unless r is negative
1558 sign = self._sign
1559 if r < 0:
1560 sign = 1-sign
1561 r = -r
1562
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001563 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001564 return ans._fix(context)
1565
1566 def __floordiv__(self, other, context=None):
1567 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001568 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001569 if other is NotImplemented:
1570 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001571
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001572 if context is None:
1573 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001574
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001575 ans = self._check_nans(other, context)
1576 if ans:
1577 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001578
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001579 if self._isinfinity():
1580 if other._isinfinity():
1581 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001582 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001583 return _SignedInfinity[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001584
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001585 if not other:
1586 if self:
1587 return context._raise_error(DivisionByZero, 'x // 0',
1588 self._sign ^ other._sign)
1589 else:
1590 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001591
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001592 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001593
1594 def __rfloordiv__(self, other, context=None):
1595 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001596 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001597 if other is NotImplemented:
1598 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001599 return other.__floordiv__(self, context=context)
1600
1601 def __float__(self):
1602 """Float representation."""
Mark Dickinsonfc33d4c2012-08-24 18:53:10 +01001603 if self._isnan():
1604 if self.is_snan():
1605 raise ValueError("Cannot convert signaling NaN to float")
1606 s = "-nan" if self._sign else "nan"
1607 else:
1608 s = str(self)
1609 return float(s)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001610
1611 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001612 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001613 if self._is_special:
1614 if self._isnan():
Mark Dickinson825fce32009-09-07 18:08:12 +00001615 raise ValueError("Cannot convert NaN to integer")
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001616 elif self._isinfinity():
Mark Dickinson825fce32009-09-07 18:08:12 +00001617 raise OverflowError("Cannot convert infinity to integer")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001618 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001619 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001620 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001621 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001622 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001623
Christian Heimes969fe572008-01-25 11:23:10 +00001624 __trunc__ = __int__
1625
Christian Heimes0bd4e112008-02-12 22:59:25 +00001626 def real(self):
1627 return self
Mark Dickinson315a20a2009-01-04 21:34:18 +00001628 real = property(real)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001629
Christian Heimes0bd4e112008-02-12 22:59:25 +00001630 def imag(self):
1631 return Decimal(0)
Mark Dickinson315a20a2009-01-04 21:34:18 +00001632 imag = property(imag)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001633
1634 def conjugate(self):
1635 return self
1636
1637 def __complex__(self):
1638 return complex(float(self))
1639
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001640 def _fix_nan(self, context):
1641 """Decapitate the payload of a NaN to fit the context"""
1642 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001643
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001644 # maximum length of payload is precision if clamp=0,
1645 # precision-1 if clamp=1.
1646 max_payload_len = context.prec - context.clamp
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001647 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001648 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1649 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001650 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001651
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001652 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001653 """Round if it is necessary to keep self within prec precision.
1654
1655 Rounds and fixes the exponent. Does not raise on a sNaN.
1656
1657 Arguments:
1658 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001659 context - context used.
1660 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001661
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001662 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001663 if self._isnan():
1664 # decapitate payload if necessary
1665 return self._fix_nan(context)
1666 else:
1667 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001668 return Decimal(self)
1669
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001670 # if self is zero then exponent should be between Etiny and
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001671 # Emax if clamp==0, and between Etiny and Etop if clamp==1.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001672 Etiny = context.Etiny()
1673 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001674 if not self:
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001675 exp_max = [context.Emax, Etop][context.clamp]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001676 new_exp = min(max(self._exp, Etiny), exp_max)
1677 if new_exp != self._exp:
1678 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001679 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001680 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001681 return Decimal(self)
1682
1683 # exp_min is the smallest allowable exponent of the result,
1684 # equal to max(self.adjusted()-context.prec+1, Etiny)
1685 exp_min = len(self._int) + self._exp - context.prec
1686 if exp_min > Etop:
1687 # overflow: exp_min > Etop iff self.adjusted() > Emax
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001688 ans = context._raise_error(Overflow, 'above Emax', self._sign)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001689 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001690 context._raise_error(Rounded)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001691 return ans
1692
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001693 self_is_subnormal = exp_min < Etiny
1694 if self_is_subnormal:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001695 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001696
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001697 # round if self has too many digits
1698 if self._exp < exp_min:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001699 digits = len(self._int) + self._exp - exp_min
1700 if digits < 0:
1701 self = _dec_from_triple(self._sign, '1', exp_min-1)
1702 digits = 0
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001703 rounding_method = self._pick_rounding_function[context.rounding]
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04001704 changed = rounding_method(self, digits)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001705 coeff = self._int[:digits] or '0'
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001706 if changed > 0:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001707 coeff = str(int(coeff)+1)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001708 if len(coeff) > context.prec:
1709 coeff = coeff[:-1]
1710 exp_min += 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001711
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001712 # check whether the rounding pushed the exponent out of range
1713 if exp_min > Etop:
1714 ans = context._raise_error(Overflow, 'above Emax', self._sign)
1715 else:
1716 ans = _dec_from_triple(self._sign, coeff, exp_min)
1717
1718 # raise the appropriate signals, taking care to respect
1719 # the precedence described in the specification
1720 if changed and self_is_subnormal:
1721 context._raise_error(Underflow)
1722 if self_is_subnormal:
1723 context._raise_error(Subnormal)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001724 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001725 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001726 context._raise_error(Rounded)
1727 if not ans:
1728 # raise Clamped on underflow to 0
1729 context._raise_error(Clamped)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001730 return ans
1731
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001732 if self_is_subnormal:
1733 context._raise_error(Subnormal)
1734
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001735 # fold down if clamp == 1 and self has too few digits
1736 if context.clamp == 1 and self._exp > Etop:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001737 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001738 self_padded = self._int + '0'*(self._exp - Etop)
1739 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001740
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001741 # here self was representable to begin with; return unchanged
1742 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001743
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001744 # for each of the rounding functions below:
1745 # self is a finite, nonzero Decimal
1746 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001747 #
1748 # each function returns either -1, 0, or 1, as follows:
1749 # 1 indicates that self should be rounded up (away from zero)
1750 # 0 indicates that self should be truncated, and that all the
1751 # digits to be truncated are zeros (so the value is unchanged)
1752 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001753
1754 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001755 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001756 if _all_zeros(self._int, prec):
1757 return 0
1758 else:
1759 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001760
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001761 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001762 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001763 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001764
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001765 def _round_half_up(self, prec):
1766 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001767 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001768 return 1
1769 elif _all_zeros(self._int, prec):
1770 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001771 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001772 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001773
1774 def _round_half_down(self, prec):
1775 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001776 if _exact_half(self._int, prec):
1777 return -1
1778 else:
1779 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001780
1781 def _round_half_even(self, prec):
1782 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001783 if _exact_half(self._int, prec) and \
1784 (prec == 0 or self._int[prec-1] in '02468'):
1785 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001786 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001787 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001788
1789 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001790 """Rounds up (not away from 0 if negative.)"""
1791 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001792 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001793 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001794 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001795
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001796 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001797 """Rounds down (not towards 0 if negative)"""
1798 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001799 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001800 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001801 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001802
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001803 def _round_05up(self, prec):
1804 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001805 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001806 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001807 else:
1808 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001809
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04001810 _pick_rounding_function = dict(
1811 ROUND_DOWN = _round_down,
1812 ROUND_UP = _round_up,
1813 ROUND_HALF_UP = _round_half_up,
1814 ROUND_HALF_DOWN = _round_half_down,
1815 ROUND_HALF_EVEN = _round_half_even,
1816 ROUND_CEILING = _round_ceiling,
1817 ROUND_FLOOR = _round_floor,
1818 ROUND_05UP = _round_05up,
1819 )
1820
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001821 def __round__(self, n=None):
1822 """Round self to the nearest integer, or to a given precision.
1823
1824 If only one argument is supplied, round a finite Decimal
1825 instance self to the nearest integer. If self is infinite or
1826 a NaN then a Python exception is raised. If self is finite
1827 and lies exactly halfway between two integers then it is
1828 rounded to the integer with even last digit.
1829
1830 >>> round(Decimal('123.456'))
1831 123
1832 >>> round(Decimal('-456.789'))
1833 -457
1834 >>> round(Decimal('-3.0'))
1835 -3
1836 >>> round(Decimal('2.5'))
1837 2
1838 >>> round(Decimal('3.5'))
1839 4
1840 >>> round(Decimal('Inf'))
1841 Traceback (most recent call last):
1842 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001843 OverflowError: cannot round an infinity
1844 >>> round(Decimal('NaN'))
1845 Traceback (most recent call last):
1846 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001847 ValueError: cannot round a NaN
1848
1849 If a second argument n is supplied, self is rounded to n
1850 decimal places using the rounding mode for the current
1851 context.
1852
1853 For an integer n, round(self, -n) is exactly equivalent to
1854 self.quantize(Decimal('1En')).
1855
1856 >>> round(Decimal('123.456'), 0)
1857 Decimal('123')
1858 >>> round(Decimal('123.456'), 2)
1859 Decimal('123.46')
1860 >>> round(Decimal('123.456'), -2)
1861 Decimal('1E+2')
1862 >>> round(Decimal('-Infinity'), 37)
1863 Decimal('NaN')
1864 >>> round(Decimal('sNaN123'), 0)
1865 Decimal('NaN123')
1866
1867 """
1868 if n is not None:
1869 # two-argument form: use the equivalent quantize call
1870 if not isinstance(n, int):
1871 raise TypeError('Second argument to round should be integral')
1872 exp = _dec_from_triple(0, '1', -n)
1873 return self.quantize(exp)
1874
1875 # one-argument form
1876 if self._is_special:
1877 if self.is_nan():
1878 raise ValueError("cannot round a NaN")
1879 else:
1880 raise OverflowError("cannot round an infinity")
1881 return int(self._rescale(0, ROUND_HALF_EVEN))
1882
1883 def __floor__(self):
1884 """Return the floor of self, as an integer.
1885
1886 For a finite Decimal instance self, return the greatest
1887 integer n such that n <= self. If self is infinite or a NaN
1888 then a Python exception is raised.
1889
1890 """
1891 if self._is_special:
1892 if self.is_nan():
1893 raise ValueError("cannot round a NaN")
1894 else:
1895 raise OverflowError("cannot round an infinity")
1896 return int(self._rescale(0, ROUND_FLOOR))
1897
1898 def __ceil__(self):
1899 """Return the ceiling of self, as an integer.
1900
1901 For a finite Decimal instance self, return the least integer n
1902 such that n >= self. If self is infinite or a NaN then a
1903 Python exception is raised.
1904
1905 """
1906 if self._is_special:
1907 if self.is_nan():
1908 raise ValueError("cannot round a NaN")
1909 else:
1910 raise OverflowError("cannot round an infinity")
1911 return int(self._rescale(0, ROUND_CEILING))
1912
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001913 def fma(self, other, third, context=None):
1914 """Fused multiply-add.
1915
1916 Returns self*other+third with no rounding of the intermediate
1917 product self*other.
1918
1919 self and other are multiplied together, with no rounding of
1920 the result. The third operand is then added to the result,
1921 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001922 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001923
1924 other = _convert_other(other, raiseit=True)
Mark Dickinsonb455e582011-05-22 12:53:18 +01001925 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001926
1927 # compute product; raise InvalidOperation if either operand is
1928 # a signaling NaN or if the product is zero times infinity.
1929 if self._is_special or other._is_special:
1930 if context is None:
1931 context = getcontext()
1932 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001933 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001934 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001935 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001936 if self._exp == 'n':
1937 product = self
1938 elif other._exp == 'n':
1939 product = other
1940 elif self._exp == 'F':
1941 if not other:
1942 return context._raise_error(InvalidOperation,
1943 'INF * 0 in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001944 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001945 elif other._exp == 'F':
1946 if not self:
1947 return context._raise_error(InvalidOperation,
1948 '0 * INF in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001949 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001950 else:
1951 product = _dec_from_triple(self._sign ^ other._sign,
1952 str(int(self._int) * int(other._int)),
1953 self._exp + other._exp)
1954
Christian Heimes8b0facf2007-12-04 19:30:01 +00001955 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001956
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001957 def _power_modulo(self, other, modulo, context=None):
1958 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001959
Stefan Krah1919b7e2012-03-21 18:25:23 +01001960 other = _convert_other(other)
1961 if other is NotImplemented:
1962 return other
1963 modulo = _convert_other(modulo)
1964 if modulo is NotImplemented:
1965 return modulo
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001966
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001967 if context is None:
1968 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001969
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001970 # deal with NaNs: if there are any sNaNs then first one wins,
1971 # (i.e. behaviour for NaNs is identical to that of fma)
1972 self_is_nan = self._isnan()
1973 other_is_nan = other._isnan()
1974 modulo_is_nan = modulo._isnan()
1975 if self_is_nan or other_is_nan or modulo_is_nan:
1976 if self_is_nan == 2:
1977 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001978 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001979 if other_is_nan == 2:
1980 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001981 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001982 if modulo_is_nan == 2:
1983 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001984 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001985 if self_is_nan:
1986 return self._fix_nan(context)
1987 if other_is_nan:
1988 return other._fix_nan(context)
1989 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001990
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001991 # check inputs: we apply same restrictions as Python's pow()
1992 if not (self._isinteger() and
1993 other._isinteger() and
1994 modulo._isinteger()):
1995 return context._raise_error(InvalidOperation,
1996 'pow() 3rd argument not allowed '
1997 'unless all arguments are integers')
1998 if other < 0:
1999 return context._raise_error(InvalidOperation,
2000 'pow() 2nd argument cannot be '
2001 'negative when 3rd argument specified')
2002 if not modulo:
2003 return context._raise_error(InvalidOperation,
2004 'pow() 3rd argument cannot be 0')
2005
2006 # additional restriction for decimal: the modulus must be less
2007 # than 10**prec in absolute value
2008 if modulo.adjusted() >= context.prec:
2009 return context._raise_error(InvalidOperation,
2010 'insufficient precision: pow() 3rd '
2011 'argument must not have more than '
2012 'precision digits')
2013
2014 # define 0**0 == NaN, for consistency with two-argument pow
2015 # (even though it hurts!)
2016 if not other and not self:
2017 return context._raise_error(InvalidOperation,
2018 'at least one of pow() 1st argument '
2019 'and 2nd argument must be nonzero ;'
2020 '0**0 is not defined')
2021
2022 # compute sign of result
2023 if other._iseven():
2024 sign = 0
2025 else:
2026 sign = self._sign
2027
2028 # convert modulo to a Python integer, and self and other to
2029 # Decimal integers (i.e. force their exponents to be >= 0)
2030 modulo = abs(int(modulo))
2031 base = _WorkRep(self.to_integral_value())
2032 exponent = _WorkRep(other.to_integral_value())
2033
2034 # compute result using integer pow()
2035 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
2036 for i in range(exponent.exp):
2037 base = pow(base, 10, modulo)
2038 base = pow(base, exponent.int, modulo)
2039
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002040 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002041
2042 def _power_exact(self, other, p):
2043 """Attempt to compute self**other exactly.
2044
2045 Given Decimals self and other and an integer p, attempt to
2046 compute an exact result for the power self**other, with p
2047 digits of precision. Return None if self**other is not
2048 exactly representable in p digits.
2049
2050 Assumes that elimination of special cases has already been
2051 performed: self and other must both be nonspecial; self must
2052 be positive and not numerically equal to 1; other must be
2053 nonzero. For efficiency, other._exp should not be too large,
2054 so that 10**abs(other._exp) is a feasible calculation."""
2055
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002056 # In the comments below, we write x for the value of self and y for the
2057 # value of other. Write x = xc*10**xe and abs(y) = yc*10**ye, with xc
2058 # and yc positive integers not divisible by 10.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002059
2060 # The main purpose of this method is to identify the *failure*
2061 # of x**y to be exactly representable with as little effort as
2062 # possible. So we look for cheap and easy tests that
2063 # eliminate the possibility of x**y being exact. Only if all
2064 # these tests are passed do we go on to actually compute x**y.
2065
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002066 # Here's the main idea. Express y as a rational number m/n, with m and
2067 # n relatively prime and n>0. Then for x**y to be exactly
2068 # representable (at *any* precision), xc must be the nth power of a
2069 # positive integer and xe must be divisible by n. If y is negative
2070 # then additionally xc must be a power of either 2 or 5, hence a power
2071 # of 2**n or 5**n.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002072 #
2073 # There's a limit to how small |y| can be: if y=m/n as above
2074 # then:
2075 #
2076 # (1) if xc != 1 then for the result to be representable we
2077 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
2078 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
2079 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
2080 # representable.
2081 #
2082 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
2083 # |y| < 1/|xe| then the result is not representable.
2084 #
2085 # Note that since x is not equal to 1, at least one of (1) and
2086 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
2087 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
2088 #
2089 # There's also a limit to how large y can be, at least if it's
2090 # positive: the normalized result will have coefficient xc**y,
2091 # so if it's representable then xc**y < 10**p, and y <
2092 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
2093 # not exactly representable.
2094
2095 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
2096 # so |y| < 1/xe and the result is not representable.
2097 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
2098 # < 1/nbits(xc).
2099
2100 x = _WorkRep(self)
2101 xc, xe = x.int, x.exp
2102 while xc % 10 == 0:
2103 xc //= 10
2104 xe += 1
2105
2106 y = _WorkRep(other)
2107 yc, ye = y.int, y.exp
2108 while yc % 10 == 0:
2109 yc //= 10
2110 ye += 1
2111
2112 # case where xc == 1: result is 10**(xe*y), with xe*y
2113 # required to be an integer
2114 if xc == 1:
Mark Dickinsona1236312010-07-08 19:03:34 +00002115 xe *= yc
2116 # result is now 10**(xe * 10**ye); xe * 10**ye must be integral
2117 while xe % 10 == 0:
2118 xe //= 10
2119 ye += 1
2120 if ye < 0:
2121 return None
2122 exponent = xe * 10**ye
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002123 if y.sign == 1:
2124 exponent = -exponent
2125 # if other is a nonnegative integer, use ideal exponent
2126 if other._isinteger() and other._sign == 0:
2127 ideal_exponent = self._exp*int(other)
2128 zeros = min(exponent-ideal_exponent, p-1)
2129 else:
2130 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002131 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002132
2133 # case where y is negative: xc must be either a power
2134 # of 2 or a power of 5.
2135 if y.sign == 1:
2136 last_digit = xc % 10
2137 if last_digit in (2,4,6,8):
2138 # quick test for power of 2
2139 if xc & -xc != xc:
2140 return None
2141 # now xc is a power of 2; e is its exponent
2142 e = _nbits(xc)-1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002143
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002144 # We now have:
2145 #
2146 # x = 2**e * 10**xe, e > 0, and y < 0.
2147 #
2148 # The exact result is:
2149 #
2150 # x**y = 5**(-e*y) * 10**(e*y + xe*y)
2151 #
2152 # provided that both e*y and xe*y are integers. Note that if
2153 # 5**(-e*y) >= 10**p, then the result can't be expressed
2154 # exactly with p digits of precision.
2155 #
2156 # Using the above, we can guard against large values of ye.
2157 # 93/65 is an upper bound for log(10)/log(5), so if
2158 #
2159 # ye >= len(str(93*p//65))
2160 #
2161 # then
2162 #
2163 # -e*y >= -y >= 10**ye > 93*p/65 > p*log(10)/log(5),
2164 #
2165 # so 5**(-e*y) >= 10**p, and the coefficient of the result
2166 # can't be expressed in p digits.
2167
2168 # emax >= largest e such that 5**e < 10**p.
2169 emax = p*93//65
2170 if ye >= len(str(emax)):
2171 return None
2172
2173 # Find -e*y and -xe*y; both must be integers
2174 e = _decimal_lshift_exact(e * yc, ye)
2175 xe = _decimal_lshift_exact(xe * yc, ye)
2176 if e is None or xe is None:
2177 return None
2178
2179 if e > emax:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002180 return None
2181 xc = 5**e
2182
2183 elif last_digit == 5:
2184 # e >= log_5(xc) if xc is a power of 5; we have
2185 # equality all the way up to xc=5**2658
2186 e = _nbits(xc)*28//65
2187 xc, remainder = divmod(5**e, xc)
2188 if remainder:
2189 return None
2190 while xc % 5 == 0:
2191 xc //= 5
2192 e -= 1
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002193
2194 # Guard against large values of ye, using the same logic as in
2195 # the 'xc is a power of 2' branch. 10/3 is an upper bound for
2196 # log(10)/log(2).
2197 emax = p*10//3
2198 if ye >= len(str(emax)):
2199 return None
2200
2201 e = _decimal_lshift_exact(e * yc, ye)
2202 xe = _decimal_lshift_exact(xe * yc, ye)
2203 if e is None or xe is None:
2204 return None
2205
2206 if e > emax:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002207 return None
2208 xc = 2**e
2209 else:
2210 return None
2211
2212 if xc >= 10**p:
2213 return None
2214 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002215 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002216
2217 # now y is positive; find m and n such that y = m/n
2218 if ye >= 0:
2219 m, n = yc*10**ye, 1
2220 else:
2221 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2222 return None
2223 xc_bits = _nbits(xc)
2224 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2225 return None
2226 m, n = yc, 10**(-ye)
2227 while m % 2 == n % 2 == 0:
2228 m //= 2
2229 n //= 2
2230 while m % 5 == n % 5 == 0:
2231 m //= 5
2232 n //= 5
2233
2234 # compute nth root of xc*10**xe
2235 if n > 1:
2236 # if 1 < xc < 2**n then xc isn't an nth power
2237 if xc != 1 and xc_bits <= n:
2238 return None
2239
2240 xe, rem = divmod(xe, n)
2241 if rem != 0:
2242 return None
2243
2244 # compute nth root of xc using Newton's method
2245 a = 1 << -(-_nbits(xc)//n) # initial estimate
2246 while True:
2247 q, r = divmod(xc, a**(n-1))
2248 if a <= q:
2249 break
2250 else:
2251 a = (a*(n-1) + q)//n
2252 if not (a == q and r == 0):
2253 return None
2254 xc = a
2255
2256 # now xc*10**xe is the nth root of the original xc*10**xe
2257 # compute mth power of xc*10**xe
2258
2259 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2260 # 10**p and the result is not representable.
2261 if xc > 1 and m > p*100//_log10_lb(xc):
2262 return None
2263 xc = xc**m
2264 xe *= m
2265 if xc > 10**p:
2266 return None
2267
2268 # by this point the result *is* exactly representable
2269 # adjust the exponent to get as close as possible to the ideal
2270 # exponent, if necessary
2271 str_xc = str(xc)
2272 if other._isinteger() and other._sign == 0:
2273 ideal_exponent = self._exp*int(other)
2274 zeros = min(xe-ideal_exponent, p-len(str_xc))
2275 else:
2276 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002277 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002278
2279 def __pow__(self, other, modulo=None, context=None):
2280 """Return self ** other [ % modulo].
2281
2282 With two arguments, compute self**other.
2283
2284 With three arguments, compute (self**other) % modulo. For the
2285 three argument form, the following restrictions on the
2286 arguments hold:
2287
2288 - all three arguments must be integral
2289 - other must be nonnegative
2290 - either self or other (or both) must be nonzero
2291 - modulo must be nonzero and must have at most p digits,
2292 where p is the context precision.
2293
2294 If any of these restrictions is violated the InvalidOperation
2295 flag is raised.
2296
2297 The result of pow(self, other, modulo) is identical to the
2298 result that would be obtained by computing (self**other) %
2299 modulo with unbounded precision, but is computed more
2300 efficiently. It is always exact.
2301 """
2302
2303 if modulo is not None:
2304 return self._power_modulo(other, modulo, context)
2305
2306 other = _convert_other(other)
2307 if other is NotImplemented:
2308 return other
2309
2310 if context is None:
2311 context = getcontext()
2312
2313 # either argument is a NaN => result is NaN
2314 ans = self._check_nans(other, context)
2315 if ans:
2316 return ans
2317
2318 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2319 if not other:
2320 if not self:
2321 return context._raise_error(InvalidOperation, '0 ** 0')
2322 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002323 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002324
2325 # result has sign 1 iff self._sign is 1 and other is an odd integer
2326 result_sign = 0
2327 if self._sign == 1:
2328 if other._isinteger():
2329 if not other._iseven():
2330 result_sign = 1
2331 else:
2332 # -ve**noninteger = NaN
2333 # (-0)**noninteger = 0**noninteger
2334 if self:
2335 return context._raise_error(InvalidOperation,
2336 'x ** y with x negative and y not an integer')
2337 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002338 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002339
2340 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2341 if not self:
2342 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002343 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002344 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002345 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002346
2347 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002348 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002349 if other._sign == 0:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002350 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002351 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002352 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002353
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002354 # 1**other = 1, but the choice of exponent and the flags
2355 # depend on the exponent of self, and on whether other is a
2356 # positive integer, a negative integer, or neither
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002357 if self == _One:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002358 if other._isinteger():
2359 # exp = max(self._exp*max(int(other), 0),
2360 # 1-context.prec) but evaluating int(other) directly
2361 # is dangerous until we know other is small (other
2362 # could be 1e999999999)
2363 if other._sign == 1:
2364 multiplier = 0
2365 elif other > context.prec:
2366 multiplier = context.prec
2367 else:
2368 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002369
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002370 exp = self._exp * multiplier
2371 if exp < 1-context.prec:
2372 exp = 1-context.prec
2373 context._raise_error(Rounded)
2374 else:
2375 context._raise_error(Inexact)
2376 context._raise_error(Rounded)
2377 exp = 1-context.prec
2378
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002379 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002380
2381 # compute adjusted exponent of self
2382 self_adj = self.adjusted()
2383
2384 # self ** infinity is infinity if self > 1, 0 if self < 1
2385 # self ** -infinity is infinity if self < 1, 0 if self > 1
2386 if other._isinfinity():
2387 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002388 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002389 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002390 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002391
2392 # from here on, the result always goes through the call
2393 # to _fix at the end of this function.
2394 ans = None
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002395 exact = False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002396
2397 # crude test to catch cases of extreme overflow/underflow. If
2398 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2399 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2400 # self**other >= 10**(Emax+1), so overflow occurs. The test
2401 # for underflow is similar.
2402 bound = self._log10_exp_bound() + other.adjusted()
2403 if (self_adj >= 0) == (other._sign == 0):
2404 # self > 1 and other +ve, or self < 1 and other -ve
2405 # possibility of overflow
2406 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002407 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002408 else:
2409 # self > 1 and other -ve, or self < 1 and other +ve
2410 # possibility of underflow to 0
2411 Etiny = context.Etiny()
2412 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002413 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002414
2415 # try for an exact result with precision +1
2416 if ans is None:
2417 ans = self._power_exact(other, context.prec + 1)
Mark Dickinsone42f1bb2010-07-08 19:09:16 +00002418 if ans is not None:
2419 if result_sign == 1:
2420 ans = _dec_from_triple(1, ans._int, ans._exp)
2421 exact = True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002422
2423 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2424 if ans is None:
2425 p = context.prec
2426 x = _WorkRep(self)
2427 xc, xe = x.int, x.exp
2428 y = _WorkRep(other)
2429 yc, ye = y.int, y.exp
2430 if y.sign == 1:
2431 yc = -yc
2432
2433 # compute correctly rounded result: start with precision +3,
2434 # then increase precision until result is unambiguously roundable
2435 extra = 3
2436 while True:
2437 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2438 if coeff % (5*10**(len(str(coeff))-p-1)):
2439 break
2440 extra += 3
2441
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002442 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002443
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002444 # unlike exp, ln and log10, the power function respects the
2445 # rounding mode; no need to switch to ROUND_HALF_EVEN here
2446
2447 # There's a difficulty here when 'other' is not an integer and
2448 # the result is exact. In this case, the specification
2449 # requires that the Inexact flag be raised (in spite of
2450 # exactness), but since the result is exact _fix won't do this
2451 # for us. (Correspondingly, the Underflow signal should also
2452 # be raised for subnormal results.) We can't directly raise
2453 # these signals either before or after calling _fix, since
2454 # that would violate the precedence for signals. So we wrap
2455 # the ._fix call in a temporary context, and reraise
2456 # afterwards.
2457 if exact and not other._isinteger():
2458 # pad with zeros up to length context.prec+1 if necessary; this
2459 # ensures that the Rounded signal will be raised.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002460 if len(ans._int) <= context.prec:
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002461 expdiff = context.prec + 1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002462 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2463 ans._exp-expdiff)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002464
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002465 # create a copy of the current context, with cleared flags/traps
2466 newcontext = context.copy()
2467 newcontext.clear_flags()
2468 for exception in _signals:
2469 newcontext.traps[exception] = 0
2470
2471 # round in the new context
2472 ans = ans._fix(newcontext)
2473
2474 # raise Inexact, and if necessary, Underflow
2475 newcontext._raise_error(Inexact)
2476 if newcontext.flags[Subnormal]:
2477 newcontext._raise_error(Underflow)
2478
2479 # propagate signals to the original context; _fix could
2480 # have raised any of Overflow, Underflow, Subnormal,
2481 # Inexact, Rounded, Clamped. Overflow needs the correct
2482 # arguments. Note that the order of the exceptions is
2483 # important here.
2484 if newcontext.flags[Overflow]:
2485 context._raise_error(Overflow, 'above Emax', ans._sign)
2486 for exception in Underflow, Subnormal, Inexact, Rounded, Clamped:
2487 if newcontext.flags[exception]:
2488 context._raise_error(exception)
2489
2490 else:
2491 ans = ans._fix(context)
2492
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002493 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002494
2495 def __rpow__(self, other, context=None):
2496 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002497 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002498 if other is NotImplemented:
2499 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002500 return other.__pow__(self, context=context)
2501
2502 def normalize(self, context=None):
2503 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002504
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002505 if context is None:
2506 context = getcontext()
2507
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002508 if self._is_special:
2509 ans = self._check_nans(context=context)
2510 if ans:
2511 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002512
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002513 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002514 if dup._isinfinity():
2515 return dup
2516
2517 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002518 return _dec_from_triple(dup._sign, '0', 0)
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00002519 exp_max = [context.Emax, context.Etop()][context.clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002520 end = len(dup._int)
2521 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002522 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002523 exp += 1
2524 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002525 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002526
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002527 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002528 """Quantize self so its exponent is the same as that of exp.
2529
2530 Similar to self._rescale(exp._exp) but with error checking.
2531 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002532 exp = _convert_other(exp, raiseit=True)
2533
2534 if context is None:
2535 context = getcontext()
2536 if rounding is None:
2537 rounding = context.rounding
2538
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002539 if self._is_special or exp._is_special:
2540 ans = self._check_nans(exp, context)
2541 if ans:
2542 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002543
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002544 if exp._isinfinity() or self._isinfinity():
2545 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002546 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002547 return context._raise_error(InvalidOperation,
2548 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002549
2550 # if we're not watching exponents, do a simple rescale
2551 if not watchexp:
2552 ans = self._rescale(exp._exp, rounding)
2553 # raise Inexact and Rounded where appropriate
2554 if ans._exp > self._exp:
2555 context._raise_error(Rounded)
2556 if ans != self:
2557 context._raise_error(Inexact)
2558 return ans
2559
2560 # exp._exp should be between Etiny and Emax
2561 if not (context.Etiny() <= exp._exp <= context.Emax):
2562 return context._raise_error(InvalidOperation,
2563 'target exponent out of bounds in quantize')
2564
2565 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002566 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002567 return ans._fix(context)
2568
2569 self_adjusted = self.adjusted()
2570 if self_adjusted > context.Emax:
2571 return context._raise_error(InvalidOperation,
2572 'exponent of quantize result too large for current context')
2573 if self_adjusted - exp._exp + 1 > context.prec:
2574 return context._raise_error(InvalidOperation,
2575 'quantize result has too many digits for current context')
2576
2577 ans = self._rescale(exp._exp, rounding)
2578 if ans.adjusted() > context.Emax:
2579 return context._raise_error(InvalidOperation,
2580 'exponent of quantize result too large for current context')
2581 if len(ans._int) > context.prec:
2582 return context._raise_error(InvalidOperation,
2583 'quantize result has too many digits for current context')
2584
2585 # raise appropriate flags
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002586 if ans and ans.adjusted() < context.Emin:
2587 context._raise_error(Subnormal)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002588 if ans._exp > self._exp:
2589 if ans != self:
2590 context._raise_error(Inexact)
2591 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002592
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002593 # call to fix takes care of any necessary folddown, and
2594 # signals Clamped if necessary
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002595 ans = ans._fix(context)
2596 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002597
Stefan Krah040e3112012-12-15 22:33:33 +01002598 def same_quantum(self, other, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002599 """Return True if self and other have the same exponent; otherwise
2600 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002601
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002602 If either operand is a special value, the following rules are used:
2603 * return True if both operands are infinities
2604 * return True if both operands are NaNs
2605 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002606 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002607 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002608 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002609 return (self.is_nan() and other.is_nan() or
2610 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002611 return self._exp == other._exp
2612
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002613 def _rescale(self, exp, rounding):
2614 """Rescale self so that the exponent is exp, either by padding with zeros
2615 or by truncating digits, using the given rounding mode.
2616
2617 Specials are returned without change. This operation is
2618 quiet: it raises no flags, and uses no information from the
2619 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002620
2621 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002622 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002623 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002624 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002625 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002626 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002627 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002628
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002629 if self._exp >= exp:
2630 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002631 return _dec_from_triple(self._sign,
2632 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002633
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002634 # too many digits; round and lose data. If self.adjusted() <
2635 # exp-1, replace self by 10**(exp-1) before rounding
2636 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002637 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002638 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002639 digits = 0
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04002640 this_function = self._pick_rounding_function[rounding]
2641 changed = this_function(self, digits)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002642 coeff = self._int[:digits] or '0'
2643 if changed == 1:
2644 coeff = str(int(coeff)+1)
2645 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002646
Christian Heimesf16baeb2008-02-29 14:57:44 +00002647 def _round(self, places, rounding):
2648 """Round a nonzero, nonspecial Decimal to a fixed number of
2649 significant figures, using the given rounding mode.
2650
2651 Infinities, NaNs and zeros are returned unaltered.
2652
2653 This operation is quiet: it raises no flags, and uses no
2654 information from the context.
2655
2656 """
2657 if places <= 0:
2658 raise ValueError("argument should be at least 1 in _round")
2659 if self._is_special or not self:
2660 return Decimal(self)
2661 ans = self._rescale(self.adjusted()+1-places, rounding)
2662 # it can happen that the rescale alters the adjusted exponent;
2663 # for example when rounding 99.97 to 3 significant figures.
2664 # When this happens we end up with an extra 0 at the end of
2665 # the number; a second rescale fixes this.
2666 if ans.adjusted() != self.adjusted():
2667 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2668 return ans
2669
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002670 def to_integral_exact(self, rounding=None, context=None):
2671 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002672
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002673 If no rounding mode is specified, take the rounding mode from
2674 the context. This method raises the Rounded and Inexact flags
2675 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002676
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002677 See also: to_integral_value, which does exactly the same as
2678 this method except that it doesn't raise Inexact or Rounded.
2679 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002680 if self._is_special:
2681 ans = self._check_nans(context=context)
2682 if ans:
2683 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002684 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002685 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002686 return Decimal(self)
2687 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002688 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002689 if context is None:
2690 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002691 if rounding is None:
2692 rounding = context.rounding
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002693 ans = self._rescale(0, rounding)
2694 if ans != self:
2695 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002696 context._raise_error(Rounded)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002697 return ans
2698
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002699 def to_integral_value(self, rounding=None, context=None):
2700 """Rounds to the nearest integer, without raising inexact, rounded."""
2701 if context is None:
2702 context = getcontext()
2703 if rounding is None:
2704 rounding = context.rounding
2705 if self._is_special:
2706 ans = self._check_nans(context=context)
2707 if ans:
2708 return ans
2709 return Decimal(self)
2710 if self._exp >= 0:
2711 return Decimal(self)
2712 else:
2713 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002714
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002715 # the method name changed, but we provide also the old one, for compatibility
2716 to_integral = to_integral_value
2717
2718 def sqrt(self, context=None):
2719 """Return the square root of self."""
Christian Heimes0348fb62008-03-26 12:55:56 +00002720 if context is None:
2721 context = getcontext()
2722
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002723 if self._is_special:
2724 ans = self._check_nans(context=context)
2725 if ans:
2726 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002727
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002728 if self._isinfinity() and self._sign == 0:
2729 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002730
2731 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002732 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002733 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002734 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002735
2736 if self._sign == 1:
2737 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2738
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002739 # At this point self represents a positive number. Let p be
2740 # the desired precision and express self in the form c*100**e
2741 # with c a positive real number and e an integer, c and e
2742 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2743 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2744 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2745 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2746 # the closest integer to sqrt(c) with the even integer chosen
2747 # in the case of a tie.
2748 #
2749 # To ensure correct rounding in all cases, we use the
2750 # following trick: we compute the square root to an extra
2751 # place (precision p+1 instead of precision p), rounding down.
2752 # Then, if the result is inexact and its last digit is 0 or 5,
2753 # we increase the last digit to 1 or 6 respectively; if it's
2754 # exact we leave the last digit alone. Now the final round to
2755 # p places (or fewer in the case of underflow) will round
2756 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002757
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002758 # use an extra digit of precision
2759 prec = context.prec+1
2760
2761 # write argument in the form c*100**e where e = self._exp//2
2762 # is the 'ideal' exponent, to be used if the square root is
2763 # exactly representable. l is the number of 'digits' of c in
2764 # base 100, so that 100**(l-1) <= c < 100**l.
2765 op = _WorkRep(self)
2766 e = op.exp >> 1
2767 if op.exp & 1:
2768 c = op.int * 10
2769 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002770 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002771 c = op.int
2772 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002773
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002774 # rescale so that c has exactly prec base 100 'digits'
2775 shift = prec-l
2776 if shift >= 0:
2777 c *= 100**shift
2778 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002779 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002780 c, remainder = divmod(c, 100**-shift)
2781 exact = not remainder
2782 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002783
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002784 # find n = floor(sqrt(c)) using Newton's method
2785 n = 10**prec
2786 while True:
2787 q = c//n
2788 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002789 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002790 else:
2791 n = n + q >> 1
2792 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002793
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002794 if exact:
2795 # result is exact; rescale to use ideal exponent e
2796 if shift >= 0:
2797 # assert n % 10**shift == 0
2798 n //= 10**shift
2799 else:
2800 n *= 10**-shift
2801 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002802 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002803 # result is not exact; fix last digit as described above
2804 if n % 5 == 0:
2805 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002806
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002807 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002808
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002809 # round, and fit to current context
2810 context = context._shallow_copy()
2811 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002812 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002813 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002814
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002815 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002816
2817 def max(self, other, context=None):
2818 """Returns the larger value.
2819
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002820 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002821 NaN (and signals if one is sNaN). Also rounds.
2822 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002823 other = _convert_other(other, raiseit=True)
2824
2825 if context is None:
2826 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002827
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002828 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002829 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002830 # number is always returned
2831 sn = self._isnan()
2832 on = other._isnan()
2833 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002834 if on == 1 and sn == 0:
2835 return self._fix(context)
2836 if sn == 1 and on == 0:
2837 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002838 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002839
Christian Heimes77c02eb2008-02-09 02:18:51 +00002840 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002841 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002842 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002843 # then an ordering is applied:
2844 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002845 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002846 # positive sign and min returns the operand with the negative sign
2847 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002848 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002849 # the result. This is exactly the ordering used in compare_total.
2850 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002851
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002852 if c == -1:
2853 ans = other
2854 else:
2855 ans = self
2856
Christian Heimes2c181612007-12-17 20:04:13 +00002857 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002858
2859 def min(self, other, context=None):
2860 """Returns the smaller value.
2861
Guido van Rossumd8faa362007-04-27 19:54:29 +00002862 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002863 NaN (and signals if one is sNaN). Also rounds.
2864 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002865 other = _convert_other(other, raiseit=True)
2866
2867 if context is None:
2868 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002869
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002870 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002871 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002872 # number is always returned
2873 sn = self._isnan()
2874 on = other._isnan()
2875 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002876 if on == 1 and sn == 0:
2877 return self._fix(context)
2878 if sn == 1 and on == 0:
2879 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002880 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002881
Christian Heimes77c02eb2008-02-09 02:18:51 +00002882 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002883 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002884 c = self.compare_total(other)
2885
2886 if c == -1:
2887 ans = self
2888 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002889 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002890
Christian Heimes2c181612007-12-17 20:04:13 +00002891 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002892
2893 def _isinteger(self):
2894 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002895 if self._is_special:
2896 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002897 if self._exp >= 0:
2898 return True
2899 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002900 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002901
2902 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002903 """Returns True if self is even. Assumes self is an integer."""
2904 if not self or self._exp > 0:
2905 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002906 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002907
2908 def adjusted(self):
2909 """Return the adjusted exponent of self"""
2910 try:
2911 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002912 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002913 except TypeError:
2914 return 0
2915
Stefan Krah040e3112012-12-15 22:33:33 +01002916 def canonical(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002917 """Returns the same Decimal object.
2918
2919 As we do not have different encodings for the same number, the
2920 received object already is in its canonical form.
2921 """
2922 return self
2923
2924 def compare_signal(self, other, context=None):
2925 """Compares self to the other operand numerically.
2926
2927 It's pretty much like compare(), but all NaNs signal, with signaling
2928 NaNs taking precedence over quiet NaNs.
2929 """
Christian Heimes77c02eb2008-02-09 02:18:51 +00002930 other = _convert_other(other, raiseit = True)
2931 ans = self._compare_check_nans(other, context)
2932 if ans:
2933 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002934 return self.compare(other, context=context)
2935
Stefan Krah040e3112012-12-15 22:33:33 +01002936 def compare_total(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002937 """Compares self to other using the abstract representations.
2938
2939 This is not like the standard compare, which use their numerical
2940 value. Note that a total ordering is defined for all possible abstract
2941 representations.
2942 """
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00002943 other = _convert_other(other, raiseit=True)
2944
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002945 # if one is negative and the other is positive, it's easy
2946 if self._sign and not other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002947 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002948 if not self._sign and other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002949 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002950 sign = self._sign
2951
2952 # let's handle both NaN types
2953 self_nan = self._isnan()
2954 other_nan = other._isnan()
2955 if self_nan or other_nan:
2956 if self_nan == other_nan:
Mark Dickinsond314e1b2009-08-28 13:39:53 +00002957 # compare payloads as though they're integers
2958 self_key = len(self._int), self._int
2959 other_key = len(other._int), other._int
2960 if self_key < other_key:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002961 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002962 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002963 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002964 return _NegativeOne
Mark Dickinsond314e1b2009-08-28 13:39:53 +00002965 if self_key > other_key:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002966 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002967 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002968 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002969 return _One
2970 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002971
2972 if sign:
2973 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002974 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002975 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002976 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002977 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002978 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002979 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002980 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002981 else:
2982 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002983 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002984 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002985 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002986 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002987 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002988 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002989 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002990
2991 if self < other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002992 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002993 if self > other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002994 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002995
2996 if self._exp < other._exp:
2997 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002998 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002999 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003000 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003001 if self._exp > other._exp:
3002 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003003 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003004 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003005 return _One
3006 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003007
3008
Stefan Krah040e3112012-12-15 22:33:33 +01003009 def compare_total_mag(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003010 """Compares self to other using abstract repr., ignoring sign.
3011
3012 Like compare_total, but with operand's sign ignored and assumed to be 0.
3013 """
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003014 other = _convert_other(other, raiseit=True)
3015
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003016 s = self.copy_abs()
3017 o = other.copy_abs()
3018 return s.compare_total(o)
3019
3020 def copy_abs(self):
3021 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003022 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003023
3024 def copy_negate(self):
3025 """Returns a copy with the sign inverted."""
3026 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003027 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003028 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003029 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003030
Stefan Krah040e3112012-12-15 22:33:33 +01003031 def copy_sign(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003032 """Returns self with the sign of other."""
Mark Dickinson84230a12010-02-18 14:49:50 +00003033 other = _convert_other(other, raiseit=True)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003034 return _dec_from_triple(other._sign, self._int,
3035 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003036
3037 def exp(self, context=None):
3038 """Returns e ** self."""
3039
3040 if context is None:
3041 context = getcontext()
3042
3043 # exp(NaN) = NaN
3044 ans = self._check_nans(context=context)
3045 if ans:
3046 return ans
3047
3048 # exp(-Infinity) = 0
3049 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003050 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003051
3052 # exp(0) = 1
3053 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003054 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003055
3056 # exp(Infinity) = Infinity
3057 if self._isinfinity() == 1:
3058 return Decimal(self)
3059
3060 # the result is now guaranteed to be inexact (the true
3061 # mathematical result is transcendental). There's no need to
3062 # raise Rounded and Inexact here---they'll always be raised as
3063 # a result of the call to _fix.
3064 p = context.prec
3065 adj = self.adjusted()
3066
3067 # we only need to do any computation for quite a small range
3068 # of adjusted exponents---for example, -29 <= adj <= 10 for
3069 # the default context. For smaller exponent the result is
3070 # indistinguishable from 1 at the given precision, while for
3071 # larger exponent the result either overflows or underflows.
3072 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
3073 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003074 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003075 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
3076 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003077 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003078 elif self._sign == 0 and adj < -p:
3079 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003080 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003081 elif self._sign == 1 and adj < -p-1:
3082 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003083 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003084 # general case
3085 else:
3086 op = _WorkRep(self)
3087 c, e = op.int, op.exp
3088 if op.sign == 1:
3089 c = -c
3090
3091 # compute correctly rounded result: increase precision by
3092 # 3 digits at a time until we get an unambiguously
3093 # roundable result
3094 extra = 3
3095 while True:
3096 coeff, exp = _dexp(c, e, p+extra)
3097 if coeff % (5*10**(len(str(coeff))-p-1)):
3098 break
3099 extra += 3
3100
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003101 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003102
3103 # at this stage, ans should round correctly with *any*
3104 # rounding mode, not just with ROUND_HALF_EVEN
3105 context = context._shallow_copy()
3106 rounding = context._set_rounding(ROUND_HALF_EVEN)
3107 ans = ans._fix(context)
3108 context.rounding = rounding
3109
3110 return ans
3111
3112 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003113 """Return True if self is canonical; otherwise return False.
3114
3115 Currently, the encoding of a Decimal instance is always
3116 canonical, so this method returns True for any Decimal.
3117 """
3118 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003119
3120 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003121 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003122
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003123 A Decimal instance is considered finite if it is neither
3124 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003125 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003126 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003127
3128 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003129 """Return True if self is infinite; otherwise return False."""
3130 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003131
3132 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003133 """Return True if self is a qNaN or sNaN; otherwise return False."""
3134 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003135
3136 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003137 """Return True if self is a normal number; otherwise return False."""
3138 if self._is_special or not self:
3139 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003140 if context is None:
3141 context = getcontext()
Mark Dickinson06bb6742009-10-20 13:38:04 +00003142 return context.Emin <= self.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003143
3144 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003145 """Return True if self is a quiet NaN; otherwise return False."""
3146 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003147
3148 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003149 """Return True if self is negative; otherwise return False."""
3150 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003151
3152 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003153 """Return True if self is a signaling NaN; otherwise return False."""
3154 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003155
3156 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003157 """Return True if self is subnormal; otherwise return False."""
3158 if self._is_special or not self:
3159 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003160 if context is None:
3161 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003162 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003163
3164 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003165 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003166 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003167
3168 def _ln_exp_bound(self):
3169 """Compute a lower bound for the adjusted exponent of self.ln().
3170 In other words, compute r such that self.ln() >= 10**r. Assumes
3171 that self is finite and positive and that self != 1.
3172 """
3173
3174 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
3175 adj = self._exp + len(self._int) - 1
3176 if adj >= 1:
3177 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
3178 return len(str(adj*23//10)) - 1
3179 if adj <= -2:
3180 # argument <= 0.1
3181 return len(str((-1-adj)*23//10)) - 1
3182 op = _WorkRep(self)
3183 c, e = op.int, op.exp
3184 if adj == 0:
3185 # 1 < self < 10
3186 num = str(c-10**-e)
3187 den = str(c)
3188 return len(num) - len(den) - (num < den)
3189 # adj == -1, 0.1 <= self < 1
3190 return e + len(str(10**-e - c)) - 1
3191
3192
3193 def ln(self, context=None):
3194 """Returns the natural (base e) logarithm of self."""
3195
3196 if context is None:
3197 context = getcontext()
3198
3199 # ln(NaN) = NaN
3200 ans = self._check_nans(context=context)
3201 if ans:
3202 return ans
3203
3204 # ln(0.0) == -Infinity
3205 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003206 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003207
3208 # ln(Infinity) = Infinity
3209 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003210 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003211
3212 # ln(1.0) == 0.0
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003213 if self == _One:
3214 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003215
3216 # ln(negative) raises InvalidOperation
3217 if self._sign == 1:
3218 return context._raise_error(InvalidOperation,
3219 'ln of a negative value')
3220
3221 # result is irrational, so necessarily inexact
3222 op = _WorkRep(self)
3223 c, e = op.int, op.exp
3224 p = context.prec
3225
3226 # correctly rounded result: repeatedly increase precision by 3
3227 # until we get an unambiguously roundable result
3228 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3229 while True:
3230 coeff = _dlog(c, e, places)
3231 # assert len(str(abs(coeff)))-p >= 1
3232 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3233 break
3234 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003235 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003236
3237 context = context._shallow_copy()
3238 rounding = context._set_rounding(ROUND_HALF_EVEN)
3239 ans = ans._fix(context)
3240 context.rounding = rounding
3241 return ans
3242
3243 def _log10_exp_bound(self):
3244 """Compute a lower bound for the adjusted exponent of self.log10().
3245 In other words, find r such that self.log10() >= 10**r.
3246 Assumes that self is finite and positive and that self != 1.
3247 """
3248
3249 # For x >= 10 or x < 0.1 we only need a bound on the integer
3250 # part of log10(self), and this comes directly from the
3251 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3252 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3253 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3254
3255 adj = self._exp + len(self._int) - 1
3256 if adj >= 1:
3257 # self >= 10
3258 return len(str(adj))-1
3259 if adj <= -2:
3260 # self < 0.1
3261 return len(str(-1-adj))-1
3262 op = _WorkRep(self)
3263 c, e = op.int, op.exp
3264 if adj == 0:
3265 # 1 < self < 10
3266 num = str(c-10**-e)
3267 den = str(231*c)
3268 return len(num) - len(den) - (num < den) + 2
3269 # adj == -1, 0.1 <= self < 1
3270 num = str(10**-e-c)
3271 return len(num) + e - (num < "231") - 1
3272
3273 def log10(self, context=None):
3274 """Returns the base 10 logarithm of self."""
3275
3276 if context is None:
3277 context = getcontext()
3278
3279 # log10(NaN) = NaN
3280 ans = self._check_nans(context=context)
3281 if ans:
3282 return ans
3283
3284 # log10(0.0) == -Infinity
3285 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003286 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003287
3288 # log10(Infinity) = Infinity
3289 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003290 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003291
3292 # log10(negative or -Infinity) raises InvalidOperation
3293 if self._sign == 1:
3294 return context._raise_error(InvalidOperation,
3295 'log10 of a negative value')
3296
3297 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003298 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003299 # answer may need rounding
3300 ans = Decimal(self._exp + len(self._int) - 1)
3301 else:
3302 # result is irrational, so necessarily inexact
3303 op = _WorkRep(self)
3304 c, e = op.int, op.exp
3305 p = context.prec
3306
3307 # correctly rounded result: repeatedly increase precision
3308 # until result is unambiguously roundable
3309 places = p-self._log10_exp_bound()+2
3310 while True:
3311 coeff = _dlog10(c, e, places)
3312 # assert len(str(abs(coeff)))-p >= 1
3313 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3314 break
3315 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003316 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003317
3318 context = context._shallow_copy()
3319 rounding = context._set_rounding(ROUND_HALF_EVEN)
3320 ans = ans._fix(context)
3321 context.rounding = rounding
3322 return ans
3323
3324 def logb(self, context=None):
3325 """ Returns the exponent of the magnitude of self's MSD.
3326
3327 The result is the integer which is the exponent of the magnitude
3328 of the most significant digit of self (as though it were truncated
3329 to a single digit while maintaining the value of that digit and
3330 without limiting the resulting exponent).
3331 """
3332 # logb(NaN) = NaN
3333 ans = self._check_nans(context=context)
3334 if ans:
3335 return ans
3336
3337 if context is None:
3338 context = getcontext()
3339
3340 # logb(+/-Inf) = +Inf
3341 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003342 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003343
3344 # logb(0) = -Inf, DivisionByZero
3345 if not self:
3346 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3347
3348 # otherwise, simply return the adjusted exponent of self, as a
3349 # Decimal. Note that no attempt is made to fit the result
3350 # into the current context.
Mark Dickinson56df8872009-10-07 19:23:50 +00003351 ans = Decimal(self.adjusted())
3352 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003353
3354 def _islogical(self):
3355 """Return True if self is a logical operand.
3356
Christian Heimes679db4a2008-01-18 09:56:22 +00003357 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003358 an exponent of 0, and a coefficient whose digits must all be
3359 either 0 or 1.
3360 """
3361 if self._sign != 0 or self._exp != 0:
3362 return False
3363 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003364 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003365 return False
3366 return True
3367
3368 def _fill_logical(self, context, opa, opb):
3369 dif = context.prec - len(opa)
3370 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003371 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003372 elif dif < 0:
3373 opa = opa[-context.prec:]
3374 dif = context.prec - len(opb)
3375 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003376 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003377 elif dif < 0:
3378 opb = opb[-context.prec:]
3379 return opa, opb
3380
3381 def logical_and(self, other, context=None):
3382 """Applies an 'and' operation between self and other's digits."""
3383 if context is None:
3384 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003385
3386 other = _convert_other(other, raiseit=True)
3387
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003388 if not self._islogical() or not other._islogical():
3389 return context._raise_error(InvalidOperation)
3390
3391 # fill to context.prec
3392 (opa, opb) = self._fill_logical(context, self._int, other._int)
3393
3394 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003395 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3396 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003397
3398 def logical_invert(self, context=None):
3399 """Invert all its digits."""
3400 if context is None:
3401 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003402 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3403 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003404
3405 def logical_or(self, other, context=None):
3406 """Applies an 'or' operation between self and other's digits."""
3407 if context is None:
3408 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003409
3410 other = _convert_other(other, raiseit=True)
3411
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003412 if not self._islogical() or not other._islogical():
3413 return context._raise_error(InvalidOperation)
3414
3415 # fill to context.prec
3416 (opa, opb) = self._fill_logical(context, self._int, other._int)
3417
3418 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003419 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003420 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003421
3422 def logical_xor(self, other, context=None):
3423 """Applies an 'xor' operation between self and other's digits."""
3424 if context is None:
3425 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003426
3427 other = _convert_other(other, raiseit=True)
3428
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003429 if not self._islogical() or not other._islogical():
3430 return context._raise_error(InvalidOperation)
3431
3432 # fill to context.prec
3433 (opa, opb) = self._fill_logical(context, self._int, other._int)
3434
3435 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003436 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003437 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003438
3439 def max_mag(self, other, context=None):
3440 """Compares the values numerically with their sign ignored."""
3441 other = _convert_other(other, raiseit=True)
3442
3443 if context is None:
3444 context = getcontext()
3445
3446 if self._is_special or other._is_special:
3447 # If one operand is a quiet NaN and the other is number, then the
3448 # number is always returned
3449 sn = self._isnan()
3450 on = other._isnan()
3451 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003452 if on == 1 and sn == 0:
3453 return self._fix(context)
3454 if sn == 1 and on == 0:
3455 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003456 return self._check_nans(other, context)
3457
Christian Heimes77c02eb2008-02-09 02:18:51 +00003458 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003459 if c == 0:
3460 c = self.compare_total(other)
3461
3462 if c == -1:
3463 ans = other
3464 else:
3465 ans = self
3466
Christian Heimes2c181612007-12-17 20:04:13 +00003467 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003468
3469 def min_mag(self, other, context=None):
3470 """Compares the values numerically with their sign ignored."""
3471 other = _convert_other(other, raiseit=True)
3472
3473 if context is None:
3474 context = getcontext()
3475
3476 if self._is_special or other._is_special:
3477 # If one operand is a quiet NaN and the other is number, then the
3478 # number is always returned
3479 sn = self._isnan()
3480 on = other._isnan()
3481 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003482 if on == 1 and sn == 0:
3483 return self._fix(context)
3484 if sn == 1 and on == 0:
3485 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003486 return self._check_nans(other, context)
3487
Christian Heimes77c02eb2008-02-09 02:18:51 +00003488 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003489 if c == 0:
3490 c = self.compare_total(other)
3491
3492 if c == -1:
3493 ans = self
3494 else:
3495 ans = other
3496
Christian Heimes2c181612007-12-17 20:04:13 +00003497 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003498
3499 def next_minus(self, context=None):
3500 """Returns the largest representable number smaller than itself."""
3501 if context is None:
3502 context = getcontext()
3503
3504 ans = self._check_nans(context=context)
3505 if ans:
3506 return ans
3507
3508 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003509 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003510 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003511 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003512
3513 context = context.copy()
3514 context._set_rounding(ROUND_FLOOR)
3515 context._ignore_all_flags()
3516 new_self = self._fix(context)
3517 if new_self != self:
3518 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003519 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3520 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003521
3522 def next_plus(self, context=None):
3523 """Returns the smallest representable number larger than itself."""
3524 if context is None:
3525 context = getcontext()
3526
3527 ans = self._check_nans(context=context)
3528 if ans:
3529 return ans
3530
3531 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003532 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003533 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003534 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003535
3536 context = context.copy()
3537 context._set_rounding(ROUND_CEILING)
3538 context._ignore_all_flags()
3539 new_self = self._fix(context)
3540 if new_self != self:
3541 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003542 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3543 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003544
3545 def next_toward(self, other, context=None):
3546 """Returns the number closest to self, in the direction towards other.
3547
3548 The result is the closest representable number to self
3549 (excluding self) that is in the direction towards other,
3550 unless both have the same value. If the two operands are
3551 numerically equal, then the result is a copy of self with the
3552 sign set to be the same as the sign of other.
3553 """
3554 other = _convert_other(other, raiseit=True)
3555
3556 if context is None:
3557 context = getcontext()
3558
3559 ans = self._check_nans(other, context)
3560 if ans:
3561 return ans
3562
Christian Heimes77c02eb2008-02-09 02:18:51 +00003563 comparison = self._cmp(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003564 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003565 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003566
3567 if comparison == -1:
3568 ans = self.next_plus(context)
3569 else: # comparison == 1
3570 ans = self.next_minus(context)
3571
3572 # decide which flags to raise using value of ans
3573 if ans._isinfinity():
3574 context._raise_error(Overflow,
3575 'Infinite result from next_toward',
3576 ans._sign)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003577 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00003578 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003579 elif ans.adjusted() < context.Emin:
3580 context._raise_error(Underflow)
3581 context._raise_error(Subnormal)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003582 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00003583 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003584 # if precision == 1 then we don't raise Clamped for a
3585 # result 0E-Etiny.
3586 if not ans:
3587 context._raise_error(Clamped)
3588
3589 return ans
3590
3591 def number_class(self, context=None):
3592 """Returns an indication of the class of self.
3593
3594 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003595 sNaN
3596 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003597 -Infinity
3598 -Normal
3599 -Subnormal
3600 -Zero
3601 +Zero
3602 +Subnormal
3603 +Normal
3604 +Infinity
3605 """
3606 if self.is_snan():
3607 return "sNaN"
3608 if self.is_qnan():
3609 return "NaN"
3610 inf = self._isinfinity()
3611 if inf == 1:
3612 return "+Infinity"
3613 if inf == -1:
3614 return "-Infinity"
3615 if self.is_zero():
3616 if self._sign:
3617 return "-Zero"
3618 else:
3619 return "+Zero"
3620 if context is None:
3621 context = getcontext()
3622 if self.is_subnormal(context=context):
3623 if self._sign:
3624 return "-Subnormal"
3625 else:
3626 return "+Subnormal"
3627 # just a normal, regular, boring number, :)
3628 if self._sign:
3629 return "-Normal"
3630 else:
3631 return "+Normal"
3632
3633 def radix(self):
3634 """Just returns 10, as this is Decimal, :)"""
3635 return Decimal(10)
3636
3637 def rotate(self, other, context=None):
3638 """Returns a rotated copy of self, value-of-other times."""
3639 if context is None:
3640 context = getcontext()
3641
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003642 other = _convert_other(other, raiseit=True)
3643
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003644 ans = self._check_nans(other, context)
3645 if ans:
3646 return ans
3647
3648 if other._exp != 0:
3649 return context._raise_error(InvalidOperation)
3650 if not (-context.prec <= int(other) <= context.prec):
3651 return context._raise_error(InvalidOperation)
3652
3653 if self._isinfinity():
3654 return Decimal(self)
3655
3656 # get values, pad if necessary
3657 torot = int(other)
3658 rotdig = self._int
3659 topad = context.prec - len(rotdig)
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003660 if topad > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003661 rotdig = '0'*topad + rotdig
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003662 elif topad < 0:
3663 rotdig = rotdig[-topad:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003664
3665 # let's rotate!
3666 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003667 return _dec_from_triple(self._sign,
3668 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003669
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003670 def scaleb(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003671 """Returns self operand after adding the second value to its exp."""
3672 if context is None:
3673 context = getcontext()
3674
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003675 other = _convert_other(other, raiseit=True)
3676
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003677 ans = self._check_nans(other, context)
3678 if ans:
3679 return ans
3680
3681 if other._exp != 0:
3682 return context._raise_error(InvalidOperation)
3683 liminf = -2 * (context.Emax + context.prec)
3684 limsup = 2 * (context.Emax + context.prec)
3685 if not (liminf <= int(other) <= limsup):
3686 return context._raise_error(InvalidOperation)
3687
3688 if self._isinfinity():
3689 return Decimal(self)
3690
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003691 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003692 d = d._fix(context)
3693 return d
3694
3695 def shift(self, other, context=None):
3696 """Returns a shifted copy of self, value-of-other times."""
3697 if context is None:
3698 context = getcontext()
3699
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003700 other = _convert_other(other, raiseit=True)
3701
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003702 ans = self._check_nans(other, context)
3703 if ans:
3704 return ans
3705
3706 if other._exp != 0:
3707 return context._raise_error(InvalidOperation)
3708 if not (-context.prec <= int(other) <= context.prec):
3709 return context._raise_error(InvalidOperation)
3710
3711 if self._isinfinity():
3712 return Decimal(self)
3713
3714 # get values, pad if necessary
3715 torot = int(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003716 rotdig = self._int
3717 topad = context.prec - len(rotdig)
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003718 if topad > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003719 rotdig = '0'*topad + rotdig
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003720 elif topad < 0:
3721 rotdig = rotdig[-topad:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003722
3723 # let's shift!
3724 if torot < 0:
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003725 shifted = rotdig[:torot]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003726 else:
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003727 shifted = rotdig + '0'*torot
3728 shifted = shifted[-context.prec:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003729
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003730 return _dec_from_triple(self._sign,
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003731 shifted.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003732
Guido van Rossumd8faa362007-04-27 19:54:29 +00003733 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003734 def __reduce__(self):
3735 return (self.__class__, (str(self),))
3736
3737 def __copy__(self):
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00003738 if type(self) is Decimal:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003739 return self # I'm immutable; therefore I am my own clone
3740 return self.__class__(str(self))
3741
3742 def __deepcopy__(self, memo):
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00003743 if type(self) is Decimal:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003744 return self # My components are also immutable
3745 return self.__class__(str(self))
3746
Mark Dickinson79f52032009-03-17 23:12:51 +00003747 # PEP 3101 support. the _localeconv keyword argument should be
3748 # considered private: it's provided for ease of testing only.
3749 def __format__(self, specifier, context=None, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00003750 """Format a Decimal instance according to the given specifier.
3751
3752 The specifier should be a standard format specifier, with the
3753 form described in PEP 3101. Formatting types 'e', 'E', 'f',
Mark Dickinson79f52032009-03-17 23:12:51 +00003754 'F', 'g', 'G', 'n' and '%' are supported. If the formatting
3755 type is omitted it defaults to 'g' or 'G', depending on the
3756 value of context.capitals.
Christian Heimesf16baeb2008-02-29 14:57:44 +00003757 """
3758
3759 # Note: PEP 3101 says that if the type is not present then
3760 # there should be at least one digit after the decimal point.
3761 # We take the liberty of ignoring this requirement for
3762 # Decimal---it's presumably there to make sure that
3763 # format(float, '') behaves similarly to str(float).
3764 if context is None:
3765 context = getcontext()
3766
Mark Dickinson79f52032009-03-17 23:12:51 +00003767 spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003768
Mark Dickinson79f52032009-03-17 23:12:51 +00003769 # special values don't care about the type or precision
Christian Heimesf16baeb2008-02-29 14:57:44 +00003770 if self._is_special:
Mark Dickinson79f52032009-03-17 23:12:51 +00003771 sign = _format_sign(self._sign, spec)
3772 body = str(self.copy_abs())
3773 return _format_align(sign, body, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003774
3775 # a type of None defaults to 'g' or 'G', depending on context
Christian Heimesf16baeb2008-02-29 14:57:44 +00003776 if spec['type'] is None:
3777 spec['type'] = ['g', 'G'][context.capitals]
Mark Dickinson79f52032009-03-17 23:12:51 +00003778
3779 # if type is '%', adjust exponent of self accordingly
3780 if spec['type'] == '%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003781 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3782
3783 # round if necessary, taking rounding mode from the context
3784 rounding = context.rounding
3785 precision = spec['precision']
3786 if precision is not None:
3787 if spec['type'] in 'eE':
3788 self = self._round(precision+1, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003789 elif spec['type'] in 'fF%':
3790 self = self._rescale(-precision, rounding)
Mark Dickinson79f52032009-03-17 23:12:51 +00003791 elif spec['type'] in 'gG' and len(self._int) > precision:
3792 self = self._round(precision, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003793 # special case: zeros with a positive exponent can't be
3794 # represented in fixed point; rescale them to 0e0.
Mark Dickinson79f52032009-03-17 23:12:51 +00003795 if not self and self._exp > 0 and spec['type'] in 'fF%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003796 self = self._rescale(0, rounding)
3797
3798 # figure out placement of the decimal point
3799 leftdigits = self._exp + len(self._int)
Mark Dickinson79f52032009-03-17 23:12:51 +00003800 if spec['type'] in 'eE':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003801 if not self and precision is not None:
3802 dotplace = 1 - precision
3803 else:
3804 dotplace = 1
Mark Dickinson79f52032009-03-17 23:12:51 +00003805 elif spec['type'] in 'fF%':
3806 dotplace = leftdigits
Christian Heimesf16baeb2008-02-29 14:57:44 +00003807 elif spec['type'] in 'gG':
3808 if self._exp <= 0 and leftdigits > -6:
3809 dotplace = leftdigits
3810 else:
3811 dotplace = 1
3812
Mark Dickinson79f52032009-03-17 23:12:51 +00003813 # find digits before and after decimal point, and get exponent
3814 if dotplace < 0:
3815 intpart = '0'
3816 fracpart = '0'*(-dotplace) + self._int
3817 elif dotplace > len(self._int):
3818 intpart = self._int + '0'*(dotplace-len(self._int))
3819 fracpart = ''
Christian Heimesf16baeb2008-02-29 14:57:44 +00003820 else:
Mark Dickinson79f52032009-03-17 23:12:51 +00003821 intpart = self._int[:dotplace] or '0'
3822 fracpart = self._int[dotplace:]
3823 exp = leftdigits-dotplace
Christian Heimesf16baeb2008-02-29 14:57:44 +00003824
Mark Dickinson79f52032009-03-17 23:12:51 +00003825 # done with the decimal-specific stuff; hand over the rest
3826 # of the formatting to the _format_number function
3827 return _format_number(self._sign, intpart, fracpart, exp, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003828
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003829def _dec_from_triple(sign, coefficient, exponent, special=False):
3830 """Create a decimal instance directly, without any validation,
3831 normalization (e.g. removal of leading zeros) or argument
3832 conversion.
3833
3834 This function is for *internal use only*.
3835 """
3836
3837 self = object.__new__(Decimal)
3838 self._sign = sign
3839 self._int = coefficient
3840 self._exp = exponent
3841 self._is_special = special
3842
3843 return self
3844
Raymond Hettinger82417ca2009-02-03 03:54:28 +00003845# Register Decimal as a kind of Number (an abstract base class).
3846# However, do not register it as Real (because Decimals are not
3847# interoperable with floats).
3848_numbers.Number.register(Decimal)
3849
3850
Guido van Rossumd8faa362007-04-27 19:54:29 +00003851##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003852
Thomas Wouters89f507f2006-12-13 04:49:30 +00003853class _ContextManager(object):
3854 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003855
Thomas Wouters89f507f2006-12-13 04:49:30 +00003856 Sets a copy of the supplied context in __enter__() and restores
3857 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003858 """
3859 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003860 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003861 def __enter__(self):
3862 self.saved_context = getcontext()
3863 setcontext(self.new_context)
3864 return self.new_context
3865 def __exit__(self, t, v, tb):
3866 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003867
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003868class Context(object):
3869 """Contains the context for a Decimal instance.
3870
3871 Contains:
3872 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003873 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003874 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003875 raised when it is caused. Otherwise, a value is
3876 substituted in.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003877 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003878 (Whether or not the trap_enabler is set)
3879 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003880 Emin - Minimum exponent
3881 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003882 capitals - If 1, 1*10^1 is printed as 1E+1.
3883 If 0, printed as 1e1
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00003884 clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003885 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003886
Stefan Krah1919b7e2012-03-21 18:25:23 +01003887 def __init__(self, prec=None, rounding=None, Emin=None, Emax=None,
3888 capitals=None, clamp=None, flags=None, traps=None,
3889 _ignored_flags=None):
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003890 # Set defaults; for everything except flags and _ignored_flags,
3891 # inherit from DefaultContext.
3892 try:
3893 dc = DefaultContext
3894 except NameError:
3895 pass
3896
3897 self.prec = prec if prec is not None else dc.prec
3898 self.rounding = rounding if rounding is not None else dc.rounding
3899 self.Emin = Emin if Emin is not None else dc.Emin
3900 self.Emax = Emax if Emax is not None else dc.Emax
3901 self.capitals = capitals if capitals is not None else dc.capitals
3902 self.clamp = clamp if clamp is not None else dc.clamp
3903
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003904 if _ignored_flags is None:
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003905 self._ignored_flags = []
3906 else:
3907 self._ignored_flags = _ignored_flags
3908
3909 if traps is None:
3910 self.traps = dc.traps.copy()
3911 elif not isinstance(traps, dict):
Stefan Krah1919b7e2012-03-21 18:25:23 +01003912 self.traps = dict((s, int(s in traps)) for s in _signals + traps)
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003913 else:
3914 self.traps = traps
3915
3916 if flags is None:
3917 self.flags = dict.fromkeys(_signals, 0)
3918 elif not isinstance(flags, dict):
Stefan Krah1919b7e2012-03-21 18:25:23 +01003919 self.flags = dict((s, int(s in flags)) for s in _signals + flags)
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003920 else:
3921 self.flags = flags
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003922
Stefan Krah1919b7e2012-03-21 18:25:23 +01003923 def _set_integer_check(self, name, value, vmin, vmax):
3924 if not isinstance(value, int):
3925 raise TypeError("%s must be an integer" % name)
3926 if vmin == '-inf':
3927 if value > vmax:
3928 raise ValueError("%s must be in [%s, %d]. got: %s" % (name, vmin, vmax, value))
3929 elif vmax == 'inf':
3930 if value < vmin:
3931 raise ValueError("%s must be in [%d, %s]. got: %s" % (name, vmin, vmax, value))
3932 else:
3933 if value < vmin or value > vmax:
3934 raise ValueError("%s must be in [%d, %d]. got %s" % (name, vmin, vmax, value))
3935 return object.__setattr__(self, name, value)
3936
3937 def _set_signal_dict(self, name, d):
3938 if not isinstance(d, dict):
3939 raise TypeError("%s must be a signal dict" % d)
3940 for key in d:
3941 if not key in _signals:
3942 raise KeyError("%s is not a valid signal dict" % d)
3943 for key in _signals:
3944 if not key in d:
3945 raise KeyError("%s is not a valid signal dict" % d)
3946 return object.__setattr__(self, name, d)
3947
3948 def __setattr__(self, name, value):
3949 if name == 'prec':
3950 return self._set_integer_check(name, value, 1, 'inf')
3951 elif name == 'Emin':
3952 return self._set_integer_check(name, value, '-inf', 0)
3953 elif name == 'Emax':
3954 return self._set_integer_check(name, value, 0, 'inf')
3955 elif name == 'capitals':
3956 return self._set_integer_check(name, value, 0, 1)
3957 elif name == 'clamp':
3958 return self._set_integer_check(name, value, 0, 1)
3959 elif name == 'rounding':
3960 if not value in _rounding_modes:
3961 # raise TypeError even for strings to have consistency
3962 # among various implementations.
3963 raise TypeError("%s: invalid rounding mode" % value)
3964 return object.__setattr__(self, name, value)
3965 elif name == 'flags' or name == 'traps':
3966 return self._set_signal_dict(name, value)
3967 elif name == '_ignored_flags':
3968 return object.__setattr__(self, name, value)
3969 else:
3970 raise AttributeError(
3971 "'decimal.Context' object has no attribute '%s'" % name)
3972
3973 def __delattr__(self, name):
3974 raise AttributeError("%s cannot be deleted" % name)
3975
3976 # Support for pickling, copy, and deepcopy
3977 def __reduce__(self):
3978 flags = [sig for sig, v in self.flags.items() if v]
3979 traps = [sig for sig, v in self.traps.items() if v]
3980 return (self.__class__,
3981 (self.prec, self.rounding, self.Emin, self.Emax,
3982 self.capitals, self.clamp, flags, traps))
3983
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003984 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003985 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003986 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003987 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00003988 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d, '
3989 'clamp=%(clamp)d'
Guido van Rossumd8faa362007-04-27 19:54:29 +00003990 % vars(self))
3991 names = [f.__name__ for f, v in self.flags.items() if v]
3992 s.append('flags=[' + ', '.join(names) + ']')
3993 names = [t.__name__ for t, v in self.traps.items() if v]
3994 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003995 return ', '.join(s) + ')'
3996
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003997 def clear_flags(self):
3998 """Reset all flags to zero"""
3999 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00004000 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00004001
Stefan Krah1919b7e2012-03-21 18:25:23 +01004002 def clear_traps(self):
4003 """Reset all traps to zero"""
4004 for flag in self.traps:
4005 self.traps[flag] = 0
4006
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004007 def _shallow_copy(self):
4008 """Returns a shallow copy from self."""
Stefan Krah1919b7e2012-03-21 18:25:23 +01004009 nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
4010 self.capitals, self.clamp, self.flags, self.traps,
4011 self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004012 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004013
4014 def copy(self):
4015 """Returns a deep copy from self."""
Stefan Krah1919b7e2012-03-21 18:25:23 +01004016 nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
4017 self.capitals, self.clamp,
4018 self.flags.copy(), self.traps.copy(),
4019 self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004020 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004021 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004022
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004023 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004024 """Handles an error
4025
4026 If the flag is in _ignored_flags, returns the default response.
Raymond Hettinger86173da2008-02-01 20:38:12 +00004027 Otherwise, it sets the flag, then, if the corresponding
Stefan Krah2eb4a072010-05-19 15:52:31 +00004028 trap_enabler is set, it reraises the exception. Otherwise, it returns
Raymond Hettinger86173da2008-02-01 20:38:12 +00004029 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004030 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004031 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004032 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00004033 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004034 return error().handle(self, *args)
4035
Raymond Hettinger86173da2008-02-01 20:38:12 +00004036 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00004037 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00004038 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004039 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004040
4041 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00004042 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00004043 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004044
4045 def _ignore_all_flags(self):
4046 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00004047 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004048
4049 def _ignore_flags(self, *flags):
4050 """Ignore the flags, if they are raised"""
4051 # Do not mutate-- This way, copies of a context leave the original
4052 # alone.
4053 self._ignored_flags = (self._ignored_flags + list(flags))
4054 return list(flags)
4055
4056 def _regard_flags(self, *flags):
4057 """Stop ignoring the flags, if they are raised"""
4058 if flags and isinstance(flags[0], (tuple,list)):
4059 flags = flags[0]
4060 for flag in flags:
4061 self._ignored_flags.remove(flag)
4062
Nick Coghland1abd252008-07-15 15:46:38 +00004063 # We inherit object.__hash__, so we must deny this explicitly
4064 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004065
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004066 def Etiny(self):
4067 """Returns Etiny (= Emin - prec + 1)"""
4068 return int(self.Emin - self.prec + 1)
4069
4070 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004071 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004072 return int(self.Emax - self.prec + 1)
4073
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004074 def _set_rounding(self, type):
4075 """Sets the rounding type.
4076
4077 Sets the rounding type, and returns the current (previous)
4078 rounding type. Often used like:
4079
4080 context = context.copy()
4081 # so you don't change the calling context
4082 # if an error occurs in the middle.
4083 rounding = context._set_rounding(ROUND_UP)
4084 val = self.__sub__(other, context=context)
4085 context._set_rounding(rounding)
4086
4087 This will make it round up for that operation.
4088 """
4089 rounding = self.rounding
4090 self.rounding= type
4091 return rounding
4092
Raymond Hettingerfed52962004-07-14 15:41:57 +00004093 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00004094 """Creates a new Decimal instance but using self as context.
4095
4096 This method implements the to-number operation of the
4097 IBM Decimal specification."""
4098
4099 if isinstance(num, str) and num != num.strip():
4100 return self._raise_error(ConversionSyntax,
4101 "no trailing or leading whitespace is "
4102 "permitted.")
4103
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004104 d = Decimal(num, context=self)
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00004105 if d._isnan() and len(d._int) > self.prec - self.clamp:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004106 return self._raise_error(ConversionSyntax,
4107 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00004108 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004109
Raymond Hettinger771ed762009-01-03 19:20:32 +00004110 def create_decimal_from_float(self, f):
4111 """Creates a new Decimal instance from a float but rounding using self
4112 as the context.
4113
4114 >>> context = Context(prec=5, rounding=ROUND_DOWN)
4115 >>> context.create_decimal_from_float(3.1415926535897932)
4116 Decimal('3.1415')
4117 >>> context = Context(prec=5, traps=[Inexact])
4118 >>> context.create_decimal_from_float(3.1415926535897932)
4119 Traceback (most recent call last):
4120 ...
4121 decimal.Inexact: None
4122
4123 """
4124 d = Decimal.from_float(f) # An exact conversion
4125 return d._fix(self) # Apply the context rounding
4126
Guido van Rossumd8faa362007-04-27 19:54:29 +00004127 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004128 def abs(self, a):
4129 """Returns the absolute value of the operand.
4130
4131 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00004132 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004133 the plus operation on the operand.
4134
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004135 >>> ExtendedContext.abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004136 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004137 >>> ExtendedContext.abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004138 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004139 >>> ExtendedContext.abs(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004140 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004141 >>> ExtendedContext.abs(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004142 Decimal('101.5')
Mark Dickinson84230a12010-02-18 14:49:50 +00004143 >>> ExtendedContext.abs(-1)
4144 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004145 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004146 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004147 return a.__abs__(context=self)
4148
4149 def add(self, a, b):
4150 """Return the sum of the two operands.
4151
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004152 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004153 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004154 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004155 Decimal('1.02E+4')
Mark Dickinson84230a12010-02-18 14:49:50 +00004156 >>> ExtendedContext.add(1, Decimal(2))
4157 Decimal('3')
4158 >>> ExtendedContext.add(Decimal(8), 5)
4159 Decimal('13')
4160 >>> ExtendedContext.add(5, 5)
4161 Decimal('10')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004162 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004163 a = _convert_other(a, raiseit=True)
4164 r = a.__add__(b, context=self)
4165 if r is NotImplemented:
4166 raise TypeError("Unable to convert %s to Decimal" % b)
4167 else:
4168 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004169
4170 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00004171 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004172
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004173 def canonical(self, a):
4174 """Returns the same Decimal object.
4175
4176 As we do not have different encodings for the same number, the
4177 received object already is in its canonical form.
4178
4179 >>> ExtendedContext.canonical(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004180 Decimal('2.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004181 """
Stefan Krah1919b7e2012-03-21 18:25:23 +01004182 if not isinstance(a, Decimal):
4183 raise TypeError("canonical requires a Decimal as an argument.")
Stefan Krah040e3112012-12-15 22:33:33 +01004184 return a.canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004185
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004186 def compare(self, a, b):
4187 """Compares values numerically.
4188
4189 If the signs of the operands differ, a value representing each operand
4190 ('-1' if the operand is less than zero, '0' if the operand is zero or
4191 negative zero, or '1' if the operand is greater than zero) is used in
4192 place of that operand for the comparison instead of the actual
4193 operand.
4194
4195 The comparison is then effected by subtracting the second operand from
4196 the first and then returning a value according to the result of the
4197 subtraction: '-1' if the result is less than zero, '0' if the result is
4198 zero or negative zero, or '1' if the result is greater than zero.
4199
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004200 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004201 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004202 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004203 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004204 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004205 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004206 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004207 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004208 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004209 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004210 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004211 Decimal('-1')
Mark Dickinson84230a12010-02-18 14:49:50 +00004212 >>> ExtendedContext.compare(1, 2)
4213 Decimal('-1')
4214 >>> ExtendedContext.compare(Decimal(1), 2)
4215 Decimal('-1')
4216 >>> ExtendedContext.compare(1, Decimal(2))
4217 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004218 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004219 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004220 return a.compare(b, context=self)
4221
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004222 def compare_signal(self, a, b):
4223 """Compares the values of the two operands numerically.
4224
4225 It's pretty much like compare(), but all NaNs signal, with signaling
4226 NaNs taking precedence over quiet NaNs.
4227
4228 >>> c = ExtendedContext
4229 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004230 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004231 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004232 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004233 >>> c.flags[InvalidOperation] = 0
4234 >>> print(c.flags[InvalidOperation])
4235 0
4236 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004237 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004238 >>> print(c.flags[InvalidOperation])
4239 1
4240 >>> c.flags[InvalidOperation] = 0
4241 >>> print(c.flags[InvalidOperation])
4242 0
4243 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004244 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004245 >>> print(c.flags[InvalidOperation])
4246 1
Mark Dickinson84230a12010-02-18 14:49:50 +00004247 >>> c.compare_signal(-1, 2)
4248 Decimal('-1')
4249 >>> c.compare_signal(Decimal(-1), 2)
4250 Decimal('-1')
4251 >>> c.compare_signal(-1, Decimal(2))
4252 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004253 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004254 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004255 return a.compare_signal(b, context=self)
4256
4257 def compare_total(self, a, b):
4258 """Compares two operands using their abstract representation.
4259
4260 This is not like the standard compare, which use their numerical
4261 value. Note that a total ordering is defined for all possible abstract
4262 representations.
4263
4264 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004265 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004266 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004267 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004268 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
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.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004271 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004272 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004273 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004274 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004275 Decimal('-1')
Mark Dickinson84230a12010-02-18 14:49:50 +00004276 >>> ExtendedContext.compare_total(1, 2)
4277 Decimal('-1')
4278 >>> ExtendedContext.compare_total(Decimal(1), 2)
4279 Decimal('-1')
4280 >>> ExtendedContext.compare_total(1, Decimal(2))
4281 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004282 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004283 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004284 return a.compare_total(b)
4285
4286 def compare_total_mag(self, a, b):
4287 """Compares two operands using their abstract representation ignoring sign.
4288
4289 Like compare_total, but with operand's sign ignored and assumed to be 0.
4290 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004291 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004292 return a.compare_total_mag(b)
4293
4294 def copy_abs(self, a):
4295 """Returns a copy of the operand with the sign set to 0.
4296
4297 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004298 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004299 >>> ExtendedContext.copy_abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004300 Decimal('100')
Mark Dickinson84230a12010-02-18 14:49:50 +00004301 >>> ExtendedContext.copy_abs(-1)
4302 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004303 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004304 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004305 return a.copy_abs()
4306
4307 def copy_decimal(self, a):
Mark Dickinson84230a12010-02-18 14:49:50 +00004308 """Returns a copy of the decimal object.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004309
4310 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004311 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004312 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004313 Decimal('-1.00')
Mark Dickinson84230a12010-02-18 14:49:50 +00004314 >>> ExtendedContext.copy_decimal(1)
4315 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004316 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004317 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004318 return Decimal(a)
4319
4320 def copy_negate(self, a):
4321 """Returns a copy of the operand with the sign inverted.
4322
4323 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004324 Decimal('-101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004325 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004326 Decimal('101.5')
Mark Dickinson84230a12010-02-18 14:49:50 +00004327 >>> ExtendedContext.copy_negate(1)
4328 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004329 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004330 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004331 return a.copy_negate()
4332
4333 def copy_sign(self, a, b):
4334 """Copies the second operand's sign to the first one.
4335
4336 In detail, it returns a copy of the first operand with the sign
4337 equal to the sign of the second operand.
4338
4339 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004340 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004341 >>> 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')
Mark Dickinson84230a12010-02-18 14:49:50 +00004347 >>> ExtendedContext.copy_sign(1, -2)
4348 Decimal('-1')
4349 >>> ExtendedContext.copy_sign(Decimal(1), -2)
4350 Decimal('-1')
4351 >>> ExtendedContext.copy_sign(1, Decimal(-2))
4352 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004353 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004354 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004355 return a.copy_sign(b)
4356
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004357 def divide(self, a, b):
4358 """Decimal division in a specified context.
4359
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004360 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004361 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004362 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004363 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004364 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004365 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004366 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004367 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004368 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004369 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004370 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004371 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004372 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004373 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004374 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004375 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004376 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004377 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004378 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004379 Decimal('1.20E+6')
Mark Dickinson84230a12010-02-18 14:49:50 +00004380 >>> ExtendedContext.divide(5, 5)
4381 Decimal('1')
4382 >>> ExtendedContext.divide(Decimal(5), 5)
4383 Decimal('1')
4384 >>> ExtendedContext.divide(5, Decimal(5))
4385 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004386 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004387 a = _convert_other(a, raiseit=True)
4388 r = a.__truediv__(b, context=self)
4389 if r is NotImplemented:
4390 raise TypeError("Unable to convert %s to Decimal" % b)
4391 else:
4392 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004393
4394 def divide_int(self, a, b):
4395 """Divides two numbers and returns the integer part of the result.
4396
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004397 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004398 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004399 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004400 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004401 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004402 Decimal('3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004403 >>> ExtendedContext.divide_int(10, 3)
4404 Decimal('3')
4405 >>> ExtendedContext.divide_int(Decimal(10), 3)
4406 Decimal('3')
4407 >>> ExtendedContext.divide_int(10, Decimal(3))
4408 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004409 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004410 a = _convert_other(a, raiseit=True)
4411 r = a.__floordiv__(b, context=self)
4412 if r is NotImplemented:
4413 raise TypeError("Unable to convert %s to Decimal" % b)
4414 else:
4415 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004416
4417 def divmod(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004418 """Return (a // b, a % b).
Mark Dickinsonc53796e2010-01-06 16:22:15 +00004419
4420 >>> ExtendedContext.divmod(Decimal(8), Decimal(3))
4421 (Decimal('2'), Decimal('2'))
4422 >>> ExtendedContext.divmod(Decimal(8), Decimal(4))
4423 (Decimal('2'), Decimal('0'))
Mark Dickinson84230a12010-02-18 14:49:50 +00004424 >>> ExtendedContext.divmod(8, 4)
4425 (Decimal('2'), Decimal('0'))
4426 >>> ExtendedContext.divmod(Decimal(8), 4)
4427 (Decimal('2'), Decimal('0'))
4428 >>> ExtendedContext.divmod(8, Decimal(4))
4429 (Decimal('2'), Decimal('0'))
Mark Dickinsonc53796e2010-01-06 16:22:15 +00004430 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004431 a = _convert_other(a, raiseit=True)
4432 r = a.__divmod__(b, context=self)
4433 if r is NotImplemented:
4434 raise TypeError("Unable to convert %s to Decimal" % b)
4435 else:
4436 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004437
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004438 def exp(self, a):
4439 """Returns e ** a.
4440
4441 >>> c = ExtendedContext.copy()
4442 >>> c.Emin = -999
4443 >>> c.Emax = 999
4444 >>> c.exp(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004445 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004446 >>> c.exp(Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004447 Decimal('0.367879441')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004448 >>> c.exp(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004449 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004450 >>> c.exp(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004451 Decimal('2.71828183')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004452 >>> c.exp(Decimal('0.693147181'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004453 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004454 >>> c.exp(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004455 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004456 >>> c.exp(10)
4457 Decimal('22026.4658')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004458 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004459 a =_convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004460 return a.exp(context=self)
4461
4462 def fma(self, a, b, c):
4463 """Returns a multiplied by b, plus c.
4464
4465 The first two operands are multiplied together, using multiply,
4466 the third operand is then added to the result of that
4467 multiplication, using add, all with only one final rounding.
4468
4469 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004470 Decimal('22')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004471 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004472 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004473 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004474 Decimal('1.38435736E+12')
Mark Dickinson84230a12010-02-18 14:49:50 +00004475 >>> ExtendedContext.fma(1, 3, 4)
4476 Decimal('7')
4477 >>> ExtendedContext.fma(1, Decimal(3), 4)
4478 Decimal('7')
4479 >>> ExtendedContext.fma(1, 3, Decimal(4))
4480 Decimal('7')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004481 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004482 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004483 return a.fma(b, c, context=self)
4484
4485 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004486 """Return True if the operand is canonical; otherwise return False.
4487
4488 Currently, the encoding of a Decimal instance is always
4489 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004490
4491 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004492 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004493 """
Stefan Krah1919b7e2012-03-21 18:25:23 +01004494 if not isinstance(a, Decimal):
4495 raise TypeError("is_canonical requires a Decimal as an argument.")
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004496 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004497
4498 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004499 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004500
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004501 A Decimal instance is considered finite if it is neither
4502 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004503
4504 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004505 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004506 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004507 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004508 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004509 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004510 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004511 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004512 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004513 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004514 >>> ExtendedContext.is_finite(1)
4515 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004516 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004517 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004518 return a.is_finite()
4519
4520 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004521 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004522
4523 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004524 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004525 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004526 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004527 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004528 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004529 >>> ExtendedContext.is_infinite(1)
4530 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004531 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004532 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004533 return a.is_infinite()
4534
4535 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004536 """Return True if the operand is a qNaN or sNaN;
4537 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004538
4539 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004540 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004541 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004542 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004543 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004544 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004545 >>> ExtendedContext.is_nan(1)
4546 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004547 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004548 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004549 return a.is_nan()
4550
4551 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004552 """Return True if the operand is a normal number;
4553 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004554
4555 >>> c = ExtendedContext.copy()
4556 >>> c.Emin = -999
4557 >>> c.Emax = 999
4558 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004559 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004560 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004561 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004562 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004563 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004564 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004565 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004566 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004567 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004568 >>> c.is_normal(1)
4569 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004570 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004571 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004572 return a.is_normal(context=self)
4573
4574 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004575 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004576
4577 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004578 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004579 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004580 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004581 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004582 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004583 >>> ExtendedContext.is_qnan(1)
4584 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004585 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004586 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004587 return a.is_qnan()
4588
4589 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004590 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004591
4592 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004593 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004594 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004595 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004596 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004597 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004598 >>> ExtendedContext.is_signed(8)
4599 False
4600 >>> ExtendedContext.is_signed(-8)
4601 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004602 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004603 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004604 return a.is_signed()
4605
4606 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004607 """Return True if the operand is a signaling NaN;
4608 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004609
4610 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004611 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004612 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004613 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004614 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004615 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004616 >>> ExtendedContext.is_snan(1)
4617 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004618 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004619 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004620 return a.is_snan()
4621
4622 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004623 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004624
4625 >>> c = ExtendedContext.copy()
4626 >>> c.Emin = -999
4627 >>> c.Emax = 999
4628 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004629 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004630 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004631 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004632 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004633 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004634 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004635 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004636 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004637 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004638 >>> c.is_subnormal(1)
4639 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004640 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004641 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004642 return a.is_subnormal(context=self)
4643
4644 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004645 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004646
4647 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004648 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004649 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004650 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004651 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004652 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004653 >>> ExtendedContext.is_zero(1)
4654 False
4655 >>> ExtendedContext.is_zero(0)
4656 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004657 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004658 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004659 return a.is_zero()
4660
4661 def ln(self, a):
4662 """Returns the natural (base e) logarithm of the operand.
4663
4664 >>> c = ExtendedContext.copy()
4665 >>> c.Emin = -999
4666 >>> c.Emax = 999
4667 >>> c.ln(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004668 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004669 >>> c.ln(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004670 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004671 >>> c.ln(Decimal('2.71828183'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004672 Decimal('1.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004673 >>> c.ln(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004674 Decimal('2.30258509')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004675 >>> c.ln(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004676 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004677 >>> c.ln(1)
4678 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004679 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004680 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004681 return a.ln(context=self)
4682
4683 def log10(self, a):
4684 """Returns the base 10 logarithm of the operand.
4685
4686 >>> c = ExtendedContext.copy()
4687 >>> c.Emin = -999
4688 >>> c.Emax = 999
4689 >>> c.log10(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004690 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004691 >>> c.log10(Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004692 Decimal('-3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004693 >>> c.log10(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004694 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004695 >>> c.log10(Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004696 Decimal('0.301029996')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004697 >>> c.log10(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004698 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004699 >>> c.log10(Decimal('70'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004700 Decimal('1.84509804')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004701 >>> c.log10(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004702 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004703 >>> c.log10(0)
4704 Decimal('-Infinity')
4705 >>> c.log10(1)
4706 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004707 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004708 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004709 return a.log10(context=self)
4710
4711 def logb(self, a):
4712 """ Returns the exponent of the magnitude of the operand's MSD.
4713
4714 The result is the integer which is the exponent of the magnitude
4715 of the most significant digit of the operand (as though the
4716 operand were truncated to a single digit while maintaining the
4717 value of that digit and without limiting the resulting exponent).
4718
4719 >>> ExtendedContext.logb(Decimal('250'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004720 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004721 >>> ExtendedContext.logb(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004722 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004723 >>> ExtendedContext.logb(Decimal('0.03'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004724 Decimal('-2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004725 >>> ExtendedContext.logb(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004726 Decimal('-Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004727 >>> ExtendedContext.logb(1)
4728 Decimal('0')
4729 >>> ExtendedContext.logb(10)
4730 Decimal('1')
4731 >>> ExtendedContext.logb(100)
4732 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004733 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004734 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004735 return a.logb(context=self)
4736
4737 def logical_and(self, a, b):
4738 """Applies the logical operation 'and' between each operand's digits.
4739
4740 The operands must be both logical numbers.
4741
4742 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004743 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004744 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004745 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004746 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004747 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004748 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004749 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004750 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004751 Decimal('1000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004752 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004753 Decimal('10')
Mark Dickinson84230a12010-02-18 14:49:50 +00004754 >>> ExtendedContext.logical_and(110, 1101)
4755 Decimal('100')
4756 >>> ExtendedContext.logical_and(Decimal(110), 1101)
4757 Decimal('100')
4758 >>> ExtendedContext.logical_and(110, Decimal(1101))
4759 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004760 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004761 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004762 return a.logical_and(b, context=self)
4763
4764 def logical_invert(self, a):
4765 """Invert all the digits in the operand.
4766
4767 The operand must be a logical number.
4768
4769 >>> ExtendedContext.logical_invert(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004770 Decimal('111111111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004771 >>> ExtendedContext.logical_invert(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004772 Decimal('111111110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004773 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004774 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004775 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004776 Decimal('10101010')
Mark Dickinson84230a12010-02-18 14:49:50 +00004777 >>> ExtendedContext.logical_invert(1101)
4778 Decimal('111110010')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004779 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004780 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004781 return a.logical_invert(context=self)
4782
4783 def logical_or(self, a, b):
4784 """Applies the logical operation 'or' between each operand's digits.
4785
4786 The operands must be both logical numbers.
4787
4788 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004789 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004790 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004791 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004792 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004793 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004794 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004795 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004796 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004797 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004798 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004799 Decimal('1110')
Mark Dickinson84230a12010-02-18 14:49:50 +00004800 >>> ExtendedContext.logical_or(110, 1101)
4801 Decimal('1111')
4802 >>> ExtendedContext.logical_or(Decimal(110), 1101)
4803 Decimal('1111')
4804 >>> ExtendedContext.logical_or(110, Decimal(1101))
4805 Decimal('1111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004806 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004807 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004808 return a.logical_or(b, context=self)
4809
4810 def logical_xor(self, a, b):
4811 """Applies the logical operation 'xor' between each operand's digits.
4812
4813 The operands must be both logical numbers.
4814
4815 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004816 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004817 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004818 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004819 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004820 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004821 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004822 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004823 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004824 Decimal('110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004825 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004826 Decimal('1101')
Mark Dickinson84230a12010-02-18 14:49:50 +00004827 >>> ExtendedContext.logical_xor(110, 1101)
4828 Decimal('1011')
4829 >>> ExtendedContext.logical_xor(Decimal(110), 1101)
4830 Decimal('1011')
4831 >>> ExtendedContext.logical_xor(110, Decimal(1101))
4832 Decimal('1011')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004833 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004834 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004835 return a.logical_xor(b, context=self)
4836
Mark Dickinson84230a12010-02-18 14:49:50 +00004837 def max(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004838 """max compares two values numerically and returns the maximum.
4839
4840 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004841 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004842 operation. If they are numerically equal then the left-hand operand
4843 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004844 infinity) of the two operands is chosen as the result.
4845
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004846 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004847 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004848 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004849 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004850 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004851 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004852 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004853 Decimal('7')
Mark Dickinson84230a12010-02-18 14:49:50 +00004854 >>> ExtendedContext.max(1, 2)
4855 Decimal('2')
4856 >>> ExtendedContext.max(Decimal(1), 2)
4857 Decimal('2')
4858 >>> ExtendedContext.max(1, Decimal(2))
4859 Decimal('2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004860 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004861 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004862 return a.max(b, context=self)
4863
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004864 def max_mag(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004865 """Compares the values numerically with their sign ignored.
4866
4867 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
4868 Decimal('7')
4869 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
4870 Decimal('-10')
4871 >>> ExtendedContext.max_mag(1, -2)
4872 Decimal('-2')
4873 >>> ExtendedContext.max_mag(Decimal(1), -2)
4874 Decimal('-2')
4875 >>> ExtendedContext.max_mag(1, Decimal(-2))
4876 Decimal('-2')
4877 """
4878 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004879 return a.max_mag(b, context=self)
4880
Mark Dickinson84230a12010-02-18 14:49:50 +00004881 def min(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004882 """min compares two values numerically and returns the minimum.
4883
4884 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004885 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004886 operation. If they are numerically equal then the left-hand operand
4887 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004888 infinity) of the two operands is chosen as the result.
4889
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004890 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004891 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004892 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004893 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004894 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004895 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004896 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004897 Decimal('7')
Mark Dickinson84230a12010-02-18 14:49:50 +00004898 >>> ExtendedContext.min(1, 2)
4899 Decimal('1')
4900 >>> ExtendedContext.min(Decimal(1), 2)
4901 Decimal('1')
4902 >>> ExtendedContext.min(1, Decimal(29))
4903 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004904 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004905 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004906 return a.min(b, context=self)
4907
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004908 def min_mag(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004909 """Compares the values numerically with their sign ignored.
4910
4911 >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2'))
4912 Decimal('-2')
4913 >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN'))
4914 Decimal('-3')
4915 >>> ExtendedContext.min_mag(1, -2)
4916 Decimal('1')
4917 >>> ExtendedContext.min_mag(Decimal(1), -2)
4918 Decimal('1')
4919 >>> ExtendedContext.min_mag(1, Decimal(-2))
4920 Decimal('1')
4921 """
4922 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004923 return a.min_mag(b, context=self)
4924
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004925 def minus(self, a):
4926 """Minus corresponds to unary prefix minus in Python.
4927
4928 The operation is evaluated using the same rules as subtract; the
4929 operation minus(a) is calculated as subtract('0', a) where the '0'
4930 has the same exponent as the operand.
4931
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004932 >>> ExtendedContext.minus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004933 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004934 >>> ExtendedContext.minus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004935 Decimal('1.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004936 >>> ExtendedContext.minus(1)
4937 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004938 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004939 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004940 return a.__neg__(context=self)
4941
4942 def multiply(self, a, b):
4943 """multiply multiplies two operands.
4944
4945 If either operand is a special value then the general rules apply.
Mark Dickinson84230a12010-02-18 14:49:50 +00004946 Otherwise, the operands are multiplied together
4947 ('long multiplication'), resulting in a number which may be as long as
4948 the sum of the lengths of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004949
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004950 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004951 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004952 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004953 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004954 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004955 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004956 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004957 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004958 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004959 Decimal('4.28135971E+11')
Mark Dickinson84230a12010-02-18 14:49:50 +00004960 >>> ExtendedContext.multiply(7, 7)
4961 Decimal('49')
4962 >>> ExtendedContext.multiply(Decimal(7), 7)
4963 Decimal('49')
4964 >>> ExtendedContext.multiply(7, Decimal(7))
4965 Decimal('49')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004966 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004967 a = _convert_other(a, raiseit=True)
4968 r = a.__mul__(b, context=self)
4969 if r is NotImplemented:
4970 raise TypeError("Unable to convert %s to Decimal" % b)
4971 else:
4972 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004973
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004974 def next_minus(self, a):
4975 """Returns the largest representable number smaller than a.
4976
4977 >>> c = ExtendedContext.copy()
4978 >>> c.Emin = -999
4979 >>> c.Emax = 999
4980 >>> ExtendedContext.next_minus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004981 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004982 >>> c.next_minus(Decimal('1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004983 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004984 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004985 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004986 >>> c.next_minus(Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004987 Decimal('9.99999999E+999')
Mark Dickinson84230a12010-02-18 14:49:50 +00004988 >>> c.next_minus(1)
4989 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004990 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004991 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004992 return a.next_minus(context=self)
4993
4994 def next_plus(self, a):
4995 """Returns the smallest representable number larger than a.
4996
4997 >>> c = ExtendedContext.copy()
4998 >>> c.Emin = -999
4999 >>> c.Emax = 999
5000 >>> ExtendedContext.next_plus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005001 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005002 >>> c.next_plus(Decimal('-1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005003 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005004 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005005 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005006 >>> c.next_plus(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005007 Decimal('-9.99999999E+999')
Mark Dickinson84230a12010-02-18 14:49:50 +00005008 >>> c.next_plus(1)
5009 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005010 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005011 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005012 return a.next_plus(context=self)
5013
5014 def next_toward(self, a, b):
5015 """Returns the number closest to a, in direction towards b.
5016
5017 The result is the closest representable number from the first
5018 operand (but not the first operand) that is in the direction
5019 towards the second operand, unless the operands have the same
5020 value.
5021
5022 >>> c = ExtendedContext.copy()
5023 >>> c.Emin = -999
5024 >>> c.Emax = 999
5025 >>> c.next_toward(Decimal('1'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005026 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005027 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005028 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005029 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005030 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005031 >>> c.next_toward(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005032 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005033 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005034 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005035 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005036 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005037 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005038 Decimal('-0.00')
Mark Dickinson84230a12010-02-18 14:49:50 +00005039 >>> c.next_toward(0, 1)
5040 Decimal('1E-1007')
5041 >>> c.next_toward(Decimal(0), 1)
5042 Decimal('1E-1007')
5043 >>> c.next_toward(0, Decimal(1))
5044 Decimal('1E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005045 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005046 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005047 return a.next_toward(b, context=self)
5048
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005049 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00005050 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005051
5052 Essentially a plus operation with all trailing zeros removed from the
5053 result.
5054
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005055 >>> ExtendedContext.normalize(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005056 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005057 >>> ExtendedContext.normalize(Decimal('-2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005058 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005059 >>> ExtendedContext.normalize(Decimal('1.200'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005060 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005061 >>> ExtendedContext.normalize(Decimal('-120'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005062 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005063 >>> ExtendedContext.normalize(Decimal('120.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005064 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005065 >>> ExtendedContext.normalize(Decimal('0.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005066 Decimal('0')
Mark Dickinson84230a12010-02-18 14:49:50 +00005067 >>> ExtendedContext.normalize(6)
5068 Decimal('6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005069 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005070 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005071 return a.normalize(context=self)
5072
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005073 def number_class(self, a):
5074 """Returns an indication of the class of the operand.
5075
5076 The class is one of the following strings:
5077 -sNaN
5078 -NaN
5079 -Infinity
5080 -Normal
5081 -Subnormal
5082 -Zero
5083 +Zero
5084 +Subnormal
5085 +Normal
5086 +Infinity
5087
Stefan Krah1919b7e2012-03-21 18:25:23 +01005088 >>> c = ExtendedContext.copy()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005089 >>> c.Emin = -999
5090 >>> c.Emax = 999
5091 >>> c.number_class(Decimal('Infinity'))
5092 '+Infinity'
5093 >>> c.number_class(Decimal('1E-10'))
5094 '+Normal'
5095 >>> c.number_class(Decimal('2.50'))
5096 '+Normal'
5097 >>> c.number_class(Decimal('0.1E-999'))
5098 '+Subnormal'
5099 >>> c.number_class(Decimal('0'))
5100 '+Zero'
5101 >>> c.number_class(Decimal('-0'))
5102 '-Zero'
5103 >>> c.number_class(Decimal('-0.1E-999'))
5104 '-Subnormal'
5105 >>> c.number_class(Decimal('-1E-10'))
5106 '-Normal'
5107 >>> c.number_class(Decimal('-2.50'))
5108 '-Normal'
5109 >>> c.number_class(Decimal('-Infinity'))
5110 '-Infinity'
5111 >>> c.number_class(Decimal('NaN'))
5112 'NaN'
5113 >>> c.number_class(Decimal('-NaN'))
5114 'NaN'
5115 >>> c.number_class(Decimal('sNaN'))
5116 'sNaN'
Mark Dickinson84230a12010-02-18 14:49:50 +00005117 >>> c.number_class(123)
5118 '+Normal'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005119 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005120 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005121 return a.number_class(context=self)
5122
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005123 def plus(self, a):
5124 """Plus corresponds to unary prefix plus in Python.
5125
5126 The operation is evaluated using the same rules as add; the
5127 operation plus(a) is calculated as add('0', a) where the '0'
5128 has the same exponent as the operand.
5129
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005130 >>> ExtendedContext.plus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005131 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005132 >>> ExtendedContext.plus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005133 Decimal('-1.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005134 >>> ExtendedContext.plus(-1)
5135 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005136 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005137 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005138 return a.__pos__(context=self)
5139
5140 def power(self, a, b, modulo=None):
5141 """Raises a to the power of b, to modulo if given.
5142
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005143 With two arguments, compute a**b. If a is negative then b
5144 must be integral. The result will be inexact unless b is
5145 integral and the result is finite and can be expressed exactly
5146 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005147
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005148 With three arguments, compute (a**b) % modulo. For the
5149 three argument form, the following restrictions on the
5150 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005151
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005152 - all three arguments must be integral
5153 - b must be nonnegative
5154 - at least one of a or b must be nonzero
5155 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005156
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005157 The result of pow(a, b, modulo) is identical to the result
5158 that would be obtained by computing (a**b) % modulo with
5159 unbounded precision, but is computed more efficiently. It is
5160 always exact.
5161
5162 >>> c = ExtendedContext.copy()
5163 >>> c.Emin = -999
5164 >>> c.Emax = 999
5165 >>> c.power(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005166 Decimal('8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005167 >>> 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('0.125')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005171 >>> c.power(Decimal('1.7'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005172 Decimal('69.7575744')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005173 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005174 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005175 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005176 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005177 >>> c.power(Decimal('Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005178 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005179 >>> c.power(Decimal('Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005180 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005181 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005182 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005183 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005184 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005185 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005186 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005187 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005188 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005189 >>> c.power(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005190 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005191
5192 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005193 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005194 >>> 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('8'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005197 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005198 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005199 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005200 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005201 Decimal('11729830')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005202 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005203 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005204 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005205 Decimal('1')
Mark Dickinson84230a12010-02-18 14:49:50 +00005206 >>> ExtendedContext.power(7, 7)
5207 Decimal('823543')
5208 >>> ExtendedContext.power(Decimal(7), 7)
5209 Decimal('823543')
5210 >>> ExtendedContext.power(7, Decimal(7), 2)
5211 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005212 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005213 a = _convert_other(a, raiseit=True)
5214 r = a.__pow__(b, modulo, context=self)
5215 if r is NotImplemented:
5216 raise TypeError("Unable to convert %s to Decimal" % b)
5217 else:
5218 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005219
5220 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005221 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005222
5223 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00005224 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005225 exponent is being increased), multiplied by a positive power of ten (if
5226 the exponent is being decreased), or is unchanged (if the exponent is
5227 already equal to that of the right-hand operand).
5228
5229 Unlike other operations, if the length of the coefficient after the
5230 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00005231 operation condition is raised. This guarantees that, unless there is
5232 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005233 equal to that of the right-hand operand.
5234
5235 Also unlike other operations, quantize will never raise Underflow, even
5236 if the result is subnormal and inexact.
5237
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005238 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005239 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005240 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005241 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005242 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005243 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005244 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005245 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005246 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005247 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005248 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005249 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005250 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005251 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005252 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005253 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005254 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005255 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005256 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005257 Decimal('NaN')
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('217'), Decimal('1e-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005261 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005262 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005263 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005264 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005265 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005266 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005267 Decimal('2E+2')
Mark Dickinson84230a12010-02-18 14:49:50 +00005268 >>> ExtendedContext.quantize(1, 2)
5269 Decimal('1')
5270 >>> ExtendedContext.quantize(Decimal(1), 2)
5271 Decimal('1')
5272 >>> ExtendedContext.quantize(1, Decimal(2))
5273 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005274 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005275 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005276 return a.quantize(b, context=self)
5277
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005278 def radix(self):
5279 """Just returns 10, as this is Decimal, :)
5280
5281 >>> ExtendedContext.radix()
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005282 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005283 """
5284 return Decimal(10)
5285
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005286 def remainder(self, a, b):
5287 """Returns the remainder from integer division.
5288
5289 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00005290 calculating integer division as described for divide-integer, rounded
5291 to precision digits if necessary. The sign of the result, if
5292 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005293
5294 This operation will fail under the same conditions as integer division
5295 (that is, if integer division on the same two operands would fail, the
5296 remainder cannot be calculated).
5297
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005298 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005299 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005300 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005301 Decimal('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.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005305 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005306 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005307 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005308 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005309 Decimal('1.0')
Mark Dickinson84230a12010-02-18 14:49:50 +00005310 >>> ExtendedContext.remainder(22, 6)
5311 Decimal('4')
5312 >>> ExtendedContext.remainder(Decimal(22), 6)
5313 Decimal('4')
5314 >>> ExtendedContext.remainder(22, Decimal(6))
5315 Decimal('4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005316 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005317 a = _convert_other(a, raiseit=True)
5318 r = a.__mod__(b, context=self)
5319 if r is NotImplemented:
5320 raise TypeError("Unable to convert %s to Decimal" % b)
5321 else:
5322 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005323
5324 def remainder_near(self, a, b):
5325 """Returns to be "a - b * n", where n is the integer nearest the exact
5326 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00005327 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005328 sign of a.
5329
5330 This operation will fail under the same conditions as integer division
5331 (that is, if integer division on the same two operands would fail, the
5332 remainder cannot be calculated).
5333
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005334 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005335 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005336 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005337 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005338 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005339 Decimal('1')
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.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005343 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005344 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005345 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005346 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005347 Decimal('-0.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005348 >>> ExtendedContext.remainder_near(3, 11)
5349 Decimal('3')
5350 >>> ExtendedContext.remainder_near(Decimal(3), 11)
5351 Decimal('3')
5352 >>> ExtendedContext.remainder_near(3, Decimal(11))
5353 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005354 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005355 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005356 return a.remainder_near(b, context=self)
5357
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005358 def rotate(self, a, b):
5359 """Returns a rotated copy of a, b times.
5360
5361 The coefficient of the result is a rotated copy of the digits in
5362 the coefficient of the first operand. The number of places of
5363 rotation is taken from the absolute value of the second operand,
5364 with the rotation being to the left if the second operand is
5365 positive or to the right otherwise.
5366
5367 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005368 Decimal('400000003')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005369 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005370 Decimal('12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005371 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005372 Decimal('891234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005373 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005374 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005375 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005376 Decimal('345678912')
Mark Dickinson84230a12010-02-18 14:49:50 +00005377 >>> ExtendedContext.rotate(1333333, 1)
5378 Decimal('13333330')
5379 >>> ExtendedContext.rotate(Decimal(1333333), 1)
5380 Decimal('13333330')
5381 >>> ExtendedContext.rotate(1333333, Decimal(1))
5382 Decimal('13333330')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005383 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005384 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005385 return a.rotate(b, context=self)
5386
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005387 def same_quantum(self, a, b):
5388 """Returns True if the two operands have the same exponent.
5389
5390 The result is never affected by either the sign or the coefficient of
5391 either operand.
5392
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005393 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005394 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005395 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005396 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005397 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005398 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005399 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005400 True
Mark Dickinson84230a12010-02-18 14:49:50 +00005401 >>> ExtendedContext.same_quantum(10000, -1)
5402 True
5403 >>> ExtendedContext.same_quantum(Decimal(10000), -1)
5404 True
5405 >>> ExtendedContext.same_quantum(10000, Decimal(-1))
5406 True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005407 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005408 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005409 return a.same_quantum(b)
5410
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005411 def scaleb (self, a, b):
5412 """Returns the first operand after adding the second value its exp.
5413
5414 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005415 Decimal('0.0750')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005416 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005417 Decimal('7.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005418 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005419 Decimal('7.50E+3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005420 >>> ExtendedContext.scaleb(1, 4)
5421 Decimal('1E+4')
5422 >>> ExtendedContext.scaleb(Decimal(1), 4)
5423 Decimal('1E+4')
5424 >>> ExtendedContext.scaleb(1, Decimal(4))
5425 Decimal('1E+4')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005426 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005427 a = _convert_other(a, raiseit=True)
5428 return a.scaleb(b, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005429
5430 def shift(self, a, b):
5431 """Returns a shifted copy of a, b times.
5432
5433 The coefficient of the result is a shifted copy of the digits
5434 in the coefficient of the first operand. The number of places
5435 to shift is taken from the absolute value of the second operand,
5436 with the shift being to the left if the second operand is
5437 positive or to the right otherwise. Digits shifted into the
5438 coefficient are zeros.
5439
5440 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005441 Decimal('400000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005442 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005443 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005444 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005445 Decimal('1234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005446 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005447 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005448 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005449 Decimal('345678900')
Mark Dickinson84230a12010-02-18 14:49:50 +00005450 >>> ExtendedContext.shift(88888888, 2)
5451 Decimal('888888800')
5452 >>> ExtendedContext.shift(Decimal(88888888), 2)
5453 Decimal('888888800')
5454 >>> ExtendedContext.shift(88888888, Decimal(2))
5455 Decimal('888888800')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005456 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005457 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005458 return a.shift(b, context=self)
5459
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005460 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005461 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005462
5463 If the result must be inexact, it is rounded using the round-half-even
5464 algorithm.
5465
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005466 >>> ExtendedContext.sqrt(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005467 Decimal('0')
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.39'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005471 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005472 >>> ExtendedContext.sqrt(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005473 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005474 >>> ExtendedContext.sqrt(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005475 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005476 >>> ExtendedContext.sqrt(Decimal('1.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005477 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005478 >>> ExtendedContext.sqrt(Decimal('1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005479 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005480 >>> ExtendedContext.sqrt(Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005481 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005482 >>> ExtendedContext.sqrt(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005483 Decimal('3.16227766')
Mark Dickinson84230a12010-02-18 14:49:50 +00005484 >>> ExtendedContext.sqrt(2)
5485 Decimal('1.41421356')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005486 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005487 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005488 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005489 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005490 return a.sqrt(context=self)
5491
5492 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00005493 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005494
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005495 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005496 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005497 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005498 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005499 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005500 Decimal('-0.77')
Mark Dickinson84230a12010-02-18 14:49:50 +00005501 >>> ExtendedContext.subtract(8, 5)
5502 Decimal('3')
5503 >>> ExtendedContext.subtract(Decimal(8), 5)
5504 Decimal('3')
5505 >>> ExtendedContext.subtract(8, Decimal(5))
5506 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005507 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005508 a = _convert_other(a, raiseit=True)
5509 r = a.__sub__(b, context=self)
5510 if r is NotImplemented:
5511 raise TypeError("Unable to convert %s to Decimal" % b)
5512 else:
5513 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005514
5515 def to_eng_string(self, a):
5516 """Converts a number to a string, using scientific notation.
5517
5518 The operation is not affected by the context.
5519 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005520 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005521 return a.to_eng_string(context=self)
5522
5523 def to_sci_string(self, a):
5524 """Converts a number to a string, using scientific notation.
5525
5526 The operation is not affected by the context.
5527 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005528 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005529 return a.__str__(context=self)
5530
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005531 def to_integral_exact(self, a):
5532 """Rounds to an integer.
5533
5534 When the operand has a negative exponent, the result is the same
5535 as using the quantize() operation using the given operand as the
5536 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5537 of the operand as the precision setting; Inexact and Rounded flags
5538 are allowed in this operation. The rounding mode is taken from the
5539 context.
5540
5541 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005542 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005543 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005544 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005545 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005546 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005547 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005548 Decimal('102')
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('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005552 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005553 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005554 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005555 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005556 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005557 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005558 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005559 return a.to_integral_exact(context=self)
5560
5561 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005562 """Rounds to an integer.
5563
5564 When the operand has a negative exponent, the result is the same
5565 as using the quantize() operation using the given operand as the
5566 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5567 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00005568 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005569
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005570 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005571 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005572 >>> ExtendedContext.to_integral_value(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005573 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005574 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005575 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005576 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005577 Decimal('102')
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('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005581 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005582 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005583 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005584 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005585 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005586 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005587 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005588 return a.to_integral_value(context=self)
5589
5590 # the method name changed, but we provide also the old one, for compatibility
5591 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005592
5593class _WorkRep(object):
5594 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00005595 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005596 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005597 # exp: None, int, or string
5598
5599 def __init__(self, value=None):
5600 if value is None:
5601 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005602 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005603 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00005604 elif isinstance(value, Decimal):
5605 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005606 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005607 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00005608 else:
5609 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005610 self.sign = value[0]
5611 self.int = value[1]
5612 self.exp = value[2]
5613
5614 def __repr__(self):
5615 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5616
5617 __str__ = __repr__
5618
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005619
5620
Christian Heimes2c181612007-12-17 20:04:13 +00005621def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005622 """Normalizes op1, op2 to have the same exp and length of coefficient.
5623
5624 Done during addition.
5625 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005626 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005627 tmp = op2
5628 other = op1
5629 else:
5630 tmp = op1
5631 other = op2
5632
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005633 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5634 # Then adding 10**exp to tmp has the same effect (after rounding)
5635 # as adding any positive quantity smaller than 10**exp; similarly
5636 # for subtraction. So if other is smaller than 10**exp we replace
5637 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00005638 tmp_len = len(str(tmp.int))
5639 other_len = len(str(other.int))
5640 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5641 if other_len + other.exp - 1 < exp:
5642 other.int = 1
5643 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005644
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005645 tmp.int *= 10 ** (tmp.exp - other.exp)
5646 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005647 return op1, op2
5648
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005649##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005650
Raymond Hettingerdb213a22010-11-27 08:09:40 +00005651_nbits = int.bit_length
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005652
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01005653def _decimal_lshift_exact(n, e):
5654 """ Given integers n and e, return n * 10**e if it's an integer, else None.
5655
5656 The computation is designed to avoid computing large powers of 10
5657 unnecessarily.
5658
5659 >>> _decimal_lshift_exact(3, 4)
5660 30000
5661 >>> _decimal_lshift_exact(300, -999999999) # returns None
5662
5663 """
5664 if n == 0:
5665 return 0
5666 elif e >= 0:
5667 return n * 10**e
5668 else:
5669 # val_n = largest power of 10 dividing n.
5670 str_n = str(abs(n))
5671 val_n = len(str_n) - len(str_n.rstrip('0'))
5672 return None if val_n < -e else n // 10**-e
5673
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005674def _sqrt_nearest(n, a):
5675 """Closest integer to the square root of the positive integer n. a is
5676 an initial approximation to the square root. Any positive integer
5677 will do for a, but the closer a is to the square root of n the
5678 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005679
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005680 """
5681 if n <= 0 or a <= 0:
5682 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5683
5684 b=0
5685 while a != b:
5686 b, a = a, a--n//a>>1
5687 return a
5688
5689def _rshift_nearest(x, shift):
5690 """Given an integer x and a nonnegative integer shift, return closest
5691 integer to x / 2**shift; use round-to-even in case of a tie.
5692
5693 """
5694 b, q = 1 << shift, x >> shift
5695 return q + (2*(x & (b-1)) + (q&1) > b)
5696
5697def _div_nearest(a, b):
5698 """Closest integer to a/b, a and b positive integers; rounds to even
5699 in the case of a tie.
5700
5701 """
5702 q, r = divmod(a, b)
5703 return q + (2*r + (q&1) > b)
5704
5705def _ilog(x, M, L = 8):
5706 """Integer approximation to M*log(x/M), with absolute error boundable
5707 in terms only of x/M.
5708
5709 Given positive integers x and M, return an integer approximation to
5710 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5711 between the approximation and the exact result is at most 22. For
5712 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5713 both cases these are upper bounds on the error; it will usually be
5714 much smaller."""
5715
5716 # The basic algorithm is the following: let log1p be the function
5717 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5718 # the reduction
5719 #
5720 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5721 #
5722 # repeatedly until the argument to log1p is small (< 2**-L in
5723 # absolute value). For small y we can use the Taylor series
5724 # expansion
5725 #
5726 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5727 #
5728 # truncating at T such that y**T is small enough. The whole
5729 # computation is carried out in a form of fixed-point arithmetic,
5730 # with a real number z being represented by an integer
5731 # approximation to z*M. To avoid loss of precision, the y below
5732 # is actually an integer approximation to 2**R*y*M, where R is the
5733 # number of reductions performed so far.
5734
5735 y = x-M
5736 # argument reduction; R = number of reductions performed
5737 R = 0
5738 while (R <= L and abs(y) << L-R >= M or
5739 R > L and abs(y) >> R-L >= M):
5740 y = _div_nearest((M*y) << 1,
5741 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5742 R += 1
5743
5744 # Taylor series with T terms
5745 T = -int(-10*len(str(M))//(3*L))
5746 yshift = _rshift_nearest(y, R)
5747 w = _div_nearest(M, T)
5748 for k in range(T-1, 0, -1):
5749 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5750
5751 return _div_nearest(w*y, M)
5752
5753def _dlog10(c, e, p):
5754 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5755 approximation to 10**p * log10(c*10**e), with an absolute error of
5756 at most 1. Assumes that c*10**e is not exactly 1."""
5757
5758 # increase precision by 2; compensate for this by dividing
5759 # final result by 100
5760 p += 2
5761
5762 # write c*10**e as d*10**f with either:
5763 # f >= 0 and 1 <= d <= 10, or
5764 # f <= 0 and 0.1 <= d <= 1.
5765 # Thus for c*10**e close to 1, f = 0
5766 l = len(str(c))
5767 f = e+l - (e+l >= 1)
5768
5769 if p > 0:
5770 M = 10**p
5771 k = e+p-f
5772 if k >= 0:
5773 c *= 10**k
5774 else:
5775 c = _div_nearest(c, 10**-k)
5776
5777 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005778 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005779 log_d = _div_nearest(log_d*M, log_10)
5780 log_tenpower = f*M # exact
5781 else:
5782 log_d = 0 # error < 2.31
Neal Norwitz2f99b242008-08-24 05:48:10 +00005783 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005784
5785 return _div_nearest(log_tenpower+log_d, 100)
5786
5787def _dlog(c, e, p):
5788 """Given integers c, e and p with c > 0, compute an integer
5789 approximation to 10**p * log(c*10**e), with an absolute error of
5790 at most 1. Assumes that c*10**e is not exactly 1."""
5791
5792 # Increase precision by 2. The precision increase is compensated
5793 # for at the end with a division by 100.
5794 p += 2
5795
5796 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5797 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5798 # as 10**p * log(d) + 10**p*f * log(10).
5799 l = len(str(c))
5800 f = e+l - (e+l >= 1)
5801
5802 # compute approximation to 10**p*log(d), with error < 27
5803 if p > 0:
5804 k = e+p-f
5805 if k >= 0:
5806 c *= 10**k
5807 else:
5808 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5809
5810 # _ilog magnifies existing error in c by a factor of at most 10
5811 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5812 else:
5813 # p <= 0: just approximate the whole thing by 0; error < 2.31
5814 log_d = 0
5815
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005816 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005817 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005818 extra = len(str(abs(f)))-1
5819 if p + extra >= 0:
5820 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5821 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5822 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005823 else:
5824 f_log_ten = 0
5825 else:
5826 f_log_ten = 0
5827
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005828 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005829 return _div_nearest(f_log_ten + log_d, 100)
5830
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005831class _Log10Memoize(object):
5832 """Class to compute, store, and allow retrieval of, digits of the
5833 constant log(10) = 2.302585.... This constant is needed by
5834 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5835 def __init__(self):
5836 self.digits = "23025850929940456840179914546843642076011014886"
5837
5838 def getdigits(self, p):
5839 """Given an integer p >= 0, return floor(10**p)*log(10).
5840
5841 For example, self.getdigits(3) returns 2302.
5842 """
5843 # digits are stored as a string, for quick conversion to
5844 # integer in the case that we've already computed enough
5845 # digits; the stored digits should always be correct
5846 # (truncated, not rounded to nearest).
5847 if p < 0:
5848 raise ValueError("p should be nonnegative")
5849
5850 if p >= len(self.digits):
5851 # compute p+3, p+6, p+9, ... digits; continue until at
5852 # least one of the extra digits is nonzero
5853 extra = 3
5854 while True:
5855 # compute p+extra digits, correct to within 1ulp
5856 M = 10**(p+extra+2)
5857 digits = str(_div_nearest(_ilog(10*M, M), 100))
5858 if digits[-extra:] != '0'*extra:
5859 break
5860 extra += 3
5861 # keep all reliable digits so far; remove trailing zeros
5862 # and next nonzero digit
5863 self.digits = digits.rstrip('0')[:-1]
5864 return int(self.digits[:p+1])
5865
5866_log10_digits = _Log10Memoize().getdigits
5867
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005868def _iexp(x, M, L=8):
5869 """Given integers x and M, M > 0, such that x/M is small in absolute
5870 value, compute an integer approximation to M*exp(x/M). For 0 <=
5871 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5872 is usually much smaller)."""
5873
5874 # Algorithm: to compute exp(z) for a real number z, first divide z
5875 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5876 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5877 # series
5878 #
5879 # expm1(x) = x + x**2/2! + x**3/3! + ...
5880 #
5881 # Now use the identity
5882 #
5883 # expm1(2x) = expm1(x)*(expm1(x)+2)
5884 #
5885 # R times to compute the sequence expm1(z/2**R),
5886 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5887
5888 # Find R such that x/2**R/M <= 2**-L
5889 R = _nbits((x<<L)//M)
5890
5891 # Taylor series. (2**L)**T > M
5892 T = -int(-10*len(str(M))//(3*L))
5893 y = _div_nearest(x, T)
5894 Mshift = M<<R
5895 for i in range(T-1, 0, -1):
5896 y = _div_nearest(x*(Mshift + y), Mshift * i)
5897
5898 # Expansion
5899 for k in range(R-1, -1, -1):
5900 Mshift = M<<(k+2)
5901 y = _div_nearest(y*(y+Mshift), Mshift)
5902
5903 return M+y
5904
5905def _dexp(c, e, p):
5906 """Compute an approximation to exp(c*10**e), with p decimal places of
5907 precision.
5908
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005909 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005910
5911 10**(p-1) <= d <= 10**p, and
5912 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5913
5914 In other words, d*10**f is an approximation to exp(c*10**e) with p
5915 digits of precision, and with an error in d of at most 1. This is
5916 almost, but not quite, the same as the error being < 1ulp: when d
5917 = 10**(p-1) the error could be up to 10 ulp."""
5918
5919 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5920 p += 2
5921
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005922 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005923 extra = max(0, e + len(str(c)) - 1)
5924 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005925
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005926 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005927 # rounding down
5928 shift = e+q
5929 if shift >= 0:
5930 cshift = c*10**shift
5931 else:
5932 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005933 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005934
5935 # reduce remainder back to original precision
5936 rem = _div_nearest(rem, 10**extra)
5937
5938 # error in result of _iexp < 120; error after division < 0.62
5939 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5940
5941def _dpower(xc, xe, yc, ye, p):
5942 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5943 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5944
5945 10**(p-1) <= c <= 10**p, and
5946 (c-1)*10**e < x**y < (c+1)*10**e
5947
5948 in other words, c*10**e is an approximation to x**y with p digits
5949 of precision, and with an error in c of at most 1. (This is
5950 almost, but not quite, the same as the error being < 1ulp: when c
5951 == 10**(p-1) we can only guarantee error < 10ulp.)
5952
5953 We assume that: x is positive and not equal to 1, and y is nonzero.
5954 """
5955
5956 # Find b such that 10**(b-1) <= |y| <= 10**b
5957 b = len(str(abs(yc))) + ye
5958
5959 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5960 lxc = _dlog(xc, xe, p+b+1)
5961
5962 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5963 shift = ye-b
5964 if shift >= 0:
5965 pc = lxc*yc*10**shift
5966 else:
5967 pc = _div_nearest(lxc*yc, 10**-shift)
5968
5969 if pc == 0:
5970 # we prefer a result that isn't exactly 1; this makes it
5971 # easier to compute a correctly rounded result in __pow__
5972 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5973 coeff, exp = 10**(p-1)+1, 1-p
5974 else:
5975 coeff, exp = 10**p-1, -p
5976 else:
5977 coeff, exp = _dexp(pc, -(p+1), p+1)
5978 coeff = _div_nearest(coeff, 10)
5979 exp += 1
5980
5981 return coeff, exp
5982
5983def _log10_lb(c, correction = {
5984 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5985 '6': 23, '7': 16, '8': 10, '9': 5}):
5986 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5987 if c <= 0:
5988 raise ValueError("The argument to _log10_lb should be nonnegative.")
5989 str_c = str(c)
5990 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005991
Guido van Rossumd8faa362007-04-27 19:54:29 +00005992##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005993
Mark Dickinsonac256ab2010-04-03 11:08:14 +00005994def _convert_other(other, raiseit=False, allow_float=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005995 """Convert other to Decimal.
5996
5997 Verifies that it's ok to use in an implicit construction.
Mark Dickinsonac256ab2010-04-03 11:08:14 +00005998 If allow_float is true, allow conversion from float; this
5999 is used in the comparison methods (__eq__ and friends).
6000
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006001 """
6002 if isinstance(other, Decimal):
6003 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00006004 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006005 return Decimal(other)
Mark Dickinsonac256ab2010-04-03 11:08:14 +00006006 if allow_float and isinstance(other, float):
6007 return Decimal.from_float(other)
6008
Thomas Wouters1b7f8912007-09-19 03:06:30 +00006009 if raiseit:
6010 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00006011 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006012
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006013def _convert_for_comparison(self, other, equality_op=False):
6014 """Given a Decimal instance self and a Python object other, return
Mark Dickinson1c164a62010-06-11 16:49:20 +00006015 a pair (s, o) of Decimal instances such that "s op o" is
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006016 equivalent to "self op other" for any of the 6 comparison
6017 operators "op".
6018
6019 """
6020 if isinstance(other, Decimal):
6021 return self, other
6022
6023 # Comparison with a Rational instance (also includes integers):
6024 # self op n/d <=> self*d op n (for n and d integers, d positive).
6025 # A NaN or infinity can be left unchanged without affecting the
6026 # comparison result.
6027 if isinstance(other, _numbers.Rational):
6028 if not self._is_special:
6029 self = _dec_from_triple(self._sign,
6030 str(int(self._int) * other.denominator),
6031 self._exp)
6032 return self, Decimal(other.numerator)
6033
6034 # Comparisons with float and complex types. == and != comparisons
6035 # with complex numbers should succeed, returning either True or False
6036 # as appropriate. Other comparisons return NotImplemented.
6037 if equality_op and isinstance(other, _numbers.Complex) and other.imag == 0:
6038 other = other.real
6039 if isinstance(other, float):
Stefan Krah1919b7e2012-03-21 18:25:23 +01006040 context = getcontext()
6041 if equality_op:
6042 context.flags[FloatOperation] = 1
6043 else:
6044 context._raise_error(FloatOperation,
6045 "strict semantics for mixing floats and Decimals are enabled")
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006046 return self, Decimal.from_float(other)
6047 return NotImplemented, NotImplemented
6048
6049
Guido van Rossumd8faa362007-04-27 19:54:29 +00006050##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006051
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006052# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00006053# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006054
6055DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00006056 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006057 traps=[DivisionByZero, Overflow, InvalidOperation],
6058 flags=[],
Stefan Krah1919b7e2012-03-21 18:25:23 +01006059 Emax=999999,
6060 Emin=-999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00006061 capitals=1,
6062 clamp=0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006063)
6064
6065# Pre-made alternate contexts offered by the specification
6066# Don't change these; the user should be able to select these
6067# contexts and be able to reproduce results from other implementations
6068# of the spec.
6069
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00006070BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006071 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006072 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
6073 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006074)
6075
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00006076ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00006077 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006078 traps=[],
6079 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006080)
6081
6082
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006083##### crud for parsing strings #############################################
Christian Heimes23daade02008-02-25 12:39:23 +00006084#
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006085# Regular expression used for parsing numeric strings. Additional
6086# comments:
6087#
6088# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
6089# whitespace. But note that the specification disallows whitespace in
6090# a numeric string.
6091#
6092# 2. For finite numbers (not infinities and NaNs) the body of the
6093# number between the optional sign and the optional exponent must have
6094# at least one decimal digit, possibly after the decimal point. The
Mark Dickinson345adc42009-08-02 10:14:23 +00006095# lookahead expression '(?=\d|\.\d)' checks this.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006096
6097import re
Benjamin Peterson41181742008-07-02 20:22:54 +00006098_parser = re.compile(r""" # A numeric string consists of:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006099# \s*
Benjamin Peterson41181742008-07-02 20:22:54 +00006100 (?P<sign>[-+])? # an optional sign, followed by either...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006101 (
Mark Dickinson345adc42009-08-02 10:14:23 +00006102 (?=\d|\.\d) # ...a number (with at least one digit)
6103 (?P<int>\d*) # having a (possibly empty) integer part
6104 (\.(?P<frac>\d*))? # followed by an optional fractional part
6105 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006106 |
Benjamin Peterson41181742008-07-02 20:22:54 +00006107 Inf(inity)? # ...an infinity, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006108 |
Benjamin Peterson41181742008-07-02 20:22:54 +00006109 (?P<signal>s)? # ...an (optionally signaling)
6110 NaN # NaN
Mark Dickinson345adc42009-08-02 10:14:23 +00006111 (?P<diag>\d*) # with (possibly empty) diagnostic info.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006112 )
6113# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00006114 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006115""", re.VERBOSE | re.IGNORECASE).match
6116
Christian Heimescbf3b5c2007-12-03 21:02:03 +00006117_all_zeros = re.compile('0*$').match
6118_exact_half = re.compile('50*$').match
Christian Heimesf16baeb2008-02-29 14:57:44 +00006119
6120##### PEP3101 support functions ##############################################
Mark Dickinson79f52032009-03-17 23:12:51 +00006121# The functions in this section have little to do with the Decimal
6122# class, and could potentially be reused or adapted for other pure
Christian Heimesf16baeb2008-02-29 14:57:44 +00006123# Python numeric classes that want to implement __format__
6124#
6125# A format specifier for Decimal looks like:
6126#
Eric Smith984bb582010-11-25 16:08:06 +00006127# [[fill]align][sign][#][0][minimumwidth][,][.precision][type]
Christian Heimesf16baeb2008-02-29 14:57:44 +00006128
6129_parse_format_specifier_regex = re.compile(r"""\A
6130(?:
6131 (?P<fill>.)?
6132 (?P<align>[<>=^])
6133)?
6134(?P<sign>[-+ ])?
Eric Smith984bb582010-11-25 16:08:06 +00006135(?P<alt>\#)?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006136(?P<zeropad>0)?
6137(?P<minimumwidth>(?!0)\d+)?
Mark Dickinson79f52032009-03-17 23:12:51 +00006138(?P<thousands_sep>,)?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006139(?:\.(?P<precision>0|(?!0)\d+))?
Mark Dickinson79f52032009-03-17 23:12:51 +00006140(?P<type>[eEfFgGn%])?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006141\Z
Stefan Krah6edda142013-05-29 15:45:38 +02006142""", re.VERBOSE|re.DOTALL)
Christian Heimesf16baeb2008-02-29 14:57:44 +00006143
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006144del re
6145
Mark Dickinson79f52032009-03-17 23:12:51 +00006146# The locale module is only needed for the 'n' format specifier. The
6147# rest of the PEP 3101 code functions quite happily without it, so we
6148# don't care too much if locale isn't present.
6149try:
6150 import locale as _locale
Brett Cannoncd171c82013-07-04 17:43:24 -04006151except ImportError:
Mark Dickinson79f52032009-03-17 23:12:51 +00006152 pass
6153
6154def _parse_format_specifier(format_spec, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00006155 """Parse and validate a format specifier.
6156
6157 Turns a standard numeric format specifier into a dict, with the
6158 following entries:
6159
6160 fill: fill character to pad field to minimum width
6161 align: alignment type, either '<', '>', '=' or '^'
6162 sign: either '+', '-' or ' '
6163 minimumwidth: nonnegative integer giving minimum width
Mark Dickinson79f52032009-03-17 23:12:51 +00006164 zeropad: boolean, indicating whether to pad with zeros
6165 thousands_sep: string to use as thousands separator, or ''
6166 grouping: grouping for thousands separators, in format
6167 used by localeconv
6168 decimal_point: string to use for decimal point
Christian Heimesf16baeb2008-02-29 14:57:44 +00006169 precision: nonnegative integer giving precision, or None
6170 type: one of the characters 'eEfFgG%', or None
Christian Heimesf16baeb2008-02-29 14:57:44 +00006171
6172 """
6173 m = _parse_format_specifier_regex.match(format_spec)
6174 if m is None:
6175 raise ValueError("Invalid format specifier: " + format_spec)
6176
6177 # get the dictionary
6178 format_dict = m.groupdict()
6179
Mark Dickinson79f52032009-03-17 23:12:51 +00006180 # zeropad; defaults for fill and alignment. If zero padding
6181 # is requested, the fill and align fields should be absent.
Christian Heimesf16baeb2008-02-29 14:57:44 +00006182 fill = format_dict['fill']
6183 align = format_dict['align']
Mark Dickinson79f52032009-03-17 23:12:51 +00006184 format_dict['zeropad'] = (format_dict['zeropad'] is not None)
6185 if format_dict['zeropad']:
6186 if fill is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00006187 raise ValueError("Fill character conflicts with '0'"
6188 " in format specifier: " + format_spec)
Mark Dickinson79f52032009-03-17 23:12:51 +00006189 if align is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00006190 raise ValueError("Alignment conflicts with '0' in "
6191 "format specifier: " + format_spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00006192 format_dict['fill'] = fill or ' '
Mark Dickinson46ab5d02009-09-08 20:22:46 +00006193 # PEP 3101 originally specified that the default alignment should
6194 # be left; it was later agreed that right-aligned makes more sense
6195 # for numeric types. See http://bugs.python.org/issue6857.
6196 format_dict['align'] = align or '>'
Christian Heimesf16baeb2008-02-29 14:57:44 +00006197
Mark Dickinson79f52032009-03-17 23:12:51 +00006198 # default sign handling: '-' for negative, '' for positive
Christian Heimesf16baeb2008-02-29 14:57:44 +00006199 if format_dict['sign'] is None:
6200 format_dict['sign'] = '-'
6201
Christian Heimesf16baeb2008-02-29 14:57:44 +00006202 # minimumwidth defaults to 0; precision remains None if not given
6203 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
6204 if format_dict['precision'] is not None:
6205 format_dict['precision'] = int(format_dict['precision'])
6206
6207 # if format type is 'g' or 'G' then a precision of 0 makes little
6208 # sense; convert it to 1. Same if format type is unspecified.
6209 if format_dict['precision'] == 0:
Stefan Krah1919b7e2012-03-21 18:25:23 +01006210 if format_dict['type'] is None or format_dict['type'] in 'gGn':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006211 format_dict['precision'] = 1
6212
Mark Dickinson79f52032009-03-17 23:12:51 +00006213 # determine thousands separator, grouping, and decimal separator, and
6214 # add appropriate entries to format_dict
6215 if format_dict['type'] == 'n':
6216 # apart from separators, 'n' behaves just like 'g'
6217 format_dict['type'] = 'g'
6218 if _localeconv is None:
6219 _localeconv = _locale.localeconv()
6220 if format_dict['thousands_sep'] is not None:
6221 raise ValueError("Explicit thousands separator conflicts with "
6222 "'n' type in format specifier: " + format_spec)
6223 format_dict['thousands_sep'] = _localeconv['thousands_sep']
6224 format_dict['grouping'] = _localeconv['grouping']
6225 format_dict['decimal_point'] = _localeconv['decimal_point']
6226 else:
6227 if format_dict['thousands_sep'] is None:
6228 format_dict['thousands_sep'] = ''
6229 format_dict['grouping'] = [3, 0]
6230 format_dict['decimal_point'] = '.'
Christian Heimesf16baeb2008-02-29 14:57:44 +00006231
6232 return format_dict
6233
Mark Dickinson79f52032009-03-17 23:12:51 +00006234def _format_align(sign, body, spec):
6235 """Given an unpadded, non-aligned numeric string 'body' and sign
Ezio Melotti42da6632011-03-15 05:18:48 +02006236 string 'sign', add padding and alignment conforming to the given
Mark Dickinson79f52032009-03-17 23:12:51 +00006237 format specifier dictionary 'spec' (as produced by
6238 parse_format_specifier).
Christian Heimesf16baeb2008-02-29 14:57:44 +00006239
6240 """
Christian Heimesf16baeb2008-02-29 14:57:44 +00006241 # how much extra space do we have to play with?
Mark Dickinson79f52032009-03-17 23:12:51 +00006242 minimumwidth = spec['minimumwidth']
6243 fill = spec['fill']
6244 padding = fill*(minimumwidth - len(sign) - len(body))
Christian Heimesf16baeb2008-02-29 14:57:44 +00006245
Mark Dickinson79f52032009-03-17 23:12:51 +00006246 align = spec['align']
Christian Heimesf16baeb2008-02-29 14:57:44 +00006247 if align == '<':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006248 result = sign + body + padding
Mark Dickinsonad416342009-03-17 18:10:15 +00006249 elif align == '>':
6250 result = padding + sign + body
Christian Heimesf16baeb2008-02-29 14:57:44 +00006251 elif align == '=':
6252 result = sign + padding + body
Mark Dickinson79f52032009-03-17 23:12:51 +00006253 elif align == '^':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006254 half = len(padding)//2
6255 result = padding[:half] + sign + body + padding[half:]
Mark Dickinson79f52032009-03-17 23:12:51 +00006256 else:
6257 raise ValueError('Unrecognised alignment field')
Christian Heimesf16baeb2008-02-29 14:57:44 +00006258
Christian Heimesf16baeb2008-02-29 14:57:44 +00006259 return result
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006260
Mark Dickinson79f52032009-03-17 23:12:51 +00006261def _group_lengths(grouping):
6262 """Convert a localeconv-style grouping into a (possibly infinite)
6263 iterable of integers representing group lengths.
6264
6265 """
6266 # The result from localeconv()['grouping'], and the input to this
6267 # function, should be a list of integers in one of the
6268 # following three forms:
6269 #
6270 # (1) an empty list, or
6271 # (2) nonempty list of positive integers + [0]
6272 # (3) list of positive integers + [locale.CHAR_MAX], or
6273
6274 from itertools import chain, repeat
6275 if not grouping:
6276 return []
6277 elif grouping[-1] == 0 and len(grouping) >= 2:
6278 return chain(grouping[:-1], repeat(grouping[-2]))
6279 elif grouping[-1] == _locale.CHAR_MAX:
6280 return grouping[:-1]
6281 else:
6282 raise ValueError('unrecognised format for grouping')
6283
6284def _insert_thousands_sep(digits, spec, min_width=1):
6285 """Insert thousands separators into a digit string.
6286
6287 spec is a dictionary whose keys should include 'thousands_sep' and
6288 'grouping'; typically it's the result of parsing the format
6289 specifier using _parse_format_specifier.
6290
6291 The min_width keyword argument gives the minimum length of the
6292 result, which will be padded on the left with zeros if necessary.
6293
6294 If necessary, the zero padding adds an extra '0' on the left to
6295 avoid a leading thousands separator. For example, inserting
6296 commas every three digits in '123456', with min_width=8, gives
6297 '0,123,456', even though that has length 9.
6298
6299 """
6300
6301 sep = spec['thousands_sep']
6302 grouping = spec['grouping']
6303
6304 groups = []
6305 for l in _group_lengths(grouping):
Mark Dickinson79f52032009-03-17 23:12:51 +00006306 if l <= 0:
6307 raise ValueError("group length should be positive")
6308 # max(..., 1) forces at least 1 digit to the left of a separator
6309 l = min(max(len(digits), min_width, 1), l)
6310 groups.append('0'*(l - len(digits)) + digits[-l:])
6311 digits = digits[:-l]
6312 min_width -= l
6313 if not digits and min_width <= 0:
6314 break
Mark Dickinson7303b592009-03-18 08:25:36 +00006315 min_width -= len(sep)
Mark Dickinson79f52032009-03-17 23:12:51 +00006316 else:
6317 l = max(len(digits), min_width, 1)
6318 groups.append('0'*(l - len(digits)) + digits[-l:])
6319 return sep.join(reversed(groups))
6320
6321def _format_sign(is_negative, spec):
6322 """Determine sign character."""
6323
6324 if is_negative:
6325 return '-'
6326 elif spec['sign'] in ' +':
6327 return spec['sign']
6328 else:
6329 return ''
6330
6331def _format_number(is_negative, intpart, fracpart, exp, spec):
6332 """Format a number, given the following data:
6333
6334 is_negative: true if the number is negative, else false
6335 intpart: string of digits that must appear before the decimal point
6336 fracpart: string of digits that must come after the point
6337 exp: exponent, as an integer
6338 spec: dictionary resulting from parsing the format specifier
6339
6340 This function uses the information in spec to:
6341 insert separators (decimal separator and thousands separators)
6342 format the sign
6343 format the exponent
6344 add trailing '%' for the '%' type
6345 zero-pad if necessary
6346 fill and align if necessary
6347 """
6348
6349 sign = _format_sign(is_negative, spec)
6350
Eric Smith984bb582010-11-25 16:08:06 +00006351 if fracpart or spec['alt']:
Mark Dickinson79f52032009-03-17 23:12:51 +00006352 fracpart = spec['decimal_point'] + fracpart
6353
6354 if exp != 0 or spec['type'] in 'eE':
6355 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
6356 fracpart += "{0}{1:+}".format(echar, exp)
6357 if spec['type'] == '%':
6358 fracpart += '%'
6359
6360 if spec['zeropad']:
6361 min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
6362 else:
6363 min_width = 0
6364 intpart = _insert_thousands_sep(intpart, spec, min_width)
6365
6366 return _format_align(sign, intpart+fracpart, spec)
6367
6368
Guido van Rossumd8faa362007-04-27 19:54:29 +00006369##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006370
Guido van Rossumd8faa362007-04-27 19:54:29 +00006371# Reusable defaults
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006372_Infinity = Decimal('Inf')
6373_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonf9236412009-01-02 23:23:21 +00006374_NaN = Decimal('NaN')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006375_Zero = Decimal(0)
6376_One = Decimal(1)
6377_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006378
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006379# _SignedInfinity[sign] is infinity w/ that sign
6380_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006381
Mark Dickinsondc787d22010-05-23 13:33:13 +00006382# Constants related to the hash implementation; hash(x) is based
6383# on the reduction of x modulo _PyHASH_MODULUS
Mark Dickinsondc787d22010-05-23 13:33:13 +00006384_PyHASH_MODULUS = sys.hash_info.modulus
6385# hash values to use for positive and negative infinities, and nans
6386_PyHASH_INF = sys.hash_info.inf
6387_PyHASH_NAN = sys.hash_info.nan
Mark Dickinsondc787d22010-05-23 13:33:13 +00006388
6389# _PyHASH_10INV is the inverse of 10 modulo the prime _PyHASH_MODULUS
6390_PyHASH_10INV = pow(10, _PyHASH_MODULUS - 2, _PyHASH_MODULUS)
Stefan Krah1919b7e2012-03-21 18:25:23 +01006391del sys
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006392
Stefan Krah1919b7e2012-03-21 18:25:23 +01006393try:
6394 import _decimal
Brett Cannoncd171c82013-07-04 17:43:24 -04006395except ImportError:
Stefan Krah1919b7e2012-03-21 18:25:23 +01006396 pass
6397else:
6398 s1 = set(dir())
6399 s2 = set(dir(_decimal))
6400 for name in s1 - s2:
6401 del globals()[name]
6402 del s1, s2, name
6403 from _decimal import *
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006404
6405if __name__ == '__main__':
Raymond Hettinger6d7e26e2011-02-01 23:54:43 +00006406 import doctest, decimal
6407 doctest.testmod(decimal)