blob: cdb88bc6e9c626d4b2009927e193c5d715386b83 [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
Raymond Hettinger27dbcf22004-08-19 22:39:55 +000010# This module is currently Py2.3 compatible and should be kept that way
11# unless a major compelling advantage arises. IOW, 2.3 compatibility is
12# strongly preferred, but not guaranteed.
13
14# Also, this module should be kept in sync with the latest updates of
15# the IBM specification as it evolves. Those updates will be treated
16# as bug fixes (deviation from the spec is a compatibility, usability
17# bug) and will be backported. At this point the spec is stabilizing
18# and the updates are becoming fewer, smaller, and less significant.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000019
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000020"""
21This is a Py2.3 implementation of decimal floating point arithmetic based on
22the General Decimal Arithmetic Specification:
23
24 www2.hursley.ibm.com/decimal/decarith.html
25
Raymond Hettinger0ea241e2004-07-04 13:53:24 +000026and IEEE standard 854-1987:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000027
28 www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
29
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000030Decimal floating point has finite precision with arbitrarily large bounds.
31
Guido van Rossumd8faa362007-04-27 19:54:29 +000032The purpose of this module is to support arithmetic using familiar
33"schoolhouse" rules and to avoid some of the tricky representation
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000034issues associated with binary floating point. The package is especially
35useful for financial applications or for contexts where users have
36expectations that are at odds with binary floating point (for instance,
37in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
38of the expected Decimal("0.00") returned by decimal floating point).
39
40Here are some examples of using the decimal module:
41
42>>> from decimal import *
Raymond Hettingerbd7f76d2004-07-08 00:49:18 +000043>>> setcontext(ExtendedContext)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000044>>> Decimal(0)
45Decimal("0")
46>>> Decimal("1")
47Decimal("1")
48>>> Decimal("-.0123")
49Decimal("-0.0123")
50>>> Decimal(123456)
51Decimal("123456")
52>>> Decimal("123.45e12345678901234567890")
53Decimal("1.2345E+12345678901234567892")
54>>> Decimal("1.33") + Decimal("1.27")
55Decimal("2.60")
56>>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41")
57Decimal("-2.20")
58>>> dig = Decimal(1)
Guido van Rossum7131f842007-02-09 20:13:25 +000059>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000600.333333333
61>>> getcontext().prec = 18
Guido van Rossum7131f842007-02-09 20:13:25 +000062>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000630.333333333333333333
Guido van Rossum7131f842007-02-09 20:13:25 +000064>>> print(dig.sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000651
Guido van Rossum7131f842007-02-09 20:13:25 +000066>>> print(Decimal(3).sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000671.73205080756887729
Guido van Rossum7131f842007-02-09 20:13:25 +000068>>> print(Decimal(3) ** 123)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000694.85192780976896427E+58
70>>> inf = Decimal(1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000071>>> print(inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000072Infinity
73>>> neginf = Decimal(-1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000074>>> print(neginf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000075-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000076>>> print(neginf + inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000077NaN
Guido van Rossum7131f842007-02-09 20:13:25 +000078>>> print(neginf * inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000079-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000080>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000081Infinity
Raymond Hettingerbf440692004-07-10 14:14:37 +000082>>> getcontext().traps[DivisionByZero] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000083>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000084Traceback (most recent call last):
85 ...
86 ...
87 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +000088decimal.DivisionByZero: x / 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000089>>> c = Context()
Raymond Hettingerbf440692004-07-10 14:14:37 +000090>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000091>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000920
93>>> c.divide(Decimal(0), Decimal(0))
94Decimal("NaN")
Raymond Hettingerbf440692004-07-10 14:14:37 +000095>>> c.traps[InvalidOperation] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000096>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000971
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000098>>> c.flags[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000099>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000
Guido van Rossum7131f842007-02-09 20:13:25 +0000101>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000102Traceback (most recent call last):
103 ...
104 ...
105 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +0000106decimal.InvalidOperation: 0 / 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000107>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000109>>> c.flags[InvalidOperation] = 0
Raymond Hettingerbf440692004-07-10 14:14:37 +0000110>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000111>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000112NaN
Guido van Rossum7131f842007-02-09 20:13:25 +0000113>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141
115>>>
116"""
117
118__all__ = [
119 # Two major classes
120 'Decimal', 'Context',
121
122 # Contexts
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +0000123 'DefaultContext', 'BasicContext', 'ExtendedContext',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000124
125 # Exceptions
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +0000126 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
127 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000128
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000129 # Constants for use in setting up contexts
130 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000131 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000132
133 # Functions for manipulating contexts
Thomas Wouters89f507f2006-12-13 04:49:30 +0000134 'setcontext', 'getcontext', 'localcontext'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000135]
136
Raymond Hettingereb260842005-06-07 18:52:34 +0000137import copy as _copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000138
Guido van Rossumd8faa362007-04-27 19:54:29 +0000139# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000140ROUND_DOWN = 'ROUND_DOWN'
141ROUND_HALF_UP = 'ROUND_HALF_UP'
142ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
143ROUND_CEILING = 'ROUND_CEILING'
144ROUND_FLOOR = 'ROUND_FLOOR'
145ROUND_UP = 'ROUND_UP'
146ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000147ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000148
Guido van Rossumd8faa362007-04-27 19:54:29 +0000149# Rounding decision (not part of the public API)
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000150NEVER_ROUND = 'NEVER_ROUND' # Round in division (non-divmod), sqrt ONLY
151ALWAYS_ROUND = 'ALWAYS_ROUND' # Every operation rounds at end.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000152
Guido van Rossumd8faa362007-04-27 19:54:29 +0000153# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000154
155class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000156 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000157
158 Used exceptions derive from this.
159 If an exception derives from another exception besides this (such as
160 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
161 called if the others are present. This isn't actually used for
162 anything, though.
163
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000164 handle -- Called when context._raise_error is called and the
165 trap_enabler is set. First argument is self, second is the
166 context. More arguments can be given, those being after
167 the explanation in _raise_error (For example,
168 context._raise_error(NewError, '(-x)!', self._sign) would
169 call NewError().handle(context, self._sign).)
170
171 To define a new exception, it should be sufficient to have it derive
172 from DecimalException.
173 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000174 def handle(self, context, *args):
175 pass
176
177
178class Clamped(DecimalException):
179 """Exponent of a 0 changed to fit bounds.
180
181 This occurs and signals clamped if the exponent of a result has been
182 altered in order to fit the constraints of a specific concrete
Guido van Rossumd8faa362007-04-27 19:54:29 +0000183 representation. This may occur when the exponent of a zero result would
184 be outside the bounds of a representation, or when a large normal
185 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000186 this latter case, the exponent is reduced to fit and the corresponding
187 number of zero digits are appended to the coefficient ("fold-down").
188 """
189
190
191class InvalidOperation(DecimalException):
192 """An invalid operation was performed.
193
194 Various bad things cause this:
195
196 Something creates a signaling NaN
197 -INF + INF
Guido van Rossumd8faa362007-04-27 19:54:29 +0000198 0 * (+-)INF
199 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000200 x % 0
201 (+-)INF % x
202 x._rescale( non-integer )
203 sqrt(-x) , x > 0
204 0 ** 0
205 x ** (non-integer)
206 x ** (+-)INF
207 An operand is invalid
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000208
209 The result of the operation after these is a quiet positive NaN,
210 except when the cause is a signaling NaN, in which case the result is
211 also a quiet NaN, but with the original sign, and an optional
212 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000213 """
214 def handle(self, context, *args):
215 if args:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000216 if args[0] == 1: # sNaN, must drop 's' but keep diagnostics
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000217 ans = Decimal((args[1]._sign, args[1]._int, 'n'))
218 return ans._fix_nan(context)
219 elif args[0] == 2:
220 return Decimal( (args[1], args[2], 'n') )
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000221 return NaN
222
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000223
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000224class ConversionSyntax(InvalidOperation):
225 """Trying to convert badly formed string.
226
227 This occurs and signals invalid-operation if an string is being
228 converted to a number and it does not conform to the numeric string
Guido van Rossumd8faa362007-04-27 19:54:29 +0000229 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000230 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000231 def handle(self, context, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000232 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000233
234class DivisionByZero(DecimalException, ZeroDivisionError):
235 """Division by 0.
236
237 This occurs and signals division-by-zero if division of a finite number
238 by zero was attempted (during a divide-integer or divide operation, or a
239 power operation with negative right-hand operand), and the dividend was
240 not zero.
241
242 The result of the operation is [sign,inf], where sign is the exclusive
243 or of the signs of the operands for divide, or is 1 for an odd power of
244 -0, for power.
245 """
246
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000247 def handle(self, context, sign, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000248 return Infsign[sign]
249
250class DivisionImpossible(InvalidOperation):
251 """Cannot perform the division adequately.
252
253 This occurs and signals invalid-operation if the integer result of a
254 divide-integer or remainder operation had too many digits (would be
Guido van Rossumd8faa362007-04-27 19:54:29 +0000255 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000256 """
257
258 def handle(self, context, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000259 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000260
261class DivisionUndefined(InvalidOperation, ZeroDivisionError):
262 """Undefined result of division.
263
264 This occurs and signals invalid-operation if division by zero was
265 attempted (during a divide-integer, divide, or remainder operation), and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000266 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000267 """
268
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000269 def handle(self, context, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000270 return NaN
271
272class Inexact(DecimalException):
273 """Had to round, losing information.
274
275 This occurs and signals inexact whenever the result of an operation is
276 not exact (that is, it needed to be rounded and any discarded digits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000277 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000278 result in all cases is unchanged.
279
280 The inexact signal may be tested (or trapped) to determine if a given
281 operation (or sequence of operations) was inexact.
282 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000283 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000284
285class InvalidContext(InvalidOperation):
286 """Invalid context. Unknown rounding, for example.
287
288 This occurs and signals invalid-operation if an invalid context was
Guido van Rossumd8faa362007-04-27 19:54:29 +0000289 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000290 on creation and either the precision exceeds the capability of the
291 underlying concrete representation or an unknown or unsupported rounding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000292 was specified. These aspects of the context need only be checked when
293 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000294 """
295
296 def handle(self, context, *args):
297 return NaN
298
299class Rounded(DecimalException):
300 """Number got rounded (not necessarily changed during rounding).
301
302 This occurs and signals rounded whenever the result of an operation is
303 rounded (that is, some zero or non-zero digits were discarded from the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000304 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000305 result in all cases is unchanged.
306
307 The rounded signal may be tested (or trapped) to determine if a given
308 operation (or sequence of operations) caused a loss of precision.
309 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000310 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000311
312class Subnormal(DecimalException):
313 """Exponent < Emin before rounding.
314
315 This occurs and signals subnormal whenever the result of a conversion or
316 operation is subnormal (that is, its adjusted exponent is less than
Guido van Rossumd8faa362007-04-27 19:54:29 +0000317 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000318
319 The subnormal signal may be tested (or trapped) to determine if a given
320 or operation (or sequence of operations) yielded a subnormal result.
321 """
322 pass
323
324class Overflow(Inexact, Rounded):
325 """Numerical overflow.
326
327 This occurs and signals overflow if the adjusted exponent of a result
328 (from a conversion or from an operation that is not an attempt to divide
329 by zero), after rounding, would be greater than the largest value that
330 can be handled by the implementation (the value Emax).
331
332 The result depends on the rounding mode:
333
334 For round-half-up and round-half-even (and for round-half-down and
335 round-up, if implemented), the result of the operation is [sign,inf],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000336 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337 result is the largest finite number that can be represented in the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000338 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000339 round-ceiling, the result is the same as for round-down if the sign of
Guido van Rossumd8faa362007-04-27 19:54:29 +0000340 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000341 the result is the same as for round-down if the sign of the intermediate
Guido van Rossumd8faa362007-04-27 19:54:29 +0000342 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000343 will also be raised.
344 """
345
346 def handle(self, context, sign, *args):
347 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000348 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000349 return Infsign[sign]
350 if sign == 0:
351 if context.rounding == ROUND_CEILING:
352 return Infsign[sign]
353 return Decimal((sign, (9,)*context.prec,
354 context.Emax-context.prec+1))
355 if sign == 1:
356 if context.rounding == ROUND_FLOOR:
357 return Infsign[sign]
358 return Decimal( (sign, (9,)*context.prec,
359 context.Emax-context.prec+1))
360
361
362class Underflow(Inexact, Rounded, Subnormal):
363 """Numerical underflow with result rounded to 0.
364
365 This occurs and signals underflow if a result is inexact and the
366 adjusted exponent of the result would be smaller (more negative) than
367 the smallest value that can be handled by the implementation (the value
Guido van Rossumd8faa362007-04-27 19:54:29 +0000368 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000369
370 The result after an underflow will be a subnormal number rounded, if
Guido van Rossumd8faa362007-04-27 19:54:29 +0000371 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000372 in 0 with the sign of the intermediate result and an exponent of Etiny.
373
374 In all cases, Inexact, Rounded, and Subnormal will also be raised.
375 """
376
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000377# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000378_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000379 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000380
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000381# Map conditions (per the spec) to signals
382_condition_map = {ConversionSyntax:InvalidOperation,
383 DivisionImpossible:InvalidOperation,
384 DivisionUndefined:InvalidOperation,
385 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000386
Guido van Rossumd8faa362007-04-27 19:54:29 +0000387##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000388
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000389# The getcontext() and setcontext() function manage access to a thread-local
390# current context. Py2.4 offers direct support for thread locals. If that
391# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000392# work for older Pythons. If threads are not part of the build, create a
393# mock threading object with threading.local() returning the module namespace.
394
395try:
396 import threading
397except ImportError:
398 # Python was compiled without threads; create a mock object instead
399 import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +0000400 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000401 def local(self, sys=sys):
402 return sys.modules[__name__]
403 threading = MockThreading()
404 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000405
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000406try:
407 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000408
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000409except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000410
Guido van Rossumd8faa362007-04-27 19:54:29 +0000411 # To fix reloading, force it to create a new context
412 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000413 if hasattr(threading.currentThread(), '__decimal_context__'):
414 del threading.currentThread().__decimal_context__
415
416 def setcontext(context):
417 """Set this thread's context to context."""
418 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000419 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000420 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000421 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000422
423 def getcontext():
424 """Returns this thread's context.
425
426 If this thread does not yet have a context, returns
427 a new context and sets this thread's context.
428 New contexts are copies of DefaultContext.
429 """
430 try:
431 return threading.currentThread().__decimal_context__
432 except AttributeError:
433 context = Context()
434 threading.currentThread().__decimal_context__ = context
435 return context
436
437else:
438
439 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000440 if hasattr(local, '__decimal_context__'):
441 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000442
443 def getcontext(_local=local):
444 """Returns this thread's context.
445
446 If this thread does not yet have a context, returns
447 a new context and sets this thread's context.
448 New contexts are copies of DefaultContext.
449 """
450 try:
451 return _local.__decimal_context__
452 except AttributeError:
453 context = Context()
454 _local.__decimal_context__ = context
455 return context
456
457 def setcontext(context, _local=local):
458 """Set this thread's context to context."""
459 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000460 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000461 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000462 _local.__decimal_context__ = context
463
464 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000465
Thomas Wouters89f507f2006-12-13 04:49:30 +0000466def localcontext(ctx=None):
467 """Return a context manager for a copy of the supplied context
468
469 Uses a copy of the current context if no context is specified
470 The returned context manager creates a local decimal context
471 in a with statement:
472 def sin(x):
473 with localcontext() as ctx:
474 ctx.prec += 2
475 # Rest of sin calculation algorithm
476 # uses a precision 2 greater than normal
Guido van Rossumd8faa362007-04-27 19:54:29 +0000477 return +s # Convert result to normal precision
Thomas Wouters89f507f2006-12-13 04:49:30 +0000478
479 def sin(x):
480 with localcontext(ExtendedContext):
481 # Rest of sin calculation algorithm
482 # uses the Extended Context from the
483 # General Decimal Arithmetic Specification
Guido van Rossumd8faa362007-04-27 19:54:29 +0000484 return +s # Convert result to normal context
Thomas Wouters89f507f2006-12-13 04:49:30 +0000485
486 """
487 # The string below can't be included in the docstring until Python 2.6
488 # as the doctest module doesn't understand __future__ statements
489 """
490 >>> from __future__ import with_statement
Guido van Rossum7131f842007-02-09 20:13:25 +0000491 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000492 28
493 >>> with localcontext():
494 ... ctx = getcontext()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000495 ... ctx.prec += 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000496 ... print(ctx.prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000497 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000498 30
499 >>> with localcontext(ExtendedContext):
Guido van Rossum7131f842007-02-09 20:13:25 +0000500 ... print(getcontext().prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000501 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000502 9
Guido van Rossum7131f842007-02-09 20:13:25 +0000503 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000504 28
505 """
506 if ctx is None: ctx = getcontext()
507 return _ContextManager(ctx)
508
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000509
Guido van Rossumd8faa362007-04-27 19:54:29 +0000510##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000511
512class Decimal(object):
513 """Floating point class for decimal arithmetic."""
514
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000515 __slots__ = ('_exp','_int','_sign', '_is_special')
516 # Generally, the value of the Decimal instance is given by
517 # (-1)**_sign * _int * 10**_exp
518 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000519
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000520 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000521 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000522 """Create a decimal point instance.
523
524 >>> Decimal('3.14') # string input
525 Decimal("3.14")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000526 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000527 Decimal("3.14")
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000528 >>> Decimal(314) # int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000529 Decimal("314")
530 >>> Decimal(Decimal(314)) # another decimal instance
531 Decimal("314")
532 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000533
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000534 self = object.__new__(cls)
535 self._is_special = False
536
537 # From an internal working value
538 if isinstance(value, _WorkRep):
Raymond Hettinger17931de2004-10-27 06:21:46 +0000539 self._sign = value.sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000540 self._int = tuple(map(int, str(value.int)))
541 self._exp = int(value.exp)
542 return self
543
544 # From another decimal
545 if isinstance(value, Decimal):
546 self._exp = value._exp
547 self._sign = value._sign
548 self._int = value._int
549 self._is_special = value._is_special
550 return self
551
552 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000553 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000554 if value >= 0:
555 self._sign = 0
556 else:
557 self._sign = 1
558 self._exp = 0
559 self._int = tuple(map(int, str(abs(value))))
560 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000561
562 # tuple/list conversion (possibly from as_tuple())
563 if isinstance(value, (list,tuple)):
564 if len(value) != 3:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000565 raise ValueError('Invalid arguments')
Raymond Hettingerdbecd932005-02-06 06:57:08 +0000566 if value[0] not in (0,1):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000567 raise ValueError('Invalid sign')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000568 for digit in value[1]:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000569 if not isinstance(digit, int) or digit < 0:
570 raise ValueError("The second value in the tuple must be "
Guido van Rossumd8faa362007-04-27 19:54:29 +0000571 "composed of non negative integer elements.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000572 self._sign = value[0]
573 self._int = tuple(value[1])
574 if value[2] in ('F','n','N'):
575 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000576 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000577 else:
578 self._exp = int(value[2])
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000579 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000580
Raymond Hettingerbf440692004-07-10 14:14:37 +0000581 if isinstance(value, float):
582 raise TypeError("Cannot convert float to Decimal. " +
583 "First convert the float to a string")
584
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000585 # Other argument types may require the context during interpretation
586 if context is None:
587 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000588
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000589 # From a string
590 # REs insist on real strings, so we can too.
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000591 if isinstance(value, str):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000592 if _isinfinity(value):
593 self._exp = 'F'
594 self._int = (0,)
595 self._is_special = True
596 if _isinfinity(value) == 1:
597 self._sign = 0
598 else:
599 self._sign = 1
600 return self
601 if _isnan(value):
602 sig, sign, diag = _isnan(value)
603 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000604 if sig == 1:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000605 self._exp = 'n' # qNaN
606 else: # sig == 2
607 self._exp = 'N' # sNaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000608 self._sign = sign
Guido van Rossumd8faa362007-04-27 19:54:29 +0000609 self._int = tuple(map(int, diag)) # Diagnostic info
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000610 return self
611 try:
612 self._sign, self._int, self._exp = _string2exact(value)
613 except ValueError:
614 self._is_special = True
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000615 return context._raise_error(ConversionSyntax,
616 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000617 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000618
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000619 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000620
621 def _isnan(self):
622 """Returns whether the number is not actually one.
623
624 0 if a number
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000625 1 if NaN (it could be a normal quiet NaN or a phantom one)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000626 2 if sNaN
627 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000628 if self._is_special:
629 exp = self._exp
630 if exp == 'n':
631 return 1
632 elif exp == 'N':
633 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000634 return 0
635
636 def _isinfinity(self):
637 """Returns whether the number is infinite
638
639 0 if finite or not a number
640 1 if +INF
641 -1 if -INF
642 """
643 if self._exp == 'F':
644 if self._sign:
645 return -1
646 return 1
647 return 0
648
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000649 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000650 """Returns whether the number is not actually one.
651
652 if self, other are sNaN, signal
653 if self, other are NaN return nan
654 return 0
655
656 Done before operations.
657 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000658
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000659 self_is_nan = self._isnan()
660 if other is None:
661 other_is_nan = False
662 else:
663 other_is_nan = other._isnan()
664
665 if self_is_nan or other_is_nan:
666 if context is None:
667 context = getcontext()
668
669 if self_is_nan == 2:
670 return context._raise_error(InvalidOperation, 'sNaN',
671 1, self)
672 if other_is_nan == 2:
673 return context._raise_error(InvalidOperation, 'sNaN',
674 1, other)
675 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000676 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000677
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000678 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000679 return 0
680
Jack Diederich4dafcc42006-11-28 19:15:13 +0000681 def __bool__(self):
Jack Diederich030debb2006-11-28 22:22:22 +0000682 """return True if the number is non-zero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000683
Jack Diederich030debb2006-11-28 22:22:22 +0000684 False if self == 0
685 True if self != 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000686 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000687 if self._is_special:
Jack Diederich4dafcc42006-11-28 19:15:13 +0000688 return True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000689 return sum(self._int) != 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000690
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000691 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000692 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000693 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000694 # Never return NotImplemented
695 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000696
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000697 if self._is_special or other._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000698 # check for nans, without raising on a signaling nan
699 if self._isnan() or other._isnan():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000700 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000701
702 # INF = INF
703 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000704
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000705 # check for zeros; note that cmp(0, -0) should return 0
706 if not self:
707 if not other:
708 return 0
709 else:
710 return -((-1)**other._sign)
711 if not other:
712 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000713
Guido van Rossumd8faa362007-04-27 19:54:29 +0000714 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000715 if other._sign < self._sign:
716 return -1
717 if self._sign < other._sign:
718 return 1
719
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000720 self_adjusted = self.adjusted()
721 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000722 if self_adjusted == other_adjusted:
723 self_padded = self._int + (0,)*(self._exp - other._exp)
724 other_padded = other._int + (0,)*(other._exp - self._exp)
725 return cmp(self_padded, other_padded) * (-1)**self._sign
726 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000727 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000728 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000729 return -((-1)**self._sign)
730
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000731 def __eq__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000732 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000733 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000734 return self.__cmp__(other) == 0
735
736 def __ne__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000737 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000738 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000739 return self.__cmp__(other) != 0
740
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000741 def __lt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000742 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000743 return NotImplemented
744 return self.__cmp__(other) < 0
745
746 def __le__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000747 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000748 return NotImplemented
749 return self.__cmp__(other) <= 0
750
751 def __gt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000752 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000753 return NotImplemented
754 return self.__cmp__(other) > 0
755
756 def __ge__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000757 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000758 return NotImplemented
759 return self.__cmp__(other) >= 0
760
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000761 def compare(self, other, context=None):
762 """Compares one to another.
763
764 -1 => a < b
765 0 => a = b
766 1 => a > b
767 NaN => one is NaN
768 Like __cmp__, but returns Decimal instances.
769 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000770 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000771
Guido van Rossumd8faa362007-04-27 19:54:29 +0000772 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000773 if (self._is_special or other and other._is_special):
774 ans = self._check_nans(other, context)
775 if ans:
776 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000777
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000778 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000779
780 def __hash__(self):
781 """x.__hash__() <==> hash(x)"""
782 # Decimal integers must hash the same as the ints
783 # Non-integer decimals are normalized and hashed as strings
Thomas Wouters477c8d52006-05-27 19:21:47 +0000784 # Normalization assures that hash(100E-1) == hash(10)
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000785 if self._is_special:
786 if self._isnan():
787 raise TypeError('Cannot hash a NaN value.')
788 return hash(str(self))
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000789 if not self:
790 return 0
791 if self._isinteger():
792 op = _WorkRep(self.to_integral_value())
793 # to make computation feasible for Decimals with large
794 # exponent, we use the fact that hash(n) == hash(m) for
795 # any two nonzero integers n and m such that (i) n and m
796 # have the same sign, and (ii) n is congruent to m modulo
797 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
798 # hash((-1)**s*c*pow(10, e, 2**64-1).
799 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000800 return hash(str(self.normalize()))
801
802 def as_tuple(self):
803 """Represents the number as a triple tuple.
804
805 To show the internals exactly as they are.
806 """
807 return (self._sign, self._int, self._exp)
808
809 def __repr__(self):
810 """Represents the number as an instance of Decimal."""
811 # Invariant: eval(repr(d)) == d
812 return 'Decimal("%s")' % str(self)
813
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000814 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000815 """Return string representation of the number in scientific notation.
816
817 Captures all of the information in the underlying representation.
818 """
819
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000820 if self._is_special:
821 if self._isnan():
822 minus = '-'*self._sign
823 if self._int == (0,):
824 info = ''
825 else:
826 info = ''.join(map(str, self._int))
827 if self._isnan() == 2:
828 return minus + 'sNaN' + info
829 return minus + 'NaN' + info
830 if self._isinfinity():
831 minus = '-'*self._sign
832 return minus + 'Infinity'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000833
834 if context is None:
835 context = getcontext()
836
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000837 tmp = list(map(str, self._int))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000838 numdigits = len(self._int)
839 leftdigits = self._exp + numdigits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000840 if eng and not self: # self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
841 if self._exp < 0 and self._exp >= -6: # short, no need for e/E
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000842 s = '-'*self._sign + '0.' + '0'*(abs(self._exp))
843 return s
Guido van Rossumd8faa362007-04-27 19:54:29 +0000844 # exp is closest mult. of 3 >= self._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000845 exp = ((self._exp - 1)// 3 + 1) * 3
846 if exp != self._exp:
847 s = '0.'+'0'*(exp - self._exp)
848 else:
849 s = '0'
850 if exp != 0:
851 if context.capitals:
852 s += 'E'
853 else:
854 s += 'e'
855 if exp > 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000856 s += '+' # 0.0e+3, not 0.0e3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000857 s += str(exp)
858 s = '-'*self._sign + s
859 return s
860 if eng:
861 dotplace = (leftdigits-1)%3+1
862 adjexp = leftdigits -1 - (leftdigits-1)%3
863 else:
864 adjexp = leftdigits-1
865 dotplace = 1
866 if self._exp == 0:
867 pass
868 elif self._exp < 0 and adjexp >= 0:
869 tmp.insert(leftdigits, '.')
870 elif self._exp < 0 and adjexp >= -6:
871 tmp[0:0] = ['0'] * int(-leftdigits)
872 tmp.insert(0, '0.')
873 else:
874 if numdigits > dotplace:
875 tmp.insert(dotplace, '.')
876 elif numdigits < dotplace:
877 tmp.extend(['0']*(dotplace-numdigits))
878 if adjexp:
879 if not context.capitals:
880 tmp.append('e')
881 else:
882 tmp.append('E')
883 if adjexp > 0:
884 tmp.append('+')
885 tmp.append(str(adjexp))
886 if eng:
887 while tmp[0:1] == ['0']:
888 tmp[0:1] = []
889 if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e':
890 tmp[0:0] = ['0']
891 if self._sign:
892 tmp.insert(0, '-')
893
894 return ''.join(tmp)
895
896 def to_eng_string(self, context=None):
897 """Convert to engineering-type string.
898
899 Engineering notation has an exponent which is a multiple of 3, so there
900 are up to 3 digits left of the decimal place.
901
902 Same rules for when in exponential and when as a value as in __str__.
903 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000904 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000905
906 def __neg__(self, context=None):
907 """Returns a copy with the sign switched.
908
909 Rounds, if it has reason.
910 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000911 if self._is_special:
912 ans = self._check_nans(context=context)
913 if ans:
914 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000915
916 if not self:
917 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000918 ans = self.copy_sign(Dec_0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000919 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000920 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000921
922 if context is None:
923 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000924 if context._rounding_decision == ALWAYS_ROUND:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000925 return ans._fix(context)
926 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000927
928 def __pos__(self, context=None):
929 """Returns a copy, unless it is a sNaN.
930
931 Rounds the number (if more then precision digits)
932 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000933 if self._is_special:
934 ans = self._check_nans(context=context)
935 if ans:
936 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000937
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000938 if not self:
939 # + (-0) = 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000940 ans = self.copy_sign(Dec_0)
941 else:
942 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000943
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000944 if context is None:
945 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000946 if context._rounding_decision == ALWAYS_ROUND:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000947 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000948 return ans
949
950 def __abs__(self, round=1, context=None):
951 """Returns the absolute value of self.
952
953 If the second argument is 0, do not round.
954 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000955 if self._is_special:
956 ans = self._check_nans(context=context)
957 if ans:
958 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000959
960 if not round:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000961 if context is None:
962 context = getcontext()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000963 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000964 context._set_rounding_decision(NEVER_ROUND)
965
966 if self._sign:
967 ans = self.__neg__(context=context)
968 else:
969 ans = self.__pos__(context=context)
970
971 return ans
972
973 def __add__(self, other, context=None):
974 """Returns self + other.
975
976 -INF + INF (or the reverse) cause InvalidOperation errors.
977 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000978 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000979 if other is NotImplemented:
980 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000981
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000982 if context is None:
983 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000984
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000985 if self._is_special or other._is_special:
986 ans = self._check_nans(other, context)
987 if ans:
988 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000989
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000990 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000991 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000992 if self._sign != other._sign and other._isinfinity():
993 return context._raise_error(InvalidOperation, '-INF + INF')
994 return Decimal(self)
995 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000996 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000997
998 shouldround = context._rounding_decision == ALWAYS_ROUND
999
1000 exp = min(self._exp, other._exp)
1001 negativezero = 0
1002 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001003 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001004 negativezero = 1
1005
1006 if not self and not other:
1007 sign = min(self._sign, other._sign)
1008 if negativezero:
1009 sign = 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001010 ans = Decimal( (sign, (0,), exp))
1011 if shouldround:
1012 ans = ans._fix(context)
1013 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001014 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001015 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001016 ans = other._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001017 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001018 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001019 return ans
1020 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001021 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001022 ans = self._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001023 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001024 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001025 return ans
1026
1027 op1 = _WorkRep(self)
1028 op2 = _WorkRep(other)
1029 op1, op2 = _normalize(op1, op2, shouldround, context.prec)
1030
1031 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001032 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001033 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001034 if op1.int == op2.int:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001035 ans = Decimal((negativezero, (0,), exp))
1036 if shouldround:
1037 ans = ans._fix(context)
1038 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001039 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001040 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001041 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001042 if op1.sign == 1:
1043 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001044 op1.sign, op2.sign = op2.sign, op1.sign
1045 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001046 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001047 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001048 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001049 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001050 op1.sign, op2.sign = (0, 0)
1051 else:
1052 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001053 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001054
Raymond Hettinger17931de2004-10-27 06:21:46 +00001055 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001056 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001057 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001058 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001059
1060 result.exp = op1.exp
1061 ans = Decimal(result)
1062 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001063 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001064 return ans
1065
1066 __radd__ = __add__
1067
1068 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001069 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001070 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001071 if other is NotImplemented:
1072 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001073
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001074 if self._is_special or other._is_special:
1075 ans = self._check_nans(other, context=context)
1076 if ans:
1077 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001078
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001079 # self - other is computed as self + other.copy_negate()
1080 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081
1082 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001083 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001084 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001085 if other is NotImplemented:
1086 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001087
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001088 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001089
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001090 def _increment(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001091 """Special case of add, adding 1eExponent
1092
1093 Since it is common, (rounding, for example) this adds
1094 (sign)*one E self._exp to the number more efficiently than add.
1095
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001096 Assumes that self is nonspecial.
1097
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001098 For example:
1099 Decimal('5.624e10')._increment() == Decimal('5.625e10')
1100 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001101 L = list(self._int)
1102 L[-1] += 1
1103 spot = len(L)-1
1104 while L[spot] == 10:
1105 L[spot] = 0
1106 if spot == 0:
1107 L[0:0] = [1]
1108 break
1109 L[spot-1] += 1
1110 spot -= 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001111 return Decimal((self._sign, L, self._exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001112
1113 def __mul__(self, other, context=None):
1114 """Return self * other.
1115
1116 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1117 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001118 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001119 if other is NotImplemented:
1120 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001121
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001122 if context is None:
1123 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001124
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001125 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001126
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001127 if self._is_special or other._is_special:
1128 ans = self._check_nans(other, context)
1129 if ans:
1130 return ans
1131
1132 if self._isinfinity():
1133 if not other:
1134 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1135 return Infsign[resultsign]
1136
1137 if other._isinfinity():
1138 if not self:
1139 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1140 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141
1142 resultexp = self._exp + other._exp
1143 shouldround = context._rounding_decision == ALWAYS_ROUND
1144
1145 # Special case for multiplying by zero
1146 if not self or not other:
1147 ans = Decimal((resultsign, (0,), resultexp))
1148 if shouldround:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001149 # Fixing in case the exponent is out of bounds
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001150 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001151 return ans
1152
1153 # Special case for multiplying by power of 10
1154 if self._int == (1,):
1155 ans = Decimal((resultsign, other._int, resultexp))
1156 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001157 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001158 return ans
1159 if other._int == (1,):
1160 ans = Decimal((resultsign, self._int, resultexp))
1161 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001162 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001163 return ans
1164
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001165 op1 = _WorkRep(self)
1166 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001167
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001168 ans = Decimal((resultsign,
1169 tuple(map(int, str(op1.int * op2.int))),
1170 resultexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001171 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001172 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001173
1174 return ans
1175 __rmul__ = __mul__
1176
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001177 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001178 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001179 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001180 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001181 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001182
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001183 if context is None:
1184 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001185
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001186 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001187
1188 if self._is_special or other._is_special:
1189 ans = self._check_nans(other, context)
1190 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001191 return ans
1192
1193 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001194 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001195
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001196 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001197 return Infsign[sign]
1198
1199 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001200 context._raise_error(Clamped, 'Division by infinity')
1201 return Decimal((sign, (0,), context.Etiny()))
1202
1203 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001204 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001205 if not self:
1206 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001207 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001208
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001209 if not self:
1210 exp = self._exp - other._exp
1211 coeff = 0
1212 else:
1213 # OK, so neither = 0, INF or NaN
1214 shift = len(other._int) - len(self._int) + context.prec + 1
1215 exp = self._exp - other._exp - shift
1216 op1 = _WorkRep(self)
1217 op2 = _WorkRep(other)
1218 if shift >= 0:
1219 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1220 else:
1221 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1222 if remainder:
1223 # result is not exact; adjust to ensure correct rounding
1224 if coeff % 5 == 0:
1225 coeff += 1
1226 else:
1227 # result is exact; get as close to ideal exponent as possible
1228 ideal_exp = self._exp - other._exp
1229 while exp < ideal_exp and coeff % 10 == 0:
1230 coeff //= 10
1231 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001232
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001233 ans = Decimal((sign, list(map(int, str(coeff))), exp))
1234 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001235
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001236 def _divide(self, other, context):
1237 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001238
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001239 Assumes that neither self nor other is a NaN, that self is not
1240 infinite and that other is nonzero.
1241 """
1242 sign = self._sign ^ other._sign
1243 if other._isinfinity():
1244 ideal_exp = self._exp
1245 else:
1246 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001247
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001248 expdiff = self.adjusted() - other.adjusted()
1249 if not self or other._isinfinity() or expdiff <= -2:
1250 return (Decimal((sign, (0,), 0)),
1251 self._rescale(ideal_exp, context.rounding))
1252 if expdiff <= context.prec:
1253 op1 = _WorkRep(self)
1254 op2 = _WorkRep(other)
1255 if op1.exp >= op2.exp:
1256 op1.int *= 10**(op1.exp - op2.exp)
1257 else:
1258 op2.int *= 10**(op2.exp - op1.exp)
1259 q, r = divmod(op1.int, op2.int)
1260 if q < 10**context.prec:
1261 return (Decimal((sign, list(map(int, str(q))), 0)),
1262 Decimal((self._sign, list(map(int, str(r))),
1263 ideal_exp)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001264
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001265 # Here the quotient is too large to be representable
1266 ans = context._raise_error(DivisionImpossible,
1267 'quotient too large in //, % or divmod')
1268 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001269
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001270 def __rtruediv__(self, other, context=None):
1271 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001272 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001273 if other is NotImplemented:
1274 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001275 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001276
1277 def __divmod__(self, other, context=None):
1278 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001279 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001280 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001281 other = _convert_other(other)
1282 if other is NotImplemented:
1283 return other
1284
1285 if context is None:
1286 context = getcontext()
1287
1288 ans = self._check_nans(other, context)
1289 if ans:
1290 return (ans, ans)
1291
1292 sign = self._sign ^ other._sign
1293 if self._isinfinity():
1294 if other._isinfinity():
1295 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1296 return ans, ans
1297 else:
1298 return (Infsign[sign],
1299 context._raise_error(InvalidOperation, 'INF % x'))
1300
1301 if not other:
1302 if not self:
1303 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1304 return ans, ans
1305 else:
1306 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1307 context._raise_error(InvalidOperation, 'x % 0'))
1308
1309 quotient, remainder = self._divide(other, context)
1310 if context._rounding_decision == ALWAYS_ROUND:
1311 remainder = remainder._fix(context)
1312 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001313
1314 def __rdivmod__(self, other, context=None):
1315 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001316 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001317 if other is NotImplemented:
1318 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001319 return other.__divmod__(self, context=context)
1320
1321 def __mod__(self, other, context=None):
1322 """
1323 self % other
1324 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001325 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001326 if other is NotImplemented:
1327 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001328
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001329 if context is None:
1330 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001331
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001332 ans = self._check_nans(other, context)
1333 if ans:
1334 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001335
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001336 if self._isinfinity():
1337 return context._raise_error(InvalidOperation, 'INF % x')
1338 elif not other:
1339 if self:
1340 return context._raise_error(InvalidOperation, 'x % 0')
1341 else:
1342 return context._raise_error(DivisionUndefined, '0 % 0')
1343
1344 remainder = self._divide(other, context)[1]
1345 if context._rounding_decision == ALWAYS_ROUND:
1346 remainder = remainder._fix(context)
1347 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001348
1349 def __rmod__(self, other, context=None):
1350 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001351 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001352 if other is NotImplemented:
1353 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001354 return other.__mod__(self, context=context)
1355
1356 def remainder_near(self, other, context=None):
1357 """
1358 Remainder nearest to 0- abs(remainder-near) <= other/2
1359 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001360 if context is None:
1361 context = getcontext()
1362
1363 other = _convert_other(other, raiseit=True)
1364
1365 ans = self._check_nans(other, context)
1366 if ans:
1367 return ans
1368
1369 # self == +/-infinity -> InvalidOperation
1370 if self._isinfinity():
1371 return context._raise_error(InvalidOperation,
1372 'remainder_near(infinity, x)')
1373
1374 # other == 0 -> either InvalidOperation or DivisionUndefined
1375 if not other:
1376 if self:
1377 return context._raise_error(InvalidOperation,
1378 'remainder_near(x, 0)')
1379 else:
1380 return context._raise_error(DivisionUndefined,
1381 'remainder_near(0, 0)')
1382
1383 # other = +/-infinity -> remainder = self
1384 if other._isinfinity():
1385 ans = Decimal(self)
1386 return ans._fix(context)
1387
1388 # self = 0 -> remainder = self, with ideal exponent
1389 ideal_exponent = min(self._exp, other._exp)
1390 if not self:
1391 ans = Decimal((self._sign, (0,), ideal_exponent))
1392 return ans._fix(context)
1393
1394 # catch most cases of large or small quotient
1395 expdiff = self.adjusted() - other.adjusted()
1396 if expdiff >= context.prec + 1:
1397 # expdiff >= prec+1 => abs(self/other) > 10**prec
1398 return context._raise_error(DivisionImpossible)
1399 if expdiff <= -2:
1400 # expdiff <= -2 => abs(self/other) < 0.1
1401 ans = self._rescale(ideal_exponent, context.rounding)
1402 return ans._fix(context)
1403
1404 # adjust both arguments to have the same exponent, then divide
1405 op1 = _WorkRep(self)
1406 op2 = _WorkRep(other)
1407 if op1.exp >= op2.exp:
1408 op1.int *= 10**(op1.exp - op2.exp)
1409 else:
1410 op2.int *= 10**(op2.exp - op1.exp)
1411 q, r = divmod(op1.int, op2.int)
1412 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1413 # 10**ideal_exponent. Apply correction to ensure that
1414 # abs(remainder) <= abs(other)/2
1415 if 2*r + (q&1) > op2.int:
1416 r -= op2.int
1417 q += 1
1418
1419 if q >= 10**context.prec:
1420 return context._raise_error(DivisionImpossible)
1421
1422 # result has same sign as self unless r is negative
1423 sign = self._sign
1424 if r < 0:
1425 sign = 1-sign
1426 r = -r
1427
1428 ans = Decimal((sign, list(map(int, str(r))), ideal_exponent))
1429 return ans._fix(context)
1430
1431 def __floordiv__(self, other, context=None):
1432 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001433 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001434 if other is NotImplemented:
1435 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001436
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001437 if context is None:
1438 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001439
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001440 ans = self._check_nans(other, context)
1441 if ans:
1442 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001443
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001444 if self._isinfinity():
1445 if other._isinfinity():
1446 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001447 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001448 return Infsign[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001449
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001450 if not other:
1451 if self:
1452 return context._raise_error(DivisionByZero, 'x // 0',
1453 self._sign ^ other._sign)
1454 else:
1455 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001456
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001457 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001458
1459 def __rfloordiv__(self, other, context=None):
1460 """Swaps self/other and returns __floordiv__."""
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 return other.__floordiv__(self, context=context)
1465
1466 def __float__(self):
1467 """Float representation."""
1468 return float(str(self))
1469
1470 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001471 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001472 if self._is_special:
1473 if self._isnan():
1474 context = getcontext()
1475 return context._raise_error(InvalidContext)
1476 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001477 raise OverflowError("Cannot convert infinity to int")
1478 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001479 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001480 return s*int(''.join(map(str, self._int)))*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001481 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001482 return s*int(''.join(map(str, self._int))[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001483
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001484 def _fix_nan(self, context):
1485 """Decapitate the payload of a NaN to fit the context"""
1486 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001487
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001488 # maximum length of payload is precision if _clamp=0,
1489 # precision-1 if _clamp=1.
1490 max_payload_len = context.prec - context._clamp
1491 if len(payload) > max_payload_len:
1492 pos = len(payload)-max_payload_len
1493 while pos < len(payload) and payload[pos] == 0:
1494 pos += 1
1495 payload = payload[pos:]
1496 return Decimal((self._sign, payload, self._exp))
1497 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001498
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001499 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001500 """Round if it is necessary to keep self within prec precision.
1501
1502 Rounds and fixes the exponent. Does not raise on a sNaN.
1503
1504 Arguments:
1505 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001506 context - context used.
1507 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001508
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001509 if context is None:
1510 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001511
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001512 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001513 if self._isnan():
1514 # decapitate payload if necessary
1515 return self._fix_nan(context)
1516 else:
1517 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001518 return Decimal(self)
1519
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001520 # if self is zero then exponent should be between Etiny and
1521 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1522 Etiny = context.Etiny()
1523 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001524 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001525 exp_max = [context.Emax, Etop][context._clamp]
1526 new_exp = min(max(self._exp, Etiny), exp_max)
1527 if new_exp != self._exp:
1528 context._raise_error(Clamped)
1529 return Decimal((self._sign, (0,), new_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001530 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001531 return Decimal(self)
1532
1533 # exp_min is the smallest allowable exponent of the result,
1534 # equal to max(self.adjusted()-context.prec+1, Etiny)
1535 exp_min = len(self._int) + self._exp - context.prec
1536 if exp_min > Etop:
1537 # overflow: exp_min > Etop iff self.adjusted() > Emax
1538 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001539 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001540 return context._raise_error(Overflow, 'above Emax', self._sign)
1541 self_is_subnormal = exp_min < Etiny
1542 if self_is_subnormal:
1543 context._raise_error(Subnormal)
1544 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001545
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001546 # round if self has too many digits
1547 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001548 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001549 ans = self._rescale(exp_min, context.rounding)
1550 if ans != self:
1551 context._raise_error(Inexact)
1552 if self_is_subnormal:
1553 context._raise_error(Underflow)
1554 if not ans:
1555 # raise Clamped on underflow to 0
1556 context._raise_error(Clamped)
1557 elif len(ans._int) == context.prec+1:
1558 # we get here only if rescaling rounds the
1559 # cofficient up to exactly 10**context.prec
1560 if ans._exp < Etop:
1561 ans = Decimal((ans._sign, ans._int[:-1], ans._exp+1))
1562 else:
1563 # Inexact and Rounded have already been raised
1564 ans = context._raise_error(Overflow, 'above Emax',
1565 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001566 return ans
1567
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001568 # fold down if _clamp == 1 and self has too few digits
1569 if context._clamp == 1 and self._exp > Etop:
1570 context._raise_error(Clamped)
1571 self_padded = self._int + (0,)*(self._exp - Etop)
1572 return Decimal((self._sign, self_padded, Etop))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001573
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001574 # here self was representable to begin with; return unchanged
1575 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001576
1577 _pick_rounding_function = {}
1578
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001579 # for each of the rounding functions below:
1580 # self is a finite, nonzero Decimal
1581 # prec is an integer satisfying 0 <= prec < len(self._int)
1582 # the rounded result will have exponent self._exp + len(self._int) - prec;
1583
1584 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001585 """Also known as round-towards-0, truncate."""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001586 newexp = self._exp + len(self._int) - prec
1587 return Decimal((self._sign, self._int[:prec] or (0,), newexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001588
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001589 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001590 """Rounds away from 0."""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001591 newexp = self._exp + len(self._int) - prec
1592 tmp = Decimal((self._sign, self._int[:prec] or (0,), newexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001593 for digit in self._int[prec:]:
1594 if digit != 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001595 return tmp._increment()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001596 return tmp
1597
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001598 def _round_half_up(self, prec):
1599 """Rounds 5 up (away from 0)"""
1600 if self._int[prec] >= 5:
1601 return self._round_up(prec)
1602 else:
1603 return self._round_down(prec)
1604
1605 def _round_half_down(self, prec):
1606 """Round 5 down"""
1607 if self._int[prec] == 5:
1608 for digit in self._int[prec+1:]:
1609 if digit != 0:
1610 break
1611 else:
1612 return self._round_down(prec)
1613 return self._round_half_up(prec)
1614
1615 def _round_half_even(self, prec):
1616 """Round 5 to even, rest to nearest."""
1617 if prec and self._int[prec-1] & 1:
1618 return self._round_half_up(prec)
1619 else:
1620 return self._round_half_down(prec)
1621
1622 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001623 """Rounds up (not away from 0 if negative.)"""
1624 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001625 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001626 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001627 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001628
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001629 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001630 """Rounds down (not towards 0 if negative)"""
1631 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001632 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001633 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001634 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001635
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001636 def _round_05up(self, prec):
1637 """Round down unless digit prec-1 is 0 or 5."""
1638 if prec == 0 or self._int[prec-1] in (0, 5):
1639 return self._round_up(prec)
1640 else:
1641 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001642
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001643 def fma(self, other, third, context=None):
1644 """Fused multiply-add.
1645
1646 Returns self*other+third with no rounding of the intermediate
1647 product self*other.
1648
1649 self and other are multiplied together, with no rounding of
1650 the result. The third operand is then added to the result,
1651 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001652 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001653
1654 other = _convert_other(other, raiseit=True)
1655 third = _convert_other(third, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001656
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001657 if context is None:
1658 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001659
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001660 # do self*other in fresh context with no traps and no rounding
1661 mul_context = Context(traps=[], flags=[],
1662 _rounding_decision=NEVER_ROUND)
1663 product = self.__mul__(other, mul_context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001664
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001665 if mul_context.flags[InvalidOperation]:
1666 # reraise in current context
1667 return context._raise_error(InvalidOperation,
1668 'invalid multiplication in fma',
1669 1, product)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001670
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001671 ans = product.__add__(third, context)
1672 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001673
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001674 def _power_modulo(self, other, modulo, context=None):
1675 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001676
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001677 # if can't convert other and modulo to Decimal, raise
1678 # TypeError; there's no point returning NotImplemented (no
1679 # equivalent of __rpow__ for three argument pow)
1680 other = _convert_other(other, raiseit=True)
1681 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001682
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001683 if context is None:
1684 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001685
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001686 # deal with NaNs: if there are any sNaNs then first one wins,
1687 # (i.e. behaviour for NaNs is identical to that of fma)
1688 self_is_nan = self._isnan()
1689 other_is_nan = other._isnan()
1690 modulo_is_nan = modulo._isnan()
1691 if self_is_nan or other_is_nan or modulo_is_nan:
1692 if self_is_nan == 2:
1693 return context._raise_error(InvalidOperation, 'sNaN',
1694 1, self)
1695 if other_is_nan == 2:
1696 return context._raise_error(InvalidOperation, 'sNaN',
1697 1, other)
1698 if modulo_is_nan == 2:
1699 return context._raise_error(InvalidOperation, 'sNaN',
1700 1, modulo)
1701 if self_is_nan:
1702 return self._fix_nan(context)
1703 if other_is_nan:
1704 return other._fix_nan(context)
1705 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001706
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001707 # check inputs: we apply same restrictions as Python's pow()
1708 if not (self._isinteger() and
1709 other._isinteger() and
1710 modulo._isinteger()):
1711 return context._raise_error(InvalidOperation,
1712 'pow() 3rd argument not allowed '
1713 'unless all arguments are integers')
1714 if other < 0:
1715 return context._raise_error(InvalidOperation,
1716 'pow() 2nd argument cannot be '
1717 'negative when 3rd argument specified')
1718 if not modulo:
1719 return context._raise_error(InvalidOperation,
1720 'pow() 3rd argument cannot be 0')
1721
1722 # additional restriction for decimal: the modulus must be less
1723 # than 10**prec in absolute value
1724 if modulo.adjusted() >= context.prec:
1725 return context._raise_error(InvalidOperation,
1726 'insufficient precision: pow() 3rd '
1727 'argument must not have more than '
1728 'precision digits')
1729
1730 # define 0**0 == NaN, for consistency with two-argument pow
1731 # (even though it hurts!)
1732 if not other and not self:
1733 return context._raise_error(InvalidOperation,
1734 'at least one of pow() 1st argument '
1735 'and 2nd argument must be nonzero ;'
1736 '0**0 is not defined')
1737
1738 # compute sign of result
1739 if other._iseven():
1740 sign = 0
1741 else:
1742 sign = self._sign
1743
1744 # convert modulo to a Python integer, and self and other to
1745 # Decimal integers (i.e. force their exponents to be >= 0)
1746 modulo = abs(int(modulo))
1747 base = _WorkRep(self.to_integral_value())
1748 exponent = _WorkRep(other.to_integral_value())
1749
1750 # compute result using integer pow()
1751 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1752 for i in range(exponent.exp):
1753 base = pow(base, 10, modulo)
1754 base = pow(base, exponent.int, modulo)
1755
1756 return Decimal((sign, list(map(int, str(base))), 0))
1757
1758 def _power_exact(self, other, p):
1759 """Attempt to compute self**other exactly.
1760
1761 Given Decimals self and other and an integer p, attempt to
1762 compute an exact result for the power self**other, with p
1763 digits of precision. Return None if self**other is not
1764 exactly representable in p digits.
1765
1766 Assumes that elimination of special cases has already been
1767 performed: self and other must both be nonspecial; self must
1768 be positive and not numerically equal to 1; other must be
1769 nonzero. For efficiency, other._exp should not be too large,
1770 so that 10**abs(other._exp) is a feasible calculation."""
1771
1772 # In the comments below, we write x for the value of self and
1773 # y for the value of other. Write x = xc*10**xe and y =
1774 # yc*10**ye.
1775
1776 # The main purpose of this method is to identify the *failure*
1777 # of x**y to be exactly representable with as little effort as
1778 # possible. So we look for cheap and easy tests that
1779 # eliminate the possibility of x**y being exact. Only if all
1780 # these tests are passed do we go on to actually compute x**y.
1781
1782 # Here's the main idea. First normalize both x and y. We
1783 # express y as a rational m/n, with m and n relatively prime
1784 # and n>0. Then for x**y to be exactly representable (at
1785 # *any* precision), xc must be the nth power of a positive
1786 # integer and xe must be divisible by n. If m is negative
1787 # then additionally xc must be a power of either 2 or 5, hence
1788 # a power of 2**n or 5**n.
1789 #
1790 # There's a limit to how small |y| can be: if y=m/n as above
1791 # then:
1792 #
1793 # (1) if xc != 1 then for the result to be representable we
1794 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1795 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1796 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1797 # representable.
1798 #
1799 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1800 # |y| < 1/|xe| then the result is not representable.
1801 #
1802 # Note that since x is not equal to 1, at least one of (1) and
1803 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1804 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1805 #
1806 # There's also a limit to how large y can be, at least if it's
1807 # positive: the normalized result will have coefficient xc**y,
1808 # so if it's representable then xc**y < 10**p, and y <
1809 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1810 # not exactly representable.
1811
1812 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1813 # so |y| < 1/xe and the result is not representable.
1814 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1815 # < 1/nbits(xc).
1816
1817 x = _WorkRep(self)
1818 xc, xe = x.int, x.exp
1819 while xc % 10 == 0:
1820 xc //= 10
1821 xe += 1
1822
1823 y = _WorkRep(other)
1824 yc, ye = y.int, y.exp
1825 while yc % 10 == 0:
1826 yc //= 10
1827 ye += 1
1828
1829 # case where xc == 1: result is 10**(xe*y), with xe*y
1830 # required to be an integer
1831 if xc == 1:
1832 if ye >= 0:
1833 exponent = xe*yc*10**ye
1834 else:
1835 exponent, remainder = divmod(xe*yc, 10**-ye)
1836 if remainder:
1837 return None
1838 if y.sign == 1:
1839 exponent = -exponent
1840 # if other is a nonnegative integer, use ideal exponent
1841 if other._isinteger() and other._sign == 0:
1842 ideal_exponent = self._exp*int(other)
1843 zeros = min(exponent-ideal_exponent, p-1)
1844 else:
1845 zeros = 0
1846 return Decimal((0, (1,) + (0,)*zeros, exponent-zeros))
1847
1848 # case where y is negative: xc must be either a power
1849 # of 2 or a power of 5.
1850 if y.sign == 1:
1851 last_digit = xc % 10
1852 if last_digit in (2,4,6,8):
1853 # quick test for power of 2
1854 if xc & -xc != xc:
1855 return None
1856 # now xc is a power of 2; e is its exponent
1857 e = _nbits(xc)-1
1858 # find e*y and xe*y; both must be integers
1859 if ye >= 0:
1860 y_as_int = yc*10**ye
1861 e = e*y_as_int
1862 xe = xe*y_as_int
1863 else:
1864 ten_pow = 10**-ye
1865 e, remainder = divmod(e*yc, ten_pow)
1866 if remainder:
1867 return None
1868 xe, remainder = divmod(xe*yc, ten_pow)
1869 if remainder:
1870 return None
1871
1872 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1873 return None
1874 xc = 5**e
1875
1876 elif last_digit == 5:
1877 # e >= log_5(xc) if xc is a power of 5; we have
1878 # equality all the way up to xc=5**2658
1879 e = _nbits(xc)*28//65
1880 xc, remainder = divmod(5**e, xc)
1881 if remainder:
1882 return None
1883 while xc % 5 == 0:
1884 xc //= 5
1885 e -= 1
1886 if ye >= 0:
1887 y_as_integer = yc*10**ye
1888 e = e*y_as_integer
1889 xe = xe*y_as_integer
1890 else:
1891 ten_pow = 10**-ye
1892 e, remainder = divmod(e*yc, ten_pow)
1893 if remainder:
1894 return None
1895 xe, remainder = divmod(xe*yc, ten_pow)
1896 if remainder:
1897 return None
1898 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1899 return None
1900 xc = 2**e
1901 else:
1902 return None
1903
1904 if xc >= 10**p:
1905 return None
1906 xe = -e-xe
1907 return Decimal((0, list(map(int, str(xc))), xe))
1908
1909 # now y is positive; find m and n such that y = m/n
1910 if ye >= 0:
1911 m, n = yc*10**ye, 1
1912 else:
1913 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1914 return None
1915 xc_bits = _nbits(xc)
1916 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1917 return None
1918 m, n = yc, 10**(-ye)
1919 while m % 2 == n % 2 == 0:
1920 m //= 2
1921 n //= 2
1922 while m % 5 == n % 5 == 0:
1923 m //= 5
1924 n //= 5
1925
1926 # compute nth root of xc*10**xe
1927 if n > 1:
1928 # if 1 < xc < 2**n then xc isn't an nth power
1929 if xc != 1 and xc_bits <= n:
1930 return None
1931
1932 xe, rem = divmod(xe, n)
1933 if rem != 0:
1934 return None
1935
1936 # compute nth root of xc using Newton's method
1937 a = 1 << -(-_nbits(xc)//n) # initial estimate
1938 while True:
1939 q, r = divmod(xc, a**(n-1))
1940 if a <= q:
1941 break
1942 else:
1943 a = (a*(n-1) + q)//n
1944 if not (a == q and r == 0):
1945 return None
1946 xc = a
1947
1948 # now xc*10**xe is the nth root of the original xc*10**xe
1949 # compute mth power of xc*10**xe
1950
1951 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1952 # 10**p and the result is not representable.
1953 if xc > 1 and m > p*100//_log10_lb(xc):
1954 return None
1955 xc = xc**m
1956 xe *= m
1957 if xc > 10**p:
1958 return None
1959
1960 # by this point the result *is* exactly representable
1961 # adjust the exponent to get as close as possible to the ideal
1962 # exponent, if necessary
1963 str_xc = str(xc)
1964 if other._isinteger() and other._sign == 0:
1965 ideal_exponent = self._exp*int(other)
1966 zeros = min(xe-ideal_exponent, p-len(str_xc))
1967 else:
1968 zeros = 0
1969 return Decimal((0, list(map(int, str_xc))+[0,]*zeros, xe-zeros))
1970
1971 def __pow__(self, other, modulo=None, context=None):
1972 """Return self ** other [ % modulo].
1973
1974 With two arguments, compute self**other.
1975
1976 With three arguments, compute (self**other) % modulo. For the
1977 three argument form, the following restrictions on the
1978 arguments hold:
1979
1980 - all three arguments must be integral
1981 - other must be nonnegative
1982 - either self or other (or both) must be nonzero
1983 - modulo must be nonzero and must have at most p digits,
1984 where p is the context precision.
1985
1986 If any of these restrictions is violated the InvalidOperation
1987 flag is raised.
1988
1989 The result of pow(self, other, modulo) is identical to the
1990 result that would be obtained by computing (self**other) %
1991 modulo with unbounded precision, but is computed more
1992 efficiently. It is always exact.
1993 """
1994
1995 if modulo is not None:
1996 return self._power_modulo(other, modulo, context)
1997
1998 other = _convert_other(other)
1999 if other is NotImplemented:
2000 return other
2001
2002 if context is None:
2003 context = getcontext()
2004
2005 # either argument is a NaN => result is NaN
2006 ans = self._check_nans(other, context)
2007 if ans:
2008 return ans
2009
2010 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2011 if not other:
2012 if not self:
2013 return context._raise_error(InvalidOperation, '0 ** 0')
2014 else:
2015 return Dec_p1
2016
2017 # result has sign 1 iff self._sign is 1 and other is an odd integer
2018 result_sign = 0
2019 if self._sign == 1:
2020 if other._isinteger():
2021 if not other._iseven():
2022 result_sign = 1
2023 else:
2024 # -ve**noninteger = NaN
2025 # (-0)**noninteger = 0**noninteger
2026 if self:
2027 return context._raise_error(InvalidOperation,
2028 'x ** y with x negative and y not an integer')
2029 # negate self, without doing any unwanted rounding
2030 self = Decimal((0, self._int, self._exp))
2031
2032 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2033 if not self:
2034 if other._sign == 0:
2035 return Decimal((result_sign, (0,), 0))
2036 else:
2037 return Infsign[result_sign]
2038
2039 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002040 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002041 if other._sign == 0:
2042 return Infsign[result_sign]
2043 else:
2044 return Decimal((result_sign, (0,), 0))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002045
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002046 # 1**other = 1, but the choice of exponent and the flags
2047 # depend on the exponent of self, and on whether other is a
2048 # positive integer, a negative integer, or neither
2049 if self == Dec_p1:
2050 if other._isinteger():
2051 # exp = max(self._exp*max(int(other), 0),
2052 # 1-context.prec) but evaluating int(other) directly
2053 # is dangerous until we know other is small (other
2054 # could be 1e999999999)
2055 if other._sign == 1:
2056 multiplier = 0
2057 elif other > context.prec:
2058 multiplier = context.prec
2059 else:
2060 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002061
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002062 exp = self._exp * multiplier
2063 if exp < 1-context.prec:
2064 exp = 1-context.prec
2065 context._raise_error(Rounded)
2066 else:
2067 context._raise_error(Inexact)
2068 context._raise_error(Rounded)
2069 exp = 1-context.prec
2070
2071 return Decimal((result_sign, (1,)+(0,)*-exp, exp))
2072
2073 # compute adjusted exponent of self
2074 self_adj = self.adjusted()
2075
2076 # self ** infinity is infinity if self > 1, 0 if self < 1
2077 # self ** -infinity is infinity if self < 1, 0 if self > 1
2078 if other._isinfinity():
2079 if (other._sign == 0) == (self_adj < 0):
2080 return Decimal((result_sign, (0,), 0))
2081 else:
2082 return Infsign[result_sign]
2083
2084 # from here on, the result always goes through the call
2085 # to _fix at the end of this function.
2086 ans = None
2087
2088 # crude test to catch cases of extreme overflow/underflow. If
2089 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2090 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2091 # self**other >= 10**(Emax+1), so overflow occurs. The test
2092 # for underflow is similar.
2093 bound = self._log10_exp_bound() + other.adjusted()
2094 if (self_adj >= 0) == (other._sign == 0):
2095 # self > 1 and other +ve, or self < 1 and other -ve
2096 # possibility of overflow
2097 if bound >= len(str(context.Emax)):
2098 ans = Decimal((result_sign, (1,), context.Emax+1))
2099 else:
2100 # self > 1 and other -ve, or self < 1 and other +ve
2101 # possibility of underflow to 0
2102 Etiny = context.Etiny()
2103 if bound >= len(str(-Etiny)):
2104 ans = Decimal((result_sign, (1,), Etiny-1))
2105
2106 # try for an exact result with precision +1
2107 if ans is None:
2108 ans = self._power_exact(other, context.prec + 1)
2109 if ans is not None and result_sign == 1:
2110 ans = Decimal((1, ans._int, ans._exp))
2111
2112 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2113 if ans is None:
2114 p = context.prec
2115 x = _WorkRep(self)
2116 xc, xe = x.int, x.exp
2117 y = _WorkRep(other)
2118 yc, ye = y.int, y.exp
2119 if y.sign == 1:
2120 yc = -yc
2121
2122 # compute correctly rounded result: start with precision +3,
2123 # then increase precision until result is unambiguously roundable
2124 extra = 3
2125 while True:
2126 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2127 if coeff % (5*10**(len(str(coeff))-p-1)):
2128 break
2129 extra += 3
2130
2131 ans = Decimal((result_sign, list(map(int, str(coeff))), exp))
2132
2133 # the specification says that for non-integer other we need to
2134 # raise Inexact, even when the result is actually exact. In
2135 # the same way, we need to raise Underflow here if the result
2136 # is subnormal. (The call to _fix will take care of raising
2137 # Rounded and Subnormal, as usual.)
2138 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002139 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002140 # pad with zeros up to length context.prec+1 if necessary
2141 if len(ans._int) <= context.prec:
2142 expdiff = context.prec+1 - len(ans._int)
2143 ans = Decimal((ans._sign, ans._int+(0,)*expdiff, ans._exp-expdiff))
2144 if ans.adjusted() < context.Emin:
2145 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002146
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002147 # unlike exp, ln and log10, the power function respects the
2148 # rounding mode; no need to use ROUND_HALF_EVEN here
2149 ans = ans._fix(context)
2150 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002151
2152 def __rpow__(self, other, context=None):
2153 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002154 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002155 if other is NotImplemented:
2156 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002157 return other.__pow__(self, context=context)
2158
2159 def normalize(self, context=None):
2160 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002161
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002162 if context is None:
2163 context = getcontext()
2164
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002165 if self._is_special:
2166 ans = self._check_nans(context=context)
2167 if ans:
2168 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002169
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002170 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002171 if dup._isinfinity():
2172 return dup
2173
2174 if not dup:
2175 return Decimal( (dup._sign, (0,), 0) )
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002176 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002177 end = len(dup._int)
2178 exp = dup._exp
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002179 while dup._int[end-1] == 0 and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002180 exp += 1
2181 end -= 1
2182 return Decimal( (dup._sign, dup._int[:end], exp) )
2183
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002184 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002185 """Quantize self so its exponent is the same as that of exp.
2186
2187 Similar to self._rescale(exp._exp) but with error checking.
2188 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002189 exp = _convert_other(exp, raiseit=True)
2190
2191 if context is None:
2192 context = getcontext()
2193 if rounding is None:
2194 rounding = context.rounding
2195
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002196 if self._is_special or exp._is_special:
2197 ans = self._check_nans(exp, context)
2198 if ans:
2199 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002200
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002201 if exp._isinfinity() or self._isinfinity():
2202 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002203 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002204 return context._raise_error(InvalidOperation,
2205 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002206
2207 # if we're not watching exponents, do a simple rescale
2208 if not watchexp:
2209 ans = self._rescale(exp._exp, rounding)
2210 # raise Inexact and Rounded where appropriate
2211 if ans._exp > self._exp:
2212 context._raise_error(Rounded)
2213 if ans != self:
2214 context._raise_error(Inexact)
2215 return ans
2216
2217 # exp._exp should be between Etiny and Emax
2218 if not (context.Etiny() <= exp._exp <= context.Emax):
2219 return context._raise_error(InvalidOperation,
2220 'target exponent out of bounds in quantize')
2221
2222 if not self:
2223 ans = Decimal((self._sign, (0,), exp._exp))
2224 return ans._fix(context)
2225
2226 self_adjusted = self.adjusted()
2227 if self_adjusted > context.Emax:
2228 return context._raise_error(InvalidOperation,
2229 'exponent of quantize result too large for current context')
2230 if self_adjusted - exp._exp + 1 > context.prec:
2231 return context._raise_error(InvalidOperation,
2232 'quantize result has too many digits for current context')
2233
2234 ans = self._rescale(exp._exp, rounding)
2235 if ans.adjusted() > context.Emax:
2236 return context._raise_error(InvalidOperation,
2237 'exponent of quantize result too large for current context')
2238 if len(ans._int) > context.prec:
2239 return context._raise_error(InvalidOperation,
2240 'quantize result has too many digits for current context')
2241
2242 # raise appropriate flags
2243 if ans._exp > self._exp:
2244 context._raise_error(Rounded)
2245 if ans != self:
2246 context._raise_error(Inexact)
2247 if ans and ans.adjusted() < context.Emin:
2248 context._raise_error(Subnormal)
2249
2250 # call to fix takes care of any necessary folddown
2251 ans = ans._fix(context)
2252 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002253
2254 def same_quantum(self, other):
2255 """Test whether self and other have the same exponent.
2256
2257 same as self._exp == other._exp, except NaN == sNaN
2258 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002259 if self._is_special or other._is_special:
2260 if self._isnan() or other._isnan():
2261 return self._isnan() and other._isnan() and True
2262 if self._isinfinity() or other._isinfinity():
2263 return self._isinfinity() and other._isinfinity() and True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002264 return self._exp == other._exp
2265
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002266 def _rescale(self, exp, rounding):
2267 """Rescale self so that the exponent is exp, either by padding with zeros
2268 or by truncating digits, using the given rounding mode.
2269
2270 Specials are returned without change. This operation is
2271 quiet: it raises no flags, and uses no information from the
2272 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002273
2274 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002275 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002276 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002277 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002278 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002279 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002280 return Decimal((self._sign, (0,), exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002281
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002282 if self._exp >= exp:
2283 # pad answer with zeros if necessary
2284 return Decimal((self._sign, self._int + (0,)*(self._exp - exp), exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002285
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002286 # too many digits; round and lose data. If self.adjusted() <
2287 # exp-1, replace self by 10**(exp-1) before rounding
2288 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002289 if digits < 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002290 self = Decimal((self._sign, (1,), exp-1))
2291 digits = 0
2292 this_function = getattr(self, self._pick_rounding_function[rounding])
2293 return this_function(digits)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002294
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002295 def to_integral_exact(self, rounding=None, context=None):
2296 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002297
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002298 If no rounding mode is specified, take the rounding mode from
2299 the context. This method raises the Rounded and Inexact flags
2300 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002301
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002302 See also: to_integral_value, which does exactly the same as
2303 this method except that it doesn't raise Inexact or Rounded.
2304 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002305 if self._is_special:
2306 ans = self._check_nans(context=context)
2307 if ans:
2308 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002309 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002310 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002311 return Decimal(self)
2312 if not self:
2313 return Decimal((self._sign, (0,), 0))
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002314 if context is None:
2315 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002316 if rounding is None:
2317 rounding = context.rounding
2318 context._raise_error(Rounded)
2319 ans = self._rescale(0, rounding)
2320 if ans != self:
2321 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002322 return ans
2323
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002324 def to_integral_value(self, rounding=None, context=None):
2325 """Rounds to the nearest integer, without raising inexact, rounded."""
2326 if context is None:
2327 context = getcontext()
2328 if rounding is None:
2329 rounding = context.rounding
2330 if self._is_special:
2331 ans = self._check_nans(context=context)
2332 if ans:
2333 return ans
2334 return Decimal(self)
2335 if self._exp >= 0:
2336 return Decimal(self)
2337 else:
2338 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002339
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002340 # the method name changed, but we provide also the old one, for compatibility
2341 to_integral = to_integral_value
2342
2343 def sqrt(self, context=None):
2344 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002345 if self._is_special:
2346 ans = self._check_nans(context=context)
2347 if ans:
2348 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002349
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002350 if self._isinfinity() and self._sign == 0:
2351 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002352
2353 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002354 # exponent = self._exp // 2. sqrt(-0) = -0
2355 ans = Decimal((self._sign, (0,), self._exp // 2))
2356 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002357
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002358 if context is None:
2359 context = getcontext()
2360
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002361 if self._sign == 1:
2362 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2363
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002364 # At this point self represents a positive number. Let p be
2365 # the desired precision and express self in the form c*100**e
2366 # with c a positive real number and e an integer, c and e
2367 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2368 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2369 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2370 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2371 # the closest integer to sqrt(c) with the even integer chosen
2372 # in the case of a tie.
2373 #
2374 # To ensure correct rounding in all cases, we use the
2375 # following trick: we compute the square root to an extra
2376 # place (precision p+1 instead of precision p), rounding down.
2377 # Then, if the result is inexact and its last digit is 0 or 5,
2378 # we increase the last digit to 1 or 6 respectively; if it's
2379 # exact we leave the last digit alone. Now the final round to
2380 # p places (or fewer in the case of underflow) will round
2381 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002382
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002383 # use an extra digit of precision
2384 prec = context.prec+1
2385
2386 # write argument in the form c*100**e where e = self._exp//2
2387 # is the 'ideal' exponent, to be used if the square root is
2388 # exactly representable. l is the number of 'digits' of c in
2389 # base 100, so that 100**(l-1) <= c < 100**l.
2390 op = _WorkRep(self)
2391 e = op.exp >> 1
2392 if op.exp & 1:
2393 c = op.int * 10
2394 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002395 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002396 c = op.int
2397 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002398
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002399 # rescale so that c has exactly prec base 100 'digits'
2400 shift = prec-l
2401 if shift >= 0:
2402 c *= 100**shift
2403 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002404 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002405 c, remainder = divmod(c, 100**-shift)
2406 exact = not remainder
2407 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002408
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002409 # find n = floor(sqrt(c)) using Newton's method
2410 n = 10**prec
2411 while True:
2412 q = c//n
2413 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002414 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002415 else:
2416 n = n + q >> 1
2417 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002418
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002419 if exact:
2420 # result is exact; rescale to use ideal exponent e
2421 if shift >= 0:
2422 # assert n % 10**shift == 0
2423 n //= 10**shift
2424 else:
2425 n *= 10**-shift
2426 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002427 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002428 # result is not exact; fix last digit as described above
2429 if n % 5 == 0:
2430 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002431
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002432 ans = Decimal((0, list(map(int, str(n))), e))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002433
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002434 # round, and fit to current context
2435 context = context._shallow_copy()
2436 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002437 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002438 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002439
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002440 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002441
2442 def max(self, other, context=None):
2443 """Returns the larger value.
2444
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002445 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002446 NaN (and signals if one is sNaN). Also rounds.
2447 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002448 other = _convert_other(other, raiseit=True)
2449
2450 if context is None:
2451 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002452
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002453 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002454 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002455 # number is always returned
2456 sn = self._isnan()
2457 on = other._isnan()
2458 if sn or on:
2459 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002460 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002461 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002462 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002463 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002464
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002465 c = self.__cmp__(other)
2466 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002467 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002468 # then an ordering is applied:
2469 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002470 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002471 # positive sign and min returns the operand with the negative sign
2472 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002473 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002474 # the result. This is exactly the ordering used in compare_total.
2475 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002476
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002477 if c == -1:
2478 ans = other
2479 else:
2480 ans = self
2481
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002482 if context._rounding_decision == ALWAYS_ROUND:
2483 return ans._fix(context)
2484 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002485
2486 def min(self, other, context=None):
2487 """Returns the smaller value.
2488
Guido van Rossumd8faa362007-04-27 19:54:29 +00002489 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002490 NaN (and signals if one is sNaN). Also rounds.
2491 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002492 other = _convert_other(other, raiseit=True)
2493
2494 if context is None:
2495 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002496
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002497 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002498 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002499 # number is always returned
2500 sn = self._isnan()
2501 on = other._isnan()
2502 if sn or on:
2503 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002504 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002505 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002506 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002507 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002508
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002509 c = self.__cmp__(other)
2510 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002511 c = self.compare_total(other)
2512
2513 if c == -1:
2514 ans = self
2515 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002516 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002517
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002518 if context._rounding_decision == ALWAYS_ROUND:
2519 return ans._fix(context)
2520 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002521
2522 def _isinteger(self):
2523 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002524 if self._is_special:
2525 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002526 if self._exp >= 0:
2527 return True
2528 rest = self._int[self._exp:]
2529 return rest == (0,)*len(rest)
2530
2531 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002532 """Returns True if self is even. Assumes self is an integer."""
2533 if not self or self._exp > 0:
2534 return True
Raymond Hettinger61992ef2004-08-06 23:42:16 +00002535 return self._int[-1+self._exp] & 1 == 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002536
2537 def adjusted(self):
2538 """Return the adjusted exponent of self"""
2539 try:
2540 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002541 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002542 except TypeError:
2543 return 0
2544
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002545 def canonical(self, context=None):
2546 """Returns the same Decimal object.
2547
2548 As we do not have different encodings for the same number, the
2549 received object already is in its canonical form.
2550 """
2551 return self
2552
2553 def compare_signal(self, other, context=None):
2554 """Compares self to the other operand numerically.
2555
2556 It's pretty much like compare(), but all NaNs signal, with signaling
2557 NaNs taking precedence over quiet NaNs.
2558 """
2559 if context is None:
2560 context = getcontext()
2561
2562 self_is_nan = self._isnan()
2563 other_is_nan = other._isnan()
2564 if self_is_nan == 2:
2565 return context._raise_error(InvalidOperation, 'sNaN',
2566 1, self)
2567 if other_is_nan == 2:
2568 return context._raise_error(InvalidOperation, 'sNaN',
2569 1, other)
2570 if self_is_nan:
2571 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2572 1, self)
2573 if other_is_nan:
2574 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2575 1, other)
2576 return self.compare(other, context=context)
2577
2578 def compare_total(self, other):
2579 """Compares self to other using the abstract representations.
2580
2581 This is not like the standard compare, which use their numerical
2582 value. Note that a total ordering is defined for all possible abstract
2583 representations.
2584 """
2585 # if one is negative and the other is positive, it's easy
2586 if self._sign and not other._sign:
2587 return Dec_n1
2588 if not self._sign and other._sign:
2589 return Dec_p1
2590 sign = self._sign
2591
2592 # let's handle both NaN types
2593 self_nan = self._isnan()
2594 other_nan = other._isnan()
2595 if self_nan or other_nan:
2596 if self_nan == other_nan:
2597 if self._int < other._int:
2598 if sign:
2599 return Dec_p1
2600 else:
2601 return Dec_n1
2602 if self._int > other._int:
2603 if sign:
2604 return Dec_n1
2605 else:
2606 return Dec_p1
2607 return Dec_0
2608
2609 if sign:
2610 if self_nan == 1:
2611 return Dec_n1
2612 if other_nan == 1:
2613 return Dec_p1
2614 if self_nan == 2:
2615 return Dec_n1
2616 if other_nan == 2:
2617 return Dec_p1
2618 else:
2619 if self_nan == 1:
2620 return Dec_p1
2621 if other_nan == 1:
2622 return Dec_n1
2623 if self_nan == 2:
2624 return Dec_p1
2625 if other_nan == 2:
2626 return Dec_n1
2627
2628 if self < other:
2629 return Dec_n1
2630 if self > other:
2631 return Dec_p1
2632
2633 if self._exp < other._exp:
2634 if sign:
2635 return Dec_p1
2636 else:
2637 return Dec_n1
2638 if self._exp > other._exp:
2639 if sign:
2640 return Dec_n1
2641 else:
2642 return Dec_p1
2643 return Dec_0
2644
2645
2646 def compare_total_mag(self, other):
2647 """Compares self to other using abstract repr., ignoring sign.
2648
2649 Like compare_total, but with operand's sign ignored and assumed to be 0.
2650 """
2651 s = self.copy_abs()
2652 o = other.copy_abs()
2653 return s.compare_total(o)
2654
2655 def copy_abs(self):
2656 """Returns a copy with the sign set to 0. """
2657 return Decimal((0, self._int, self._exp))
2658
2659 def copy_negate(self):
2660 """Returns a copy with the sign inverted."""
2661 if self._sign:
2662 return Decimal((0, self._int, self._exp))
2663 else:
2664 return Decimal((1, self._int, self._exp))
2665
2666 def copy_sign(self, other):
2667 """Returns self with the sign of other."""
2668 return Decimal((other._sign, self._int, self._exp))
2669
2670 def exp(self, context=None):
2671 """Returns e ** self."""
2672
2673 if context is None:
2674 context = getcontext()
2675
2676 # exp(NaN) = NaN
2677 ans = self._check_nans(context=context)
2678 if ans:
2679 return ans
2680
2681 # exp(-Infinity) = 0
2682 if self._isinfinity() == -1:
2683 return Dec_0
2684
2685 # exp(0) = 1
2686 if not self:
2687 return Dec_p1
2688
2689 # exp(Infinity) = Infinity
2690 if self._isinfinity() == 1:
2691 return Decimal(self)
2692
2693 # the result is now guaranteed to be inexact (the true
2694 # mathematical result is transcendental). There's no need to
2695 # raise Rounded and Inexact here---they'll always be raised as
2696 # a result of the call to _fix.
2697 p = context.prec
2698 adj = self.adjusted()
2699
2700 # we only need to do any computation for quite a small range
2701 # of adjusted exponents---for example, -29 <= adj <= 10 for
2702 # the default context. For smaller exponent the result is
2703 # indistinguishable from 1 at the given precision, while for
2704 # larger exponent the result either overflows or underflows.
2705 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2706 # overflow
2707 ans = Decimal((0, (1,), context.Emax+1))
2708 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2709 # underflow to 0
2710 ans = Decimal((0, (1,), context.Etiny()-1))
2711 elif self._sign == 0 and adj < -p:
2712 # p+1 digits; final round will raise correct flags
2713 ans = Decimal((0, (1,) + (0,)*(p-1) + (1,), -p))
2714 elif self._sign == 1 and adj < -p-1:
2715 # p+1 digits; final round will raise correct flags
2716 ans = Decimal((0, (9,)*(p+1), -p-1))
2717 # general case
2718 else:
2719 op = _WorkRep(self)
2720 c, e = op.int, op.exp
2721 if op.sign == 1:
2722 c = -c
2723
2724 # compute correctly rounded result: increase precision by
2725 # 3 digits at a time until we get an unambiguously
2726 # roundable result
2727 extra = 3
2728 while True:
2729 coeff, exp = _dexp(c, e, p+extra)
2730 if coeff % (5*10**(len(str(coeff))-p-1)):
2731 break
2732 extra += 3
2733
2734 ans = Decimal((0, list(map(int, str(coeff))), exp))
2735
2736 # at this stage, ans should round correctly with *any*
2737 # rounding mode, not just with ROUND_HALF_EVEN
2738 context = context._shallow_copy()
2739 rounding = context._set_rounding(ROUND_HALF_EVEN)
2740 ans = ans._fix(context)
2741 context.rounding = rounding
2742
2743 return ans
2744
2745 def is_canonical(self):
2746 """Returns 1 if self is canonical; otherwise returns 0."""
2747 return Dec_p1
2748
2749 def is_finite(self):
2750 """Returns 1 if self is finite, otherwise returns 0.
2751
2752 For it to be finite, it must be neither infinite nor a NaN.
2753 """
2754 if self._is_special:
2755 return Dec_0
2756 else:
2757 return Dec_p1
2758
2759 def is_infinite(self):
2760 """Returns 1 if self is an Infinite, otherwise returns 0."""
2761 if self._isinfinity():
2762 return Dec_p1
2763 else:
2764 return Dec_0
2765
2766 def is_nan(self):
2767 """Returns 1 if self is qNaN or sNaN, otherwise returns 0."""
2768 if self._isnan():
2769 return Dec_p1
2770 else:
2771 return Dec_0
2772
2773 def is_normal(self, context=None):
2774 """Returns 1 if self is a normal number, otherwise returns 0."""
2775 if self._is_special:
2776 return Dec_0
2777 if not self:
2778 return Dec_0
2779 if context is None:
2780 context = getcontext()
2781 if context.Emin <= self.adjusted() <= context.Emax:
2782 return Dec_p1
2783 else:
2784 return Dec_0
2785
2786 def is_qnan(self):
2787 """Returns 1 if self is a quiet NaN, otherwise returns 0."""
2788 if self._isnan() == 1:
2789 return Dec_p1
2790 else:
2791 return Dec_0
2792
2793 def is_signed(self):
2794 """Returns 1 if self is negative, otherwise returns 0."""
2795 return Decimal(self._sign)
2796
2797 def is_snan(self):
2798 """Returns 1 if self is a signaling NaN, otherwise returns 0."""
2799 if self._isnan() == 2:
2800 return Dec_p1
2801 else:
2802 return Dec_0
2803
2804 def is_subnormal(self, context=None):
2805 """Returns 1 if self is subnormal, otherwise returns 0."""
2806 if self._is_special:
2807 return Dec_0
2808 if not self:
2809 return Dec_0
2810 if context is None:
2811 context = getcontext()
2812
2813 r = self._exp + len(self._int)
2814 if r <= context.Emin:
2815 return Dec_p1
2816 return Dec_0
2817
2818 def is_zero(self):
2819 """Returns 1 if self is a zero, otherwise returns 0."""
2820 if self:
2821 return Dec_0
2822 else:
2823 return Dec_p1
2824
2825 def _ln_exp_bound(self):
2826 """Compute a lower bound for the adjusted exponent of self.ln().
2827 In other words, compute r such that self.ln() >= 10**r. Assumes
2828 that self is finite and positive and that self != 1.
2829 """
2830
2831 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2832 adj = self._exp + len(self._int) - 1
2833 if adj >= 1:
2834 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2835 return len(str(adj*23//10)) - 1
2836 if adj <= -2:
2837 # argument <= 0.1
2838 return len(str((-1-adj)*23//10)) - 1
2839 op = _WorkRep(self)
2840 c, e = op.int, op.exp
2841 if adj == 0:
2842 # 1 < self < 10
2843 num = str(c-10**-e)
2844 den = str(c)
2845 return len(num) - len(den) - (num < den)
2846 # adj == -1, 0.1 <= self < 1
2847 return e + len(str(10**-e - c)) - 1
2848
2849
2850 def ln(self, context=None):
2851 """Returns the natural (base e) logarithm of self."""
2852
2853 if context is None:
2854 context = getcontext()
2855
2856 # ln(NaN) = NaN
2857 ans = self._check_nans(context=context)
2858 if ans:
2859 return ans
2860
2861 # ln(0.0) == -Infinity
2862 if not self:
2863 return negInf
2864
2865 # ln(Infinity) = Infinity
2866 if self._isinfinity() == 1:
2867 return Inf
2868
2869 # ln(1.0) == 0.0
2870 if self == Dec_p1:
2871 return Dec_0
2872
2873 # ln(negative) raises InvalidOperation
2874 if self._sign == 1:
2875 return context._raise_error(InvalidOperation,
2876 'ln of a negative value')
2877
2878 # result is irrational, so necessarily inexact
2879 op = _WorkRep(self)
2880 c, e = op.int, op.exp
2881 p = context.prec
2882
2883 # correctly rounded result: repeatedly increase precision by 3
2884 # until we get an unambiguously roundable result
2885 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2886 while True:
2887 coeff = _dlog(c, e, places)
2888 # assert len(str(abs(coeff)))-p >= 1
2889 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2890 break
2891 places += 3
2892 ans = Decimal((int(coeff<0), list(map(int, str(abs(coeff)))), -places))
2893
2894 context = context._shallow_copy()
2895 rounding = context._set_rounding(ROUND_HALF_EVEN)
2896 ans = ans._fix(context)
2897 context.rounding = rounding
2898 return ans
2899
2900 def _log10_exp_bound(self):
2901 """Compute a lower bound for the adjusted exponent of self.log10().
2902 In other words, find r such that self.log10() >= 10**r.
2903 Assumes that self is finite and positive and that self != 1.
2904 """
2905
2906 # For x >= 10 or x < 0.1 we only need a bound on the integer
2907 # part of log10(self), and this comes directly from the
2908 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2909 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2910 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2911
2912 adj = self._exp + len(self._int) - 1
2913 if adj >= 1:
2914 # self >= 10
2915 return len(str(adj))-1
2916 if adj <= -2:
2917 # self < 0.1
2918 return len(str(-1-adj))-1
2919 op = _WorkRep(self)
2920 c, e = op.int, op.exp
2921 if adj == 0:
2922 # 1 < self < 10
2923 num = str(c-10**-e)
2924 den = str(231*c)
2925 return len(num) - len(den) - (num < den) + 2
2926 # adj == -1, 0.1 <= self < 1
2927 num = str(10**-e-c)
2928 return len(num) + e - (num < "231") - 1
2929
2930 def log10(self, context=None):
2931 """Returns the base 10 logarithm of self."""
2932
2933 if context is None:
2934 context = getcontext()
2935
2936 # log10(NaN) = NaN
2937 ans = self._check_nans(context=context)
2938 if ans:
2939 return ans
2940
2941 # log10(0.0) == -Infinity
2942 if not self:
2943 return negInf
2944
2945 # log10(Infinity) = Infinity
2946 if self._isinfinity() == 1:
2947 return Inf
2948
2949 # log10(negative or -Infinity) raises InvalidOperation
2950 if self._sign == 1:
2951 return context._raise_error(InvalidOperation,
2952 'log10 of a negative value')
2953
2954 # log10(10**n) = n
2955 if self._int[0] == 1 and self._int[1:] == (0,)*(len(self._int) - 1):
2956 # answer may need rounding
2957 ans = Decimal(self._exp + len(self._int) - 1)
2958 else:
2959 # result is irrational, so necessarily inexact
2960 op = _WorkRep(self)
2961 c, e = op.int, op.exp
2962 p = context.prec
2963
2964 # correctly rounded result: repeatedly increase precision
2965 # until result is unambiguously roundable
2966 places = p-self._log10_exp_bound()+2
2967 while True:
2968 coeff = _dlog10(c, e, places)
2969 # assert len(str(abs(coeff)))-p >= 1
2970 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2971 break
2972 places += 3
2973 ans = Decimal((int(coeff<0), list(map(int, str(abs(coeff)))),
2974 -places))
2975
2976 context = context._shallow_copy()
2977 rounding = context._set_rounding(ROUND_HALF_EVEN)
2978 ans = ans._fix(context)
2979 context.rounding = rounding
2980 return ans
2981
2982 def logb(self, context=None):
2983 """ Returns the exponent of the magnitude of self's MSD.
2984
2985 The result is the integer which is the exponent of the magnitude
2986 of the most significant digit of self (as though it were truncated
2987 to a single digit while maintaining the value of that digit and
2988 without limiting the resulting exponent).
2989 """
2990 # logb(NaN) = NaN
2991 ans = self._check_nans(context=context)
2992 if ans:
2993 return ans
2994
2995 if context is None:
2996 context = getcontext()
2997
2998 # logb(+/-Inf) = +Inf
2999 if self._isinfinity():
3000 return Inf
3001
3002 # logb(0) = -Inf, DivisionByZero
3003 if not self:
3004 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3005
3006 # otherwise, simply return the adjusted exponent of self, as a
3007 # Decimal. Note that no attempt is made to fit the result
3008 # into the current context.
3009 return Decimal(self.adjusted())
3010
3011 def _islogical(self):
3012 """Return True if self is a logical operand.
3013
3014 For being logical, it must be a finite numbers with a sign of 0,
3015 an exponent of 0, and a coefficient whose digits must all be
3016 either 0 or 1.
3017 """
3018 if self._sign != 0 or self._exp != 0:
3019 return False
3020 for dig in self._int:
3021 if dig not in (0, 1):
3022 return False
3023 return True
3024
3025 def _fill_logical(self, context, opa, opb):
3026 dif = context.prec - len(opa)
3027 if dif > 0:
3028 opa = (0,)*dif + opa
3029 elif dif < 0:
3030 opa = opa[-context.prec:]
3031 dif = context.prec - len(opb)
3032 if dif > 0:
3033 opb = (0,)*dif + opb
3034 elif dif < 0:
3035 opb = opb[-context.prec:]
3036 return opa, opb
3037
3038 def logical_and(self, other, context=None):
3039 """Applies an 'and' operation between self and other's digits."""
3040 if context is None:
3041 context = getcontext()
3042 if not self._islogical() or not other._islogical():
3043 return context._raise_error(InvalidOperation)
3044
3045 # fill to context.prec
3046 (opa, opb) = self._fill_logical(context, self._int, other._int)
3047
3048 # make the operation, and clean starting zeroes
3049 result = [a&b for a,b in zip(opa,opb)]
3050 for i,d in enumerate(result):
3051 if d == 1:
3052 break
3053 result = tuple(result[i:])
3054
3055 # if empty, we must have at least a zero
3056 if not result:
3057 result = (0,)
3058 return Decimal((0, result, 0))
3059
3060 def logical_invert(self, context=None):
3061 """Invert all its digits."""
3062 if context is None:
3063 context = getcontext()
3064 return self.logical_xor(Decimal((0,(1,)*context.prec,0)), context)
3065
3066 def logical_or(self, other, context=None):
3067 """Applies an 'or' operation between self and other's digits."""
3068 if context is None:
3069 context = getcontext()
3070 if not self._islogical() or not other._islogical():
3071 return context._raise_error(InvalidOperation)
3072
3073 # fill to context.prec
3074 (opa, opb) = self._fill_logical(context, self._int, other._int)
3075
3076 # make the operation, and clean starting zeroes
3077 result = [a|b for a,b in zip(opa,opb)]
3078 for i,d in enumerate(result):
3079 if d == 1:
3080 break
3081 result = tuple(result[i:])
3082
3083 # if empty, we must have at least a zero
3084 if not result:
3085 result = (0,)
3086 return Decimal((0, result, 0))
3087
3088 def logical_xor(self, other, context=None):
3089 """Applies an 'xor' operation between self and other's digits."""
3090 if context is None:
3091 context = getcontext()
3092 if not self._islogical() or not other._islogical():
3093 return context._raise_error(InvalidOperation)
3094
3095 # fill to context.prec
3096 (opa, opb) = self._fill_logical(context, self._int, other._int)
3097
3098 # make the operation, and clean starting zeroes
3099 result = [a^b for a,b in zip(opa,opb)]
3100 for i,d in enumerate(result):
3101 if d == 1:
3102 break
3103 result = tuple(result[i:])
3104
3105 # if empty, we must have at least a zero
3106 if not result:
3107 result = (0,)
3108 return Decimal((0, result, 0))
3109
3110 def max_mag(self, other, context=None):
3111 """Compares the values numerically with their sign ignored."""
3112 other = _convert_other(other, raiseit=True)
3113
3114 if context is None:
3115 context = getcontext()
3116
3117 if self._is_special or other._is_special:
3118 # If one operand is a quiet NaN and the other is number, then the
3119 # number is always returned
3120 sn = self._isnan()
3121 on = other._isnan()
3122 if sn or on:
3123 if on == 1 and sn != 2:
3124 return self._fix_nan(context)
3125 if sn == 1 and on != 2:
3126 return other._fix_nan(context)
3127 return self._check_nans(other, context)
3128
3129 c = self.copy_abs().__cmp__(other.copy_abs())
3130 if c == 0:
3131 c = self.compare_total(other)
3132
3133 if c == -1:
3134 ans = other
3135 else:
3136 ans = self
3137
3138 if context._rounding_decision == ALWAYS_ROUND:
3139 return ans._fix(context)
3140 return ans
3141
3142 def min_mag(self, other, context=None):
3143 """Compares the values numerically with their sign ignored."""
3144 other = _convert_other(other, raiseit=True)
3145
3146 if context is None:
3147 context = getcontext()
3148
3149 if self._is_special or other._is_special:
3150 # If one operand is a quiet NaN and the other is number, then the
3151 # number is always returned
3152 sn = self._isnan()
3153 on = other._isnan()
3154 if sn or on:
3155 if on == 1 and sn != 2:
3156 return self._fix_nan(context)
3157 if sn == 1 and on != 2:
3158 return other._fix_nan(context)
3159 return self._check_nans(other, context)
3160
3161 c = self.copy_abs().__cmp__(other.copy_abs())
3162 if c == 0:
3163 c = self.compare_total(other)
3164
3165 if c == -1:
3166 ans = self
3167 else:
3168 ans = other
3169
3170 if context._rounding_decision == ALWAYS_ROUND:
3171 return ans._fix(context)
3172 return ans
3173
3174 def next_minus(self, context=None):
3175 """Returns the largest representable number smaller than itself."""
3176 if context is None:
3177 context = getcontext()
3178
3179 ans = self._check_nans(context=context)
3180 if ans:
3181 return ans
3182
3183 if self._isinfinity() == -1:
3184 return negInf
3185 if self._isinfinity() == 1:
3186 return Decimal((0, (9,)*context.prec, context.Etop()))
3187
3188 context = context.copy()
3189 context._set_rounding(ROUND_FLOOR)
3190 context._ignore_all_flags()
3191 new_self = self._fix(context)
3192 if new_self != self:
3193 return new_self
3194 return self.__sub__(Decimal((0, (1,), context.Etiny()-1)), context)
3195
3196 def next_plus(self, context=None):
3197 """Returns the smallest representable number larger than itself."""
3198 if context is None:
3199 context = getcontext()
3200
3201 ans = self._check_nans(context=context)
3202 if ans:
3203 return ans
3204
3205 if self._isinfinity() == 1:
3206 return Inf
3207 if self._isinfinity() == -1:
3208 return Decimal((1, (9,)*context.prec, context.Etop()))
3209
3210 context = context.copy()
3211 context._set_rounding(ROUND_CEILING)
3212 context._ignore_all_flags()
3213 new_self = self._fix(context)
3214 if new_self != self:
3215 return new_self
3216 return self.__add__(Decimal((0, (1,), context.Etiny()-1)), context)
3217
3218 def next_toward(self, other, context=None):
3219 """Returns the number closest to self, in the direction towards other.
3220
3221 The result is the closest representable number to self
3222 (excluding self) that is in the direction towards other,
3223 unless both have the same value. If the two operands are
3224 numerically equal, then the result is a copy of self with the
3225 sign set to be the same as the sign of other.
3226 """
3227 other = _convert_other(other, raiseit=True)
3228
3229 if context is None:
3230 context = getcontext()
3231
3232 ans = self._check_nans(other, context)
3233 if ans:
3234 return ans
3235
3236 comparison = self.__cmp__(other)
3237 if comparison == 0:
3238 return Decimal((other._sign, self._int, self._exp))
3239
3240 if comparison == -1:
3241 ans = self.next_plus(context)
3242 else: # comparison == 1
3243 ans = self.next_minus(context)
3244
3245 # decide which flags to raise using value of ans
3246 if ans._isinfinity():
3247 context._raise_error(Overflow,
3248 'Infinite result from next_toward',
3249 ans._sign)
3250 context._raise_error(Rounded)
3251 context._raise_error(Inexact)
3252 elif ans.adjusted() < context.Emin:
3253 context._raise_error(Underflow)
3254 context._raise_error(Subnormal)
3255 context._raise_error(Rounded)
3256 context._raise_error(Inexact)
3257 # if precision == 1 then we don't raise Clamped for a
3258 # result 0E-Etiny.
3259 if not ans:
3260 context._raise_error(Clamped)
3261
3262 return ans
3263
3264 def number_class(self, context=None):
3265 """Returns an indication of the class of self.
3266
3267 The class is one of the following strings:
3268 -sNaN
3269 -NaN
3270 -Infinity
3271 -Normal
3272 -Subnormal
3273 -Zero
3274 +Zero
3275 +Subnormal
3276 +Normal
3277 +Infinity
3278 """
3279 if self.is_snan():
3280 return "sNaN"
3281 if self.is_qnan():
3282 return "NaN"
3283 inf = self._isinfinity()
3284 if inf == 1:
3285 return "+Infinity"
3286 if inf == -1:
3287 return "-Infinity"
3288 if self.is_zero():
3289 if self._sign:
3290 return "-Zero"
3291 else:
3292 return "+Zero"
3293 if context is None:
3294 context = getcontext()
3295 if self.is_subnormal(context=context):
3296 if self._sign:
3297 return "-Subnormal"
3298 else:
3299 return "+Subnormal"
3300 # just a normal, regular, boring number, :)
3301 if self._sign:
3302 return "-Normal"
3303 else:
3304 return "+Normal"
3305
3306 def radix(self):
3307 """Just returns 10, as this is Decimal, :)"""
3308 return Decimal(10)
3309
3310 def rotate(self, other, context=None):
3311 """Returns a rotated copy of self, value-of-other times."""
3312 if context is None:
3313 context = getcontext()
3314
3315 ans = self._check_nans(other, context)
3316 if ans:
3317 return ans
3318
3319 if other._exp != 0:
3320 return context._raise_error(InvalidOperation)
3321 if not (-context.prec <= int(other) <= context.prec):
3322 return context._raise_error(InvalidOperation)
3323
3324 if self._isinfinity():
3325 return Decimal(self)
3326
3327 # get values, pad if necessary
3328 torot = int(other)
3329 rotdig = self._int
3330 topad = context.prec - len(rotdig)
3331 if topad:
3332 rotdig = ((0,)*topad) + rotdig
3333
3334 # let's rotate!
3335 rotated = rotdig[torot:] + rotdig[:torot]
3336
3337 # clean starting zeroes
3338 for i,d in enumerate(rotated):
3339 if d != 0:
3340 break
3341 rotated = rotated[i:]
3342
3343 return Decimal((self._sign, rotated, self._exp))
3344
3345
3346 def scaleb (self, other, context=None):
3347 """Returns self operand after adding the second value to its exp."""
3348 if context is None:
3349 context = getcontext()
3350
3351 ans = self._check_nans(other, context)
3352 if ans:
3353 return ans
3354
3355 if other._exp != 0:
3356 return context._raise_error(InvalidOperation)
3357 liminf = -2 * (context.Emax + context.prec)
3358 limsup = 2 * (context.Emax + context.prec)
3359 if not (liminf <= int(other) <= limsup):
3360 return context._raise_error(InvalidOperation)
3361
3362 if self._isinfinity():
3363 return Decimal(self)
3364
3365 d = Decimal((self._sign, self._int, self._exp + int(other)))
3366 d = d._fix(context)
3367 return d
3368
3369 def shift(self, other, context=None):
3370 """Returns a shifted copy of self, value-of-other times."""
3371 if context is None:
3372 context = getcontext()
3373
3374 ans = self._check_nans(other, context)
3375 if ans:
3376 return ans
3377
3378 if other._exp != 0:
3379 return context._raise_error(InvalidOperation)
3380 if not (-context.prec <= int(other) <= context.prec):
3381 return context._raise_error(InvalidOperation)
3382
3383 if self._isinfinity():
3384 return Decimal(self)
3385
3386 # get values, pad if necessary
3387 torot = int(other)
3388 if not torot:
3389 return Decimal(self)
3390 rotdig = self._int
3391 topad = context.prec - len(rotdig)
3392 if topad:
3393 rotdig = ((0,)*topad) + rotdig
3394
3395 # let's shift!
3396 if torot < 0:
3397 rotated = rotdig[:torot]
3398 else:
3399 rotated = (rotdig + ((0,) * torot))
3400 rotated = rotated[-context.prec:]
3401
3402 # clean starting zeroes
3403 if rotated:
3404 for i,d in enumerate(rotated):
3405 if d != 0:
3406 break
3407 rotated = rotated[i:]
3408 else:
3409 rotated = (0,)
3410
3411 return Decimal((self._sign, rotated, self._exp))
3412
3413
Guido van Rossumd8faa362007-04-27 19:54:29 +00003414 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003415 def __reduce__(self):
3416 return (self.__class__, (str(self),))
3417
3418 def __copy__(self):
3419 if type(self) == Decimal:
3420 return self # I'm immutable; therefore I am my own clone
3421 return self.__class__(str(self))
3422
3423 def __deepcopy__(self, memo):
3424 if type(self) == Decimal:
3425 return self # My components are also immutable
3426 return self.__class__(str(self))
3427
Guido van Rossumd8faa362007-04-27 19:54:29 +00003428##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003429
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003430
3431# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003432rounding_functions = [name for name in Decimal.__dict__.keys()
3433 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003434for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003435 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003436 globalname = name[1:].upper()
3437 val = globals()[globalname]
3438 Decimal._pick_rounding_function[val] = name
3439
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003440del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003441
Thomas Wouters89f507f2006-12-13 04:49:30 +00003442class _ContextManager(object):
3443 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003444
Thomas Wouters89f507f2006-12-13 04:49:30 +00003445 Sets a copy of the supplied context in __enter__() and restores
3446 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003447 """
3448 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003449 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003450 def __enter__(self):
3451 self.saved_context = getcontext()
3452 setcontext(self.new_context)
3453 return self.new_context
3454 def __exit__(self, t, v, tb):
3455 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003456
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003457class Context(object):
3458 """Contains the context for a Decimal instance.
3459
3460 Contains:
3461 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003462 rounding - rounding type (how you round)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003463 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
Raymond Hettingerbf440692004-07-10 14:14:37 +00003464 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003465 raised when it is caused. Otherwise, a value is
3466 substituted in.
3467 flags - When an exception is caused, flags[exception] is incremented.
3468 (Whether or not the trap_enabler is set)
3469 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003470 Emin - Minimum exponent
3471 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003472 capitals - If 1, 1*10^1 is printed as 1E+1.
3473 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003474 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003475 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003476
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003477 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003478 traps=None, flags=None,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003479 _rounding_decision=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003480 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003481 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003482 _ignored_flags=None):
3483 if flags is None:
3484 flags = []
3485 if _ignored_flags is None:
3486 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003487 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003488 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003489 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003490 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003491 for name, val in locals().items():
3492 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003493 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003494 else:
3495 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003496 del self.self
3497
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003498 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003499 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003500 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003501 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3502 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3503 % vars(self))
3504 names = [f.__name__ for f, v in self.flags.items() if v]
3505 s.append('flags=[' + ', '.join(names) + ']')
3506 names = [t.__name__ for t, v in self.traps.items() if v]
3507 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003508 return ', '.join(s) + ')'
3509
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003510 def clear_flags(self):
3511 """Reset all flags to zero"""
3512 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003513 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003514
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003515 def _shallow_copy(self):
3516 """Returns a shallow copy from self."""
Raymond Hettingerbf440692004-07-10 14:14:37 +00003517 nc = Context(self.prec, self.rounding, self.traps, self.flags,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003518 self._rounding_decision, self.Emin, self.Emax,
3519 self.capitals, self._clamp, self._ignored_flags)
3520 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003521
3522 def copy(self):
3523 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003524 nc = Context(self.prec, self.rounding, self.traps.copy(),
3525 self.flags.copy(), self._rounding_decision, self.Emin,
3526 self.Emax, self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003527 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003528 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003529
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003530 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003531 """Handles an error
3532
3533 If the flag is in _ignored_flags, returns the default response.
3534 Otherwise, it increments the flag, then, if the corresponding
3535 trap_enabler is set, it reaises the exception. Otherwise, it returns
3536 the default value after incrementing the flag.
3537 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003538 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003539 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003540 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003541 return error().handle(self, *args)
3542
3543 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003544 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003545 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003546 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003547
3548 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003549 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003550 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003551
3552 def _ignore_all_flags(self):
3553 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003554 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003555
3556 def _ignore_flags(self, *flags):
3557 """Ignore the flags, if they are raised"""
3558 # Do not mutate-- This way, copies of a context leave the original
3559 # alone.
3560 self._ignored_flags = (self._ignored_flags + list(flags))
3561 return list(flags)
3562
3563 def _regard_flags(self, *flags):
3564 """Stop ignoring the flags, if they are raised"""
3565 if flags and isinstance(flags[0], (tuple,list)):
3566 flags = flags[0]
3567 for flag in flags:
3568 self._ignored_flags.remove(flag)
3569
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003570 def __hash__(self):
3571 """A Context cannot be hashed."""
3572 # We inherit object.__hash__, so we must deny this explicitly
Guido van Rossumd8faa362007-04-27 19:54:29 +00003573 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003574
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003575 def Etiny(self):
3576 """Returns Etiny (= Emin - prec + 1)"""
3577 return int(self.Emin - self.prec + 1)
3578
3579 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003580 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003581 return int(self.Emax - self.prec + 1)
3582
3583 def _set_rounding_decision(self, type):
3584 """Sets the rounding decision.
3585
3586 Sets the rounding decision, and returns the current (previous)
3587 rounding decision. Often used like:
3588
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003589 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003590 # That so you don't change the calling context
3591 # if an error occurs in the middle (say DivisionImpossible is raised).
3592
3593 rounding = context._set_rounding_decision(NEVER_ROUND)
3594 instance = instance / Decimal(2)
3595 context._set_rounding_decision(rounding)
3596
3597 This will make it not round for that operation.
3598 """
3599
3600 rounding = self._rounding_decision
3601 self._rounding_decision = type
3602 return rounding
3603
3604 def _set_rounding(self, type):
3605 """Sets the rounding type.
3606
3607 Sets the rounding type, and returns the current (previous)
3608 rounding type. Often used like:
3609
3610 context = context.copy()
3611 # so you don't change the calling context
3612 # if an error occurs in the middle.
3613 rounding = context._set_rounding(ROUND_UP)
3614 val = self.__sub__(other, context=context)
3615 context._set_rounding(rounding)
3616
3617 This will make it round up for that operation.
3618 """
3619 rounding = self.rounding
3620 self.rounding= type
3621 return rounding
3622
Raymond Hettingerfed52962004-07-14 15:41:57 +00003623 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003624 """Creates a new Decimal instance but using self as context."""
3625 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003626 if d._isnan() and len(d._int) > self.prec - self._clamp:
3627 return self._raise_error(ConversionSyntax,
3628 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003629 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003630
Guido van Rossumd8faa362007-04-27 19:54:29 +00003631 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003632 def abs(self, a):
3633 """Returns the absolute value of the operand.
3634
3635 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003636 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003637 the plus operation on the operand.
3638
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003639 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003640 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003641 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003642 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003643 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003644 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003645 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003646 Decimal("101.5")
3647 """
3648 return a.__abs__(context=self)
3649
3650 def add(self, a, b):
3651 """Return the sum of the two operands.
3652
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003653 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003654 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003655 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003656 Decimal("1.02E+4")
3657 """
3658 return a.__add__(b, context=self)
3659
3660 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003661 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003662
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003663 def canonical(self, a):
3664 """Returns the same Decimal object.
3665
3666 As we do not have different encodings for the same number, the
3667 received object already is in its canonical form.
3668
3669 >>> ExtendedContext.canonical(Decimal('2.50'))
3670 Decimal("2.50")
3671 """
3672 return a.canonical(context=self)
3673
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003674 def compare(self, a, b):
3675 """Compares values numerically.
3676
3677 If the signs of the operands differ, a value representing each operand
3678 ('-1' if the operand is less than zero, '0' if the operand is zero or
3679 negative zero, or '1' if the operand is greater than zero) is used in
3680 place of that operand for the comparison instead of the actual
3681 operand.
3682
3683 The comparison is then effected by subtracting the second operand from
3684 the first and then returning a value according to the result of the
3685 subtraction: '-1' if the result is less than zero, '0' if the result is
3686 zero or negative zero, or '1' if the result is greater than zero.
3687
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003688 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003689 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003690 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003691 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003692 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003693 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003694 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003695 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003696 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003697 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003698 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003699 Decimal("-1")
3700 """
3701 return a.compare(b, context=self)
3702
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003703 def compare_signal(self, a, b):
3704 """Compares the values of the two operands numerically.
3705
3706 It's pretty much like compare(), but all NaNs signal, with signaling
3707 NaNs taking precedence over quiet NaNs.
3708
3709 >>> c = ExtendedContext
3710 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3711 Decimal("-1")
3712 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3713 Decimal("0")
3714 >>> c.flags[InvalidOperation] = 0
3715 >>> print(c.flags[InvalidOperation])
3716 0
3717 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3718 Decimal("NaN")
3719 >>> print(c.flags[InvalidOperation])
3720 1
3721 >>> c.flags[InvalidOperation] = 0
3722 >>> print(c.flags[InvalidOperation])
3723 0
3724 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3725 Decimal("NaN")
3726 >>> print(c.flags[InvalidOperation])
3727 1
3728 """
3729 return a.compare_signal(b, context=self)
3730
3731 def compare_total(self, a, b):
3732 """Compares two operands using their abstract representation.
3733
3734 This is not like the standard compare, which use their numerical
3735 value. Note that a total ordering is defined for all possible abstract
3736 representations.
3737
3738 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3739 Decimal("-1")
3740 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3741 Decimal("-1")
3742 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3743 Decimal("-1")
3744 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3745 Decimal("0")
3746 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3747 Decimal("1")
3748 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3749 Decimal("-1")
3750 """
3751 return a.compare_total(b)
3752
3753 def compare_total_mag(self, a, b):
3754 """Compares two operands using their abstract representation ignoring sign.
3755
3756 Like compare_total, but with operand's sign ignored and assumed to be 0.
3757 """
3758 return a.compare_total_mag(b)
3759
3760 def copy_abs(self, a):
3761 """Returns a copy of the operand with the sign set to 0.
3762
3763 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3764 Decimal("2.1")
3765 >>> ExtendedContext.copy_abs(Decimal('-100'))
3766 Decimal("100")
3767 """
3768 return a.copy_abs()
3769
3770 def copy_decimal(self, a):
3771 """Returns a copy of the decimal objet.
3772
3773 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3774 Decimal("2.1")
3775 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3776 Decimal("-1.00")
3777 """
3778 return Decimal(a)
3779
3780 def copy_negate(self, a):
3781 """Returns a copy of the operand with the sign inverted.
3782
3783 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3784 Decimal("-101.5")
3785 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3786 Decimal("101.5")
3787 """
3788 return a.copy_negate()
3789
3790 def copy_sign(self, a, b):
3791 """Copies the second operand's sign to the first one.
3792
3793 In detail, it returns a copy of the first operand with the sign
3794 equal to the sign of the second operand.
3795
3796 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3797 Decimal("1.50")
3798 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3799 Decimal("1.50")
3800 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3801 Decimal("-1.50")
3802 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3803 Decimal("-1.50")
3804 """
3805 return a.copy_sign(b)
3806
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003807 def divide(self, a, b):
3808 """Decimal division in a specified context.
3809
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003810 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003811 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003812 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003813 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003814 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003815 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003816 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003817 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003818 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003819 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003820 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003821 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003822 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003823 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003824 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003825 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003826 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003827 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003828 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003829 Decimal("1.20E+6")
3830 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003831 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003832
3833 def divide_int(self, a, b):
3834 """Divides two numbers and returns the integer part of the result.
3835
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003836 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003837 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003838 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003839 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003840 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003841 Decimal("3")
3842 """
3843 return a.__floordiv__(b, context=self)
3844
3845 def divmod(self, a, b):
3846 return a.__divmod__(b, context=self)
3847
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003848 def exp(self, a):
3849 """Returns e ** a.
3850
3851 >>> c = ExtendedContext.copy()
3852 >>> c.Emin = -999
3853 >>> c.Emax = 999
3854 >>> c.exp(Decimal('-Infinity'))
3855 Decimal("0")
3856 >>> c.exp(Decimal('-1'))
3857 Decimal("0.367879441")
3858 >>> c.exp(Decimal('0'))
3859 Decimal("1")
3860 >>> c.exp(Decimal('1'))
3861 Decimal("2.71828183")
3862 >>> c.exp(Decimal('0.693147181'))
3863 Decimal("2.00000000")
3864 >>> c.exp(Decimal('+Infinity'))
3865 Decimal("Infinity")
3866 """
3867 return a.exp(context=self)
3868
3869 def fma(self, a, b, c):
3870 """Returns a multiplied by b, plus c.
3871
3872 The first two operands are multiplied together, using multiply,
3873 the third operand is then added to the result of that
3874 multiplication, using add, all with only one final rounding.
3875
3876 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3877 Decimal("22")
3878 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3879 Decimal("-8")
3880 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3881 Decimal("1.38435736E+12")
3882 """
3883 return a.fma(b, c, context=self)
3884
3885 def is_canonical(self, a):
3886 """Returns 1 if the operand is canonical; otherwise returns 0.
3887
3888 >>> ExtendedContext.is_canonical(Decimal('2.50'))
3889 Decimal("1")
3890 """
3891 return Dec_p1
3892
3893 def is_finite(self, a):
3894 """Returns 1 if the operand is finite, otherwise returns 0.
3895
3896 For it to be finite, it must be neither infinite nor a NaN.
3897
3898 >>> ExtendedContext.is_finite(Decimal('2.50'))
3899 Decimal("1")
3900 >>> ExtendedContext.is_finite(Decimal('-0.3'))
3901 Decimal("1")
3902 >>> ExtendedContext.is_finite(Decimal('0'))
3903 Decimal("1")
3904 >>> ExtendedContext.is_finite(Decimal('Inf'))
3905 Decimal("0")
3906 >>> ExtendedContext.is_finite(Decimal('NaN'))
3907 Decimal("0")
3908 """
3909 return a.is_finite()
3910
3911 def is_infinite(self, a):
3912 """Returns 1 if the operand is an Infinite, otherwise returns 0.
3913
3914 >>> ExtendedContext.is_infinite(Decimal('2.50'))
3915 Decimal("0")
3916 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
3917 Decimal("1")
3918 >>> ExtendedContext.is_infinite(Decimal('NaN'))
3919 Decimal("0")
3920 """
3921 return a.is_infinite()
3922
3923 def is_nan(self, a):
3924 """Returns 1 if the operand is qNaN or sNaN, otherwise returns 0.
3925
3926 >>> ExtendedContext.is_nan(Decimal('2.50'))
3927 Decimal("0")
3928 >>> ExtendedContext.is_nan(Decimal('NaN'))
3929 Decimal("1")
3930 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
3931 Decimal("1")
3932 """
3933 return a.is_nan()
3934
3935 def is_normal(self, a):
3936 """Returns 1 if the operand is a normal number, otherwise returns 0.
3937
3938 >>> c = ExtendedContext.copy()
3939 >>> c.Emin = -999
3940 >>> c.Emax = 999
3941 >>> c.is_normal(Decimal('2.50'))
3942 Decimal("1")
3943 >>> c.is_normal(Decimal('0.1E-999'))
3944 Decimal("0")
3945 >>> c.is_normal(Decimal('0.00'))
3946 Decimal("0")
3947 >>> c.is_normal(Decimal('-Inf'))
3948 Decimal("0")
3949 >>> c.is_normal(Decimal('NaN'))
3950 Decimal("0")
3951 """
3952 return a.is_normal(context=self)
3953
3954 def is_qnan(self, a):
3955 """Returns 1 if the operand is a quiet NaN, otherwise returns 0.
3956
3957 >>> ExtendedContext.is_qnan(Decimal('2.50'))
3958 Decimal("0")
3959 >>> ExtendedContext.is_qnan(Decimal('NaN'))
3960 Decimal("1")
3961 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
3962 Decimal("0")
3963 """
3964 return a.is_qnan()
3965
3966 def is_signed(self, a):
3967 """Returns 1 if the operand is negative, otherwise returns 0.
3968
3969 >>> ExtendedContext.is_signed(Decimal('2.50'))
3970 Decimal("0")
3971 >>> ExtendedContext.is_signed(Decimal('-12'))
3972 Decimal("1")
3973 >>> ExtendedContext.is_signed(Decimal('-0'))
3974 Decimal("1")
3975 """
3976 return a.is_signed()
3977
3978 def is_snan(self, a):
3979 """Returns 1 if the operand is a signaling NaN, otherwise returns 0.
3980
3981 >>> ExtendedContext.is_snan(Decimal('2.50'))
3982 Decimal("0")
3983 >>> ExtendedContext.is_snan(Decimal('NaN'))
3984 Decimal("0")
3985 >>> ExtendedContext.is_snan(Decimal('sNaN'))
3986 Decimal("1")
3987 """
3988 return a.is_snan()
3989
3990 def is_subnormal(self, a):
3991 """Returns 1 if the operand is subnormal, otherwise returns 0.
3992
3993 >>> c = ExtendedContext.copy()
3994 >>> c.Emin = -999
3995 >>> c.Emax = 999
3996 >>> c.is_subnormal(Decimal('2.50'))
3997 Decimal("0")
3998 >>> c.is_subnormal(Decimal('0.1E-999'))
3999 Decimal("1")
4000 >>> c.is_subnormal(Decimal('0.00'))
4001 Decimal("0")
4002 >>> c.is_subnormal(Decimal('-Inf'))
4003 Decimal("0")
4004 >>> c.is_subnormal(Decimal('NaN'))
4005 Decimal("0")
4006 """
4007 return a.is_subnormal(context=self)
4008
4009 def is_zero(self, a):
4010 """Returns 1 if the operand is a zero, otherwise returns 0.
4011
4012 >>> ExtendedContext.is_zero(Decimal('0'))
4013 Decimal("1")
4014 >>> ExtendedContext.is_zero(Decimal('2.50'))
4015 Decimal("0")
4016 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
4017 Decimal("1")
4018 """
4019 return a.is_zero()
4020
4021 def ln(self, a):
4022 """Returns the natural (base e) logarithm of the operand.
4023
4024 >>> c = ExtendedContext.copy()
4025 >>> c.Emin = -999
4026 >>> c.Emax = 999
4027 >>> c.ln(Decimal('0'))
4028 Decimal("-Infinity")
4029 >>> c.ln(Decimal('1.000'))
4030 Decimal("0")
4031 >>> c.ln(Decimal('2.71828183'))
4032 Decimal("1.00000000")
4033 >>> c.ln(Decimal('10'))
4034 Decimal("2.30258509")
4035 >>> c.ln(Decimal('+Infinity'))
4036 Decimal("Infinity")
4037 """
4038 return a.ln(context=self)
4039
4040 def log10(self, a):
4041 """Returns the base 10 logarithm of the operand.
4042
4043 >>> c = ExtendedContext.copy()
4044 >>> c.Emin = -999
4045 >>> c.Emax = 999
4046 >>> c.log10(Decimal('0'))
4047 Decimal("-Infinity")
4048 >>> c.log10(Decimal('0.001'))
4049 Decimal("-3")
4050 >>> c.log10(Decimal('1.000'))
4051 Decimal("0")
4052 >>> c.log10(Decimal('2'))
4053 Decimal("0.301029996")
4054 >>> c.log10(Decimal('10'))
4055 Decimal("1")
4056 >>> c.log10(Decimal('70'))
4057 Decimal("1.84509804")
4058 >>> c.log10(Decimal('+Infinity'))
4059 Decimal("Infinity")
4060 """
4061 return a.log10(context=self)
4062
4063 def logb(self, a):
4064 """ Returns the exponent of the magnitude of the operand's MSD.
4065
4066 The result is the integer which is the exponent of the magnitude
4067 of the most significant digit of the operand (as though the
4068 operand were truncated to a single digit while maintaining the
4069 value of that digit and without limiting the resulting exponent).
4070
4071 >>> ExtendedContext.logb(Decimal('250'))
4072 Decimal("2")
4073 >>> ExtendedContext.logb(Decimal('2.50'))
4074 Decimal("0")
4075 >>> ExtendedContext.logb(Decimal('0.03'))
4076 Decimal("-2")
4077 >>> ExtendedContext.logb(Decimal('0'))
4078 Decimal("-Infinity")
4079 """
4080 return a.logb(context=self)
4081
4082 def logical_and(self, a, b):
4083 """Applies the logical operation 'and' between each operand's digits.
4084
4085 The operands must be both logical numbers.
4086
4087 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4088 Decimal("0")
4089 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4090 Decimal("0")
4091 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4092 Decimal("0")
4093 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4094 Decimal("1")
4095 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4096 Decimal("1000")
4097 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4098 Decimal("10")
4099 """
4100 return a.logical_and(b, context=self)
4101
4102 def logical_invert(self, a):
4103 """Invert all the digits in the operand.
4104
4105 The operand must be a logical number.
4106
4107 >>> ExtendedContext.logical_invert(Decimal('0'))
4108 Decimal("111111111")
4109 >>> ExtendedContext.logical_invert(Decimal('1'))
4110 Decimal("111111110")
4111 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4112 Decimal("0")
4113 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4114 Decimal("10101010")
4115 """
4116 return a.logical_invert(context=self)
4117
4118 def logical_or(self, a, b):
4119 """Applies the logical operation 'or' between each operand's digits.
4120
4121 The operands must be both logical numbers.
4122
4123 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4124 Decimal("0")
4125 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4126 Decimal("1")
4127 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4128 Decimal("1")
4129 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4130 Decimal("1")
4131 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4132 Decimal("1110")
4133 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4134 Decimal("1110")
4135 """
4136 return a.logical_or(b, context=self)
4137
4138 def logical_xor(self, a, b):
4139 """Applies the logical operation 'xor' between each operand's digits.
4140
4141 The operands must be both logical numbers.
4142
4143 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4144 Decimal("0")
4145 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4146 Decimal("1")
4147 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4148 Decimal("1")
4149 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4150 Decimal("0")
4151 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4152 Decimal("110")
4153 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4154 Decimal("1101")
4155 """
4156 return a.logical_xor(b, context=self)
4157
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004158 def max(self, a,b):
4159 """max compares two values numerically and returns the maximum.
4160
4161 If either operand is a NaN then the general rules apply.
4162 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004163 operation. If they are numerically equal then the left-hand operand
4164 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004165 infinity) of the two operands is chosen as the result.
4166
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004167 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004168 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004169 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004170 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004171 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004172 Decimal("1")
4173 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4174 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004175 """
4176 return a.max(b, context=self)
4177
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004178 def max_mag(self, a, b):
4179 """Compares the values numerically with their sign ignored."""
4180 return a.max_mag(b, context=self)
4181
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004182 def min(self, a,b):
4183 """min compares two values numerically and returns the minimum.
4184
4185 If either operand is a NaN then the general rules apply.
4186 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004187 operation. If they are numerically equal then the left-hand operand
4188 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004189 infinity) of the two operands is chosen as the result.
4190
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004191 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004192 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004193 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004194 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004195 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004196 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004197 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4198 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004199 """
4200 return a.min(b, context=self)
4201
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004202 def min_mag(self, a, b):
4203 """Compares the values numerically with their sign ignored."""
4204 return a.min_mag(b, context=self)
4205
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004206 def minus(self, a):
4207 """Minus corresponds to unary prefix minus in Python.
4208
4209 The operation is evaluated using the same rules as subtract; the
4210 operation minus(a) is calculated as subtract('0', a) where the '0'
4211 has the same exponent as the operand.
4212
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004213 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004214 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004215 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004216 Decimal("1.3")
4217 """
4218 return a.__neg__(context=self)
4219
4220 def multiply(self, a, b):
4221 """multiply multiplies two operands.
4222
4223 If either operand is a special value then the general rules apply.
4224 Otherwise, the operands are multiplied together ('long multiplication'),
4225 resulting in a number which may be as long as the sum of the lengths
4226 of the two operands.
4227
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004228 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004229 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004230 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004231 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004232 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004233 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004234 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004235 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004236 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004237 Decimal("4.28135971E+11")
4238 """
4239 return a.__mul__(b, context=self)
4240
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004241 def next_minus(self, a):
4242 """Returns the largest representable number smaller than a.
4243
4244 >>> c = ExtendedContext.copy()
4245 >>> c.Emin = -999
4246 >>> c.Emax = 999
4247 >>> ExtendedContext.next_minus(Decimal('1'))
4248 Decimal("0.999999999")
4249 >>> c.next_minus(Decimal('1E-1007'))
4250 Decimal("0E-1007")
4251 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4252 Decimal("-1.00000004")
4253 >>> c.next_minus(Decimal('Infinity'))
4254 Decimal("9.99999999E+999")
4255 """
4256 return a.next_minus(context=self)
4257
4258 def next_plus(self, a):
4259 """Returns the smallest representable number larger than a.
4260
4261 >>> c = ExtendedContext.copy()
4262 >>> c.Emin = -999
4263 >>> c.Emax = 999
4264 >>> ExtendedContext.next_plus(Decimal('1'))
4265 Decimal("1.00000001")
4266 >>> c.next_plus(Decimal('-1E-1007'))
4267 Decimal("-0E-1007")
4268 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4269 Decimal("-1.00000002")
4270 >>> c.next_plus(Decimal('-Infinity'))
4271 Decimal("-9.99999999E+999")
4272 """
4273 return a.next_plus(context=self)
4274
4275 def next_toward(self, a, b):
4276 """Returns the number closest to a, in direction towards b.
4277
4278 The result is the closest representable number from the first
4279 operand (but not the first operand) that is in the direction
4280 towards the second operand, unless the operands have the same
4281 value.
4282
4283 >>> c = ExtendedContext.copy()
4284 >>> c.Emin = -999
4285 >>> c.Emax = 999
4286 >>> c.next_toward(Decimal('1'), Decimal('2'))
4287 Decimal("1.00000001")
4288 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4289 Decimal("-0E-1007")
4290 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4291 Decimal("-1.00000002")
4292 >>> c.next_toward(Decimal('1'), Decimal('0'))
4293 Decimal("0.999999999")
4294 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4295 Decimal("0E-1007")
4296 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4297 Decimal("-1.00000004")
4298 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4299 Decimal("-0.00")
4300 """
4301 return a.next_toward(b, context=self)
4302
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004303 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004304 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004305
4306 Essentially a plus operation with all trailing zeros removed from the
4307 result.
4308
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004309 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004310 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004311 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004312 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004313 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004314 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004315 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004316 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004317 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004318 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004319 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004320 Decimal("0")
4321 """
4322 return a.normalize(context=self)
4323
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004324 def number_class(self, a):
4325 """Returns an indication of the class of the operand.
4326
4327 The class is one of the following strings:
4328 -sNaN
4329 -NaN
4330 -Infinity
4331 -Normal
4332 -Subnormal
4333 -Zero
4334 +Zero
4335 +Subnormal
4336 +Normal
4337 +Infinity
4338
4339 >>> c = Context(ExtendedContext)
4340 >>> c.Emin = -999
4341 >>> c.Emax = 999
4342 >>> c.number_class(Decimal('Infinity'))
4343 '+Infinity'
4344 >>> c.number_class(Decimal('1E-10'))
4345 '+Normal'
4346 >>> c.number_class(Decimal('2.50'))
4347 '+Normal'
4348 >>> c.number_class(Decimal('0.1E-999'))
4349 '+Subnormal'
4350 >>> c.number_class(Decimal('0'))
4351 '+Zero'
4352 >>> c.number_class(Decimal('-0'))
4353 '-Zero'
4354 >>> c.number_class(Decimal('-0.1E-999'))
4355 '-Subnormal'
4356 >>> c.number_class(Decimal('-1E-10'))
4357 '-Normal'
4358 >>> c.number_class(Decimal('-2.50'))
4359 '-Normal'
4360 >>> c.number_class(Decimal('-Infinity'))
4361 '-Infinity'
4362 >>> c.number_class(Decimal('NaN'))
4363 'NaN'
4364 >>> c.number_class(Decimal('-NaN'))
4365 'NaN'
4366 >>> c.number_class(Decimal('sNaN'))
4367 'sNaN'
4368 """
4369 return a.number_class(context=self)
4370
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004371 def plus(self, a):
4372 """Plus corresponds to unary prefix plus in Python.
4373
4374 The operation is evaluated using the same rules as add; the
4375 operation plus(a) is calculated as add('0', a) where the '0'
4376 has the same exponent as the operand.
4377
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004378 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004379 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004380 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004381 Decimal("-1.3")
4382 """
4383 return a.__pos__(context=self)
4384
4385 def power(self, a, b, modulo=None):
4386 """Raises a to the power of b, to modulo if given.
4387
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004388 With two arguments, compute a**b. If a is negative then b
4389 must be integral. The result will be inexact unless b is
4390 integral and the result is finite and can be expressed exactly
4391 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004392
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004393 With three arguments, compute (a**b) % modulo. For the
4394 three argument form, the following restrictions on the
4395 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004396
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004397 - all three arguments must be integral
4398 - b must be nonnegative
4399 - at least one of a or b must be nonzero
4400 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004401
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004402 The result of pow(a, b, modulo) is identical to the result
4403 that would be obtained by computing (a**b) % modulo with
4404 unbounded precision, but is computed more efficiently. It is
4405 always exact.
4406
4407 >>> c = ExtendedContext.copy()
4408 >>> c.Emin = -999
4409 >>> c.Emax = 999
4410 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004411 Decimal("8")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004412 >>> c.power(Decimal('-2'), Decimal('3'))
4413 Decimal("-8")
4414 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004415 Decimal("0.125")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004416 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004417 Decimal("69.7575744")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004418 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4419 Decimal("2.00000000")
4420 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004421 Decimal("0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004422 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004423 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004424 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004425 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004426 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004427 Decimal("-0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004428 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004429 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004430 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004431 Decimal("-Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004432 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004433 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004434 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004435 Decimal("NaN")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004436
4437 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4438 Decimal("11")
4439 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4440 Decimal("-11")
4441 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4442 Decimal("1")
4443 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4444 Decimal("11")
4445 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4446 Decimal("11729830")
4447 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4448 Decimal("-0")
4449 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4450 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004451 """
4452 return a.__pow__(b, modulo, context=self)
4453
4454 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004455 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004456
4457 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004458 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004459 exponent is being increased), multiplied by a positive power of ten (if
4460 the exponent is being decreased), or is unchanged (if the exponent is
4461 already equal to that of the right-hand operand).
4462
4463 Unlike other operations, if the length of the coefficient after the
4464 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004465 operation condition is raised. This guarantees that, unless there is
4466 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004467 equal to that of the right-hand operand.
4468
4469 Also unlike other operations, quantize will never raise Underflow, even
4470 if the result is subnormal and inexact.
4471
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004472 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004473 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004474 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004475 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004476 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004477 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004478 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004479 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004480 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004481 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004482 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004483 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004484 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004485 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004486 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004487 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004488 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004489 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004490 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004491 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004492 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004493 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004494 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004495 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004496 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004497 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004498 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004499 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004500 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004501 Decimal("2E+2")
4502 """
4503 return a.quantize(b, context=self)
4504
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004505 def radix(self):
4506 """Just returns 10, as this is Decimal, :)
4507
4508 >>> ExtendedContext.radix()
4509 Decimal("10")
4510 """
4511 return Decimal(10)
4512
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004513 def remainder(self, a, b):
4514 """Returns the remainder from integer division.
4515
4516 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004517 calculating integer division as described for divide-integer, rounded
4518 to precision digits if necessary. The sign of the result, if
4519 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004520
4521 This operation will fail under the same conditions as integer division
4522 (that is, if integer division on the same two operands would fail, the
4523 remainder cannot be calculated).
4524
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004525 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004526 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004527 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004528 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004529 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004530 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004531 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004532 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004533 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004534 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004535 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004536 Decimal("1.0")
4537 """
4538 return a.__mod__(b, context=self)
4539
4540 def remainder_near(self, a, b):
4541 """Returns to be "a - b * n", where n is the integer nearest the exact
4542 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004543 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004544 sign of a.
4545
4546 This operation will fail under the same conditions as integer division
4547 (that is, if integer division on the same two operands would fail, the
4548 remainder cannot be calculated).
4549
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004550 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004551 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004552 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004553 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004554 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004555 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004556 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004557 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004558 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004559 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004560 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004561 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004562 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004563 Decimal("-0.3")
4564 """
4565 return a.remainder_near(b, context=self)
4566
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004567 def rotate(self, a, b):
4568 """Returns a rotated copy of a, b times.
4569
4570 The coefficient of the result is a rotated copy of the digits in
4571 the coefficient of the first operand. The number of places of
4572 rotation is taken from the absolute value of the second operand,
4573 with the rotation being to the left if the second operand is
4574 positive or to the right otherwise.
4575
4576 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4577 Decimal("400000003")
4578 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4579 Decimal("12")
4580 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4581 Decimal("891234567")
4582 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4583 Decimal("123456789")
4584 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4585 Decimal("345678912")
4586 """
4587 return a.rotate(b, context=self)
4588
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004589 def same_quantum(self, a, b):
4590 """Returns True if the two operands have the same exponent.
4591
4592 The result is never affected by either the sign or the coefficient of
4593 either operand.
4594
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004595 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004596 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004597 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004598 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004599 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004600 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004601 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004602 True
4603 """
4604 return a.same_quantum(b)
4605
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004606 def scaleb (self, a, b):
4607 """Returns the first operand after adding the second value its exp.
4608
4609 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4610 Decimal("0.0750")
4611 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4612 Decimal("7.50")
4613 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4614 Decimal("7.50E+3")
4615 """
4616 return a.scaleb (b, context=self)
4617
4618 def shift(self, a, b):
4619 """Returns a shifted copy of a, b times.
4620
4621 The coefficient of the result is a shifted copy of the digits
4622 in the coefficient of the first operand. The number of places
4623 to shift is taken from the absolute value of the second operand,
4624 with the shift being to the left if the second operand is
4625 positive or to the right otherwise. Digits shifted into the
4626 coefficient are zeros.
4627
4628 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4629 Decimal("400000000")
4630 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4631 Decimal("0")
4632 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4633 Decimal("1234567")
4634 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4635 Decimal("123456789")
4636 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4637 Decimal("345678900")
4638 """
4639 return a.shift(b, context=self)
4640
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004641 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004642 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004643
4644 If the result must be inexact, it is rounded using the round-half-even
4645 algorithm.
4646
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004647 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004648 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004649 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004650 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004651 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004652 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004653 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004654 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004655 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004656 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004657 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004658 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004659 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004660 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004661 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004662 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004663 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004664 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004665 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004666 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004667 """
4668 return a.sqrt(context=self)
4669
4670 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004671 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004672
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004673 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004674 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004675 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004676 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004677 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004678 Decimal("-0.77")
4679 """
4680 return a.__sub__(b, context=self)
4681
4682 def to_eng_string(self, a):
4683 """Converts a number to a string, using scientific notation.
4684
4685 The operation is not affected by the context.
4686 """
4687 return a.to_eng_string(context=self)
4688
4689 def to_sci_string(self, a):
4690 """Converts a number to a string, using scientific notation.
4691
4692 The operation is not affected by the context.
4693 """
4694 return a.__str__(context=self)
4695
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004696 def to_integral_exact(self, a):
4697 """Rounds to an integer.
4698
4699 When the operand has a negative exponent, the result is the same
4700 as using the quantize() operation using the given operand as the
4701 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4702 of the operand as the precision setting; Inexact and Rounded flags
4703 are allowed in this operation. The rounding mode is taken from the
4704 context.
4705
4706 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4707 Decimal("2")
4708 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4709 Decimal("100")
4710 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4711 Decimal("100")
4712 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4713 Decimal("102")
4714 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4715 Decimal("-102")
4716 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4717 Decimal("1.0E+6")
4718 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4719 Decimal("7.89E+77")
4720 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4721 Decimal("-Infinity")
4722 """
4723 return a.to_integral_exact(context=self)
4724
4725 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004726 """Rounds to an integer.
4727
4728 When the operand has a negative exponent, the result is the same
4729 as using the quantize() operation using the given operand as the
4730 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4731 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00004732 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004733
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004734 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004735 Decimal("2")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004736 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004737 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004738 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004739 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004740 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004741 Decimal("102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004742 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004743 Decimal("-102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004744 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004745 Decimal("1.0E+6")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004746 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004747 Decimal("7.89E+77")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004748 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004749 Decimal("-Infinity")
4750 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004751 return a.to_integral_value(context=self)
4752
4753 # the method name changed, but we provide also the old one, for compatibility
4754 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004755
4756class _WorkRep(object):
4757 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004758 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004759 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004760 # exp: None, int, or string
4761
4762 def __init__(self, value=None):
4763 if value is None:
4764 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004765 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004766 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004767 elif isinstance(value, Decimal):
4768 self.sign = value._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004769 cum = 0
Raymond Hettinger17931de2004-10-27 06:21:46 +00004770 for digit in value._int:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004771 cum = cum * 10 + digit
4772 self.int = cum
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004773 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004774 else:
4775 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004776 self.sign = value[0]
4777 self.int = value[1]
4778 self.exp = value[2]
4779
4780 def __repr__(self):
4781 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4782
4783 __str__ = __repr__
4784
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004785
4786
4787def _normalize(op1, op2, shouldround = 0, prec = 0):
4788 """Normalizes op1, op2 to have the same exp and length of coefficient.
4789
4790 Done during addition.
4791 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004792 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004793 tmp = op2
4794 other = op1
4795 else:
4796 tmp = op1
4797 other = op2
4798
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004799 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4800 # Then adding 10**exp to tmp has the same effect (after rounding)
4801 # as adding any positive quantity smaller than 10**exp; similarly
4802 # for subtraction. So if other is smaller than 10**exp we replace
4803 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4804 if shouldround:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004805 tmp_len = len(str(tmp.int))
4806 other_len = len(str(other.int))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004807 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4808 if other_len + other.exp - 1 < exp:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004809 other.int = 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004810 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004811
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004812 tmp.int *= 10 ** (tmp.exp - other.exp)
4813 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004814 return op1, op2
4815
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004816##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004817
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004818# This function from Tim Peters was taken from here:
4819# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4820# The correction being in the function definition is for speed, and
4821# the whole function is not resolved with math.log because of avoiding
4822# the use of floats.
4823def _nbits(n, correction = {
4824 '0': 4, '1': 3, '2': 2, '3': 2,
4825 '4': 1, '5': 1, '6': 1, '7': 1,
4826 '8': 0, '9': 0, 'a': 0, 'b': 0,
4827 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4828 """Number of bits in binary representation of the positive integer n,
4829 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004830 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004831 if n < 0:
4832 raise ValueError("The argument to _nbits should be nonnegative.")
4833 hex_n = "%x" % n
4834 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004835
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004836def _sqrt_nearest(n, a):
4837 """Closest integer to the square root of the positive integer n. a is
4838 an initial approximation to the square root. Any positive integer
4839 will do for a, but the closer a is to the square root of n the
4840 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004841
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004842 """
4843 if n <= 0 or a <= 0:
4844 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4845
4846 b=0
4847 while a != b:
4848 b, a = a, a--n//a>>1
4849 return a
4850
4851def _rshift_nearest(x, shift):
4852 """Given an integer x and a nonnegative integer shift, return closest
4853 integer to x / 2**shift; use round-to-even in case of a tie.
4854
4855 """
4856 b, q = 1 << shift, x >> shift
4857 return q + (2*(x & (b-1)) + (q&1) > b)
4858
4859def _div_nearest(a, b):
4860 """Closest integer to a/b, a and b positive integers; rounds to even
4861 in the case of a tie.
4862
4863 """
4864 q, r = divmod(a, b)
4865 return q + (2*r + (q&1) > b)
4866
4867def _ilog(x, M, L = 8):
4868 """Integer approximation to M*log(x/M), with absolute error boundable
4869 in terms only of x/M.
4870
4871 Given positive integers x and M, return an integer approximation to
4872 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4873 between the approximation and the exact result is at most 22. For
4874 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4875 both cases these are upper bounds on the error; it will usually be
4876 much smaller."""
4877
4878 # The basic algorithm is the following: let log1p be the function
4879 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4880 # the reduction
4881 #
4882 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4883 #
4884 # repeatedly until the argument to log1p is small (< 2**-L in
4885 # absolute value). For small y we can use the Taylor series
4886 # expansion
4887 #
4888 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4889 #
4890 # truncating at T such that y**T is small enough. The whole
4891 # computation is carried out in a form of fixed-point arithmetic,
4892 # with a real number z being represented by an integer
4893 # approximation to z*M. To avoid loss of precision, the y below
4894 # is actually an integer approximation to 2**R*y*M, where R is the
4895 # number of reductions performed so far.
4896
4897 y = x-M
4898 # argument reduction; R = number of reductions performed
4899 R = 0
4900 while (R <= L and abs(y) << L-R >= M or
4901 R > L and abs(y) >> R-L >= M):
4902 y = _div_nearest((M*y) << 1,
4903 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4904 R += 1
4905
4906 # Taylor series with T terms
4907 T = -int(-10*len(str(M))//(3*L))
4908 yshift = _rshift_nearest(y, R)
4909 w = _div_nearest(M, T)
4910 for k in range(T-1, 0, -1):
4911 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4912
4913 return _div_nearest(w*y, M)
4914
4915def _dlog10(c, e, p):
4916 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4917 approximation to 10**p * log10(c*10**e), with an absolute error of
4918 at most 1. Assumes that c*10**e is not exactly 1."""
4919
4920 # increase precision by 2; compensate for this by dividing
4921 # final result by 100
4922 p += 2
4923
4924 # write c*10**e as d*10**f with either:
4925 # f >= 0 and 1 <= d <= 10, or
4926 # f <= 0 and 0.1 <= d <= 1.
4927 # Thus for c*10**e close to 1, f = 0
4928 l = len(str(c))
4929 f = e+l - (e+l >= 1)
4930
4931 if p > 0:
4932 M = 10**p
4933 k = e+p-f
4934 if k >= 0:
4935 c *= 10**k
4936 else:
4937 c = _div_nearest(c, 10**-k)
4938
4939 log_d = _ilog(c, M) # error < 5 + 22 = 27
4940 log_10 = _ilog(10*M, M) # error < 15
4941 log_d = _div_nearest(log_d*M, log_10)
4942 log_tenpower = f*M # exact
4943 else:
4944 log_d = 0 # error < 2.31
4945 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4946
4947 return _div_nearest(log_tenpower+log_d, 100)
4948
4949def _dlog(c, e, p):
4950 """Given integers c, e and p with c > 0, compute an integer
4951 approximation to 10**p * log(c*10**e), with an absolute error of
4952 at most 1. Assumes that c*10**e is not exactly 1."""
4953
4954 # Increase precision by 2. The precision increase is compensated
4955 # for at the end with a division by 100.
4956 p += 2
4957
4958 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4959 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4960 # as 10**p * log(d) + 10**p*f * log(10).
4961 l = len(str(c))
4962 f = e+l - (e+l >= 1)
4963
4964 # compute approximation to 10**p*log(d), with error < 27
4965 if p > 0:
4966 k = e+p-f
4967 if k >= 0:
4968 c *= 10**k
4969 else:
4970 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4971
4972 # _ilog magnifies existing error in c by a factor of at most 10
4973 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4974 else:
4975 # p <= 0: just approximate the whole thing by 0; error < 2.31
4976 log_d = 0
4977
4978 # compute approximation to 10**p*f*log(10), with error < 17
4979 if f:
4980 sign_f = [-1, 1][f > 0]
4981 if p >= 0:
4982 M = 10**p * abs(f)
4983 else:
4984 M = _div_nearest(abs(f), 10**-p) # M = 10**p*|f|, error <= 0.5
4985
4986 if M:
4987 f_log_ten = sign_f*_ilog(10*M, M) # M*log(10), error <= 1.2 + 15 < 17
4988 else:
4989 f_log_ten = 0
4990 else:
4991 f_log_ten = 0
4992
4993 # error in sum < 17+27 = 44; error after division < 0.44 + 0.5 < 1
4994 return _div_nearest(f_log_ten + log_d, 100)
4995
4996def _iexp(x, M, L=8):
4997 """Given integers x and M, M > 0, such that x/M is small in absolute
4998 value, compute an integer approximation to M*exp(x/M). For 0 <=
4999 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5000 is usually much smaller)."""
5001
5002 # Algorithm: to compute exp(z) for a real number z, first divide z
5003 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5004 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5005 # series
5006 #
5007 # expm1(x) = x + x**2/2! + x**3/3! + ...
5008 #
5009 # Now use the identity
5010 #
5011 # expm1(2x) = expm1(x)*(expm1(x)+2)
5012 #
5013 # R times to compute the sequence expm1(z/2**R),
5014 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5015
5016 # Find R such that x/2**R/M <= 2**-L
5017 R = _nbits((x<<L)//M)
5018
5019 # Taylor series. (2**L)**T > M
5020 T = -int(-10*len(str(M))//(3*L))
5021 y = _div_nearest(x, T)
5022 Mshift = M<<R
5023 for i in range(T-1, 0, -1):
5024 y = _div_nearest(x*(Mshift + y), Mshift * i)
5025
5026 # Expansion
5027 for k in range(R-1, -1, -1):
5028 Mshift = M<<(k+2)
5029 y = _div_nearest(y*(y+Mshift), Mshift)
5030
5031 return M+y
5032
5033def _dexp(c, e, p):
5034 """Compute an approximation to exp(c*10**e), with p decimal places of
5035 precision.
5036
5037 Returns d, f such that:
5038
5039 10**(p-1) <= d <= 10**p, and
5040 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5041
5042 In other words, d*10**f is an approximation to exp(c*10**e) with p
5043 digits of precision, and with an error in d of at most 1. This is
5044 almost, but not quite, the same as the error being < 1ulp: when d
5045 = 10**(p-1) the error could be up to 10 ulp."""
5046
5047 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5048 p += 2
5049
5050 # compute log10 with extra precision = adjusted exponent of c*10**e
5051 extra = max(0, e + len(str(c)) - 1)
5052 q = p + extra
5053 log10 = _dlog(10, 0, q) # error <= 1
5054
5055 # compute quotient c*10**e/(log10/10**q) = c*10**(e+q)/log10,
5056 # rounding down
5057 shift = e+q
5058 if shift >= 0:
5059 cshift = c*10**shift
5060 else:
5061 cshift = c//10**-shift
5062 quot, rem = divmod(cshift, log10)
5063
5064 # reduce remainder back to original precision
5065 rem = _div_nearest(rem, 10**extra)
5066
5067 # error in result of _iexp < 120; error after division < 0.62
5068 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5069
5070def _dpower(xc, xe, yc, ye, p):
5071 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5072 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5073
5074 10**(p-1) <= c <= 10**p, and
5075 (c-1)*10**e < x**y < (c+1)*10**e
5076
5077 in other words, c*10**e is an approximation to x**y with p digits
5078 of precision, and with an error in c of at most 1. (This is
5079 almost, but not quite, the same as the error being < 1ulp: when c
5080 == 10**(p-1) we can only guarantee error < 10ulp.)
5081
5082 We assume that: x is positive and not equal to 1, and y is nonzero.
5083 """
5084
5085 # Find b such that 10**(b-1) <= |y| <= 10**b
5086 b = len(str(abs(yc))) + ye
5087
5088 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5089 lxc = _dlog(xc, xe, p+b+1)
5090
5091 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5092 shift = ye-b
5093 if shift >= 0:
5094 pc = lxc*yc*10**shift
5095 else:
5096 pc = _div_nearest(lxc*yc, 10**-shift)
5097
5098 if pc == 0:
5099 # we prefer a result that isn't exactly 1; this makes it
5100 # easier to compute a correctly rounded result in __pow__
5101 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5102 coeff, exp = 10**(p-1)+1, 1-p
5103 else:
5104 coeff, exp = 10**p-1, -p
5105 else:
5106 coeff, exp = _dexp(pc, -(p+1), p+1)
5107 coeff = _div_nearest(coeff, 10)
5108 exp += 1
5109
5110 return coeff, exp
5111
5112def _log10_lb(c, correction = {
5113 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5114 '6': 23, '7': 16, '8': 10, '9': 5}):
5115 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5116 if c <= 0:
5117 raise ValueError("The argument to _log10_lb should be nonnegative.")
5118 str_c = str(c)
5119 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005120
Guido van Rossumd8faa362007-04-27 19:54:29 +00005121##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005122
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005123def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005124 """Convert other to Decimal.
5125
5126 Verifies that it's ok to use in an implicit construction.
5127 """
5128 if isinstance(other, Decimal):
5129 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005130 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005131 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005132 if raiseit:
5133 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005134 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005135
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005136_infinity_map = {
5137 'inf' : 1,
5138 'infinity' : 1,
5139 '+inf' : 1,
5140 '+infinity' : 1,
5141 '-inf' : -1,
5142 '-infinity' : -1
5143}
5144
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005145def _isinfinity(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005146 """Determines whether a string or float is infinity.
5147
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005148 +1 for negative infinity; 0 for finite ; +1 for positive infinity
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005149 """
5150 num = str(num).lower()
5151 return _infinity_map.get(num, 0)
5152
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005153def _isnan(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005154 """Determines whether a string or float is NaN
5155
5156 (1, sign, diagnostic info as string) => NaN
5157 (2, sign, diagnostic info as string) => sNaN
5158 0 => not a NaN
5159 """
5160 num = str(num).lower()
5161 if not num:
5162 return 0
5163
Guido van Rossumd8faa362007-04-27 19:54:29 +00005164 # Get the sign, get rid of trailing [+-]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005165 sign = 0
5166 if num[0] == '+':
5167 num = num[1:]
Guido van Rossumd8faa362007-04-27 19:54:29 +00005168 elif num[0] == '-': # elif avoids '+-nan'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005169 num = num[1:]
5170 sign = 1
5171
5172 if num.startswith('nan'):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005173 if len(num) > 3 and not num[3:].isdigit(): # diagnostic info
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005174 return 0
5175 return (1, sign, num[3:].lstrip('0'))
5176 if num.startswith('snan'):
5177 if len(num) > 4 and not num[4:].isdigit():
5178 return 0
5179 return (2, sign, num[4:].lstrip('0'))
5180 return 0
5181
5182
Guido van Rossumd8faa362007-04-27 19:54:29 +00005183##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005184
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005185# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005186# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005187
5188DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005189 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005190 traps=[DivisionByZero, Overflow, InvalidOperation],
5191 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005192 _rounding_decision=ALWAYS_ROUND,
Raymond Hettinger99148e72004-07-14 19:56:56 +00005193 Emax=999999999,
5194 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005195 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005196)
5197
5198# Pre-made alternate contexts offered by the specification
5199# Don't change these; the user should be able to select these
5200# contexts and be able to reproduce results from other implementations
5201# of the spec.
5202
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005203BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005204 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005205 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5206 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005207)
5208
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005209ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005210 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005211 traps=[],
5212 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005213)
5214
5215
Guido van Rossumd8faa362007-04-27 19:54:29 +00005216##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005217
Guido van Rossumd8faa362007-04-27 19:54:29 +00005218# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005219Inf = Decimal('Inf')
5220negInf = Decimal('-Inf')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005221NaN = Decimal('NaN')
5222Dec_0 = Decimal(0)
5223Dec_p1 = Decimal(1)
5224Dec_n1 = Decimal(-1)
5225Dec_p2 = Decimal(2)
5226Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005227
Guido van Rossumd8faa362007-04-27 19:54:29 +00005228# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005229Infsign = (Inf, negInf)
5230
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005231
Guido van Rossumd8faa362007-04-27 19:54:29 +00005232##### crud for parsing strings #############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005233import re
5234
5235# There's an optional sign at the start, and an optional exponent
5236# at the end. The exponent has an optional sign and at least one
5237# digit. In between, must have either at least one digit followed
5238# by an optional fraction, or a decimal point followed by at least
5239# one digit. Yuck.
5240
5241_parser = re.compile(r"""
5242# \s*
5243 (?P<sign>[-+])?
5244 (
5245 (?P<int>\d+) (\. (?P<frac>\d*))?
5246 |
5247 \. (?P<onlyfrac>\d+)
5248 )
5249 ([eE](?P<exp>[-+]? \d+))?
5250# \s*
5251 $
Guido van Rossumd8faa362007-04-27 19:54:29 +00005252""", re.VERBOSE).match # Uncomment the \s* to allow leading or trailing spaces.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005253
5254del re
5255
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005256def _string2exact(s):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005257 """Return sign, n, p s.t.
5258
5259 Float string value == -1**sign * n * 10**p exactly
5260 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005261 m = _parser(s)
5262 if m is None:
5263 raise ValueError("invalid literal for Decimal: %r" % s)
5264
5265 if m.group('sign') == "-":
5266 sign = 1
5267 else:
5268 sign = 0
5269
5270 exp = m.group('exp')
5271 if exp is None:
5272 exp = 0
5273 else:
5274 exp = int(exp)
5275
5276 intpart = m.group('int')
5277 if intpart is None:
5278 intpart = ""
5279 fracpart = m.group('onlyfrac')
5280 else:
5281 fracpart = m.group('frac')
5282 if fracpart is None:
5283 fracpart = ""
5284
5285 exp -= len(fracpart)
5286
5287 mantissa = intpart + fracpart
Guido van Rossumc1f779c2007-07-03 08:25:58 +00005288 tmp = list(map(int, mantissa))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005289 backup = tmp
5290 while tmp and tmp[0] == 0:
5291 del tmp[0]
5292
5293 # It's a zero
5294 if not tmp:
5295 if backup:
5296 return (sign, tuple(backup), exp)
5297 return (sign, (0,), exp)
5298 mantissa = tuple(tmp)
5299
5300 return (sign, mantissa, exp)
5301
5302
5303if __name__ == '__main__':
5304 import doctest, sys
5305 doctest.testmod(sys.modules[__name__])