blob: 17d67d541d0e1d9e8fa49771479c5ce874ff86c2 [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',
131 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN',
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'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000147
Guido van Rossumd8faa362007-04-27 19:54:29 +0000148# Rounding decision (not part of the public API)
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000149NEVER_ROUND = 'NEVER_ROUND' # Round in division (non-divmod), sqrt ONLY
150ALWAYS_ROUND = 'ALWAYS_ROUND' # Every operation rounds at end.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000151
Guido van Rossumd8faa362007-04-27 19:54:29 +0000152# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000153
154class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000155 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000156
157 Used exceptions derive from this.
158 If an exception derives from another exception besides this (such as
159 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
160 called if the others are present. This isn't actually used for
161 anything, though.
162
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000163 handle -- Called when context._raise_error is called and the
164 trap_enabler is set. First argument is self, second is the
165 context. More arguments can be given, those being after
166 the explanation in _raise_error (For example,
167 context._raise_error(NewError, '(-x)!', self._sign) would
168 call NewError().handle(context, self._sign).)
169
170 To define a new exception, it should be sufficient to have it derive
171 from DecimalException.
172 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000173 def handle(self, context, *args):
174 pass
175
176
177class Clamped(DecimalException):
178 """Exponent of a 0 changed to fit bounds.
179
180 This occurs and signals clamped if the exponent of a result has been
181 altered in order to fit the constraints of a specific concrete
Guido van Rossumd8faa362007-04-27 19:54:29 +0000182 representation. This may occur when the exponent of a zero result would
183 be outside the bounds of a representation, or when a large normal
184 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000185 this latter case, the exponent is reduced to fit and the corresponding
186 number of zero digits are appended to the coefficient ("fold-down").
187 """
188
189
190class InvalidOperation(DecimalException):
191 """An invalid operation was performed.
192
193 Various bad things cause this:
194
195 Something creates a signaling NaN
196 -INF + INF
Guido van Rossumd8faa362007-04-27 19:54:29 +0000197 0 * (+-)INF
198 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000199 x % 0
200 (+-)INF % x
201 x._rescale( non-integer )
202 sqrt(-x) , x > 0
203 0 ** 0
204 x ** (non-integer)
205 x ** (+-)INF
206 An operand is invalid
207 """
208 def handle(self, context, *args):
209 if args:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000210 if args[0] == 1: # sNaN, must drop 's' but keep diagnostics
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000211 return Decimal( (args[1]._sign, args[1]._int, 'n') )
212 return NaN
213
214class ConversionSyntax(InvalidOperation):
215 """Trying to convert badly formed string.
216
217 This occurs and signals invalid-operation if an string is being
218 converted to a number and it does not conform to the numeric string
Guido van Rossumd8faa362007-04-27 19:54:29 +0000219 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000220 """
221
222 def handle(self, context, *args):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000223 return (0, (0,), 'n') # Passed to something which uses a tuple.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000224
225class DivisionByZero(DecimalException, ZeroDivisionError):
226 """Division by 0.
227
228 This occurs and signals division-by-zero if division of a finite number
229 by zero was attempted (during a divide-integer or divide operation, or a
230 power operation with negative right-hand operand), and the dividend was
231 not zero.
232
233 The result of the operation is [sign,inf], where sign is the exclusive
234 or of the signs of the operands for divide, or is 1 for an odd power of
235 -0, for power.
236 """
237
238 def handle(self, context, sign, double = None, *args):
239 if double is not None:
240 return (Infsign[sign],)*2
241 return Infsign[sign]
242
243class DivisionImpossible(InvalidOperation):
244 """Cannot perform the division adequately.
245
246 This occurs and signals invalid-operation if the integer result of a
247 divide-integer or remainder operation had too many digits (would be
Guido van Rossumd8faa362007-04-27 19:54:29 +0000248 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000249 """
250
251 def handle(self, context, *args):
252 return (NaN, NaN)
253
254class DivisionUndefined(InvalidOperation, ZeroDivisionError):
255 """Undefined result of division.
256
257 This occurs and signals invalid-operation if division by zero was
258 attempted (during a divide-integer, divide, or remainder operation), and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000259 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000260 """
261
262 def handle(self, context, tup=None, *args):
263 if tup is not None:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000264 return (NaN, NaN) # for 0 %0, 0 // 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000265 return NaN
266
267class Inexact(DecimalException):
268 """Had to round, losing information.
269
270 This occurs and signals inexact whenever the result of an operation is
271 not exact (that is, it needed to be rounded and any discarded digits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000272 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000273 result in all cases is unchanged.
274
275 The inexact signal may be tested (or trapped) to determine if a given
276 operation (or sequence of operations) was inexact.
277 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000278 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000279
280class InvalidContext(InvalidOperation):
281 """Invalid context. Unknown rounding, for example.
282
283 This occurs and signals invalid-operation if an invalid context was
Guido van Rossumd8faa362007-04-27 19:54:29 +0000284 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000285 on creation and either the precision exceeds the capability of the
286 underlying concrete representation or an unknown or unsupported rounding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000287 was specified. These aspects of the context need only be checked when
288 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000289 """
290
291 def handle(self, context, *args):
292 return NaN
293
294class Rounded(DecimalException):
295 """Number got rounded (not necessarily changed during rounding).
296
297 This occurs and signals rounded whenever the result of an operation is
298 rounded (that is, some zero or non-zero digits were discarded from the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000299 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000300 result in all cases is unchanged.
301
302 The rounded signal may be tested (or trapped) to determine if a given
303 operation (or sequence of operations) caused a loss of precision.
304 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000305 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000306
307class Subnormal(DecimalException):
308 """Exponent < Emin before rounding.
309
310 This occurs and signals subnormal whenever the result of a conversion or
311 operation is subnormal (that is, its adjusted exponent is less than
Guido van Rossumd8faa362007-04-27 19:54:29 +0000312 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000313
314 The subnormal signal may be tested (or trapped) to determine if a given
315 or operation (or sequence of operations) yielded a subnormal result.
316 """
317 pass
318
319class Overflow(Inexact, Rounded):
320 """Numerical overflow.
321
322 This occurs and signals overflow if the adjusted exponent of a result
323 (from a conversion or from an operation that is not an attempt to divide
324 by zero), after rounding, would be greater than the largest value that
325 can be handled by the implementation (the value Emax).
326
327 The result depends on the rounding mode:
328
329 For round-half-up and round-half-even (and for round-half-down and
330 round-up, if implemented), the result of the operation is [sign,inf],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000331 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000332 result is the largest finite number that can be represented in the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000333 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000334 round-ceiling, the result is the same as for round-down if the sign of
Guido van Rossumd8faa362007-04-27 19:54:29 +0000335 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000336 the result is the same as for round-down if the sign of the intermediate
Guido van Rossumd8faa362007-04-27 19:54:29 +0000337 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000338 will also be raised.
339 """
340
341 def handle(self, context, sign, *args):
342 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
343 ROUND_HALF_DOWN, ROUND_UP):
344 return Infsign[sign]
345 if sign == 0:
346 if context.rounding == ROUND_CEILING:
347 return Infsign[sign]
348 return Decimal((sign, (9,)*context.prec,
349 context.Emax-context.prec+1))
350 if sign == 1:
351 if context.rounding == ROUND_FLOOR:
352 return Infsign[sign]
353 return Decimal( (sign, (9,)*context.prec,
354 context.Emax-context.prec+1))
355
356
357class Underflow(Inexact, Rounded, Subnormal):
358 """Numerical underflow with result rounded to 0.
359
360 This occurs and signals underflow if a result is inexact and the
361 adjusted exponent of the result would be smaller (more negative) than
362 the smallest value that can be handled by the implementation (the value
Guido van Rossumd8faa362007-04-27 19:54:29 +0000363 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000364
365 The result after an underflow will be a subnormal number rounded, if
Guido van Rossumd8faa362007-04-27 19:54:29 +0000366 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000367 in 0 with the sign of the intermediate result and an exponent of Etiny.
368
369 In all cases, Inexact, Rounded, and Subnormal will also be raised.
370 """
371
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000372# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000373_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000374 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000375
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000376# Map conditions (per the spec) to signals
377_condition_map = {ConversionSyntax:InvalidOperation,
378 DivisionImpossible:InvalidOperation,
379 DivisionUndefined:InvalidOperation,
380 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000381
Guido van Rossumd8faa362007-04-27 19:54:29 +0000382##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000383
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000384# The getcontext() and setcontext() function manage access to a thread-local
385# current context. Py2.4 offers direct support for thread locals. If that
386# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000387# work for older Pythons. If threads are not part of the build, create a
388# mock threading object with threading.local() returning the module namespace.
389
390try:
391 import threading
392except ImportError:
393 # Python was compiled without threads; create a mock object instead
394 import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +0000395 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000396 def local(self, sys=sys):
397 return sys.modules[__name__]
398 threading = MockThreading()
399 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000400
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000401try:
402 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000403
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000404except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000405
Guido van Rossumd8faa362007-04-27 19:54:29 +0000406 # To fix reloading, force it to create a new context
407 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000408 if hasattr(threading.currentThread(), '__decimal_context__'):
409 del threading.currentThread().__decimal_context__
410
411 def setcontext(context):
412 """Set this thread's context to context."""
413 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000414 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000415 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000416 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000417
418 def getcontext():
419 """Returns this thread's context.
420
421 If this thread does not yet have a context, returns
422 a new context and sets this thread's context.
423 New contexts are copies of DefaultContext.
424 """
425 try:
426 return threading.currentThread().__decimal_context__
427 except AttributeError:
428 context = Context()
429 threading.currentThread().__decimal_context__ = context
430 return context
431
432else:
433
434 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000435 if hasattr(local, '__decimal_context__'):
436 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000437
438 def getcontext(_local=local):
439 """Returns this thread's context.
440
441 If this thread does not yet have a context, returns
442 a new context and sets this thread's context.
443 New contexts are copies of DefaultContext.
444 """
445 try:
446 return _local.__decimal_context__
447 except AttributeError:
448 context = Context()
449 _local.__decimal_context__ = context
450 return context
451
452 def setcontext(context, _local=local):
453 """Set this thread's context to context."""
454 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000455 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000456 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000457 _local.__decimal_context__ = context
458
459 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000460
Thomas Wouters89f507f2006-12-13 04:49:30 +0000461def localcontext(ctx=None):
462 """Return a context manager for a copy of the supplied context
463
464 Uses a copy of the current context if no context is specified
465 The returned context manager creates a local decimal context
466 in a with statement:
467 def sin(x):
468 with localcontext() as ctx:
469 ctx.prec += 2
470 # Rest of sin calculation algorithm
471 # uses a precision 2 greater than normal
Guido van Rossumd8faa362007-04-27 19:54:29 +0000472 return +s # Convert result to normal precision
Thomas Wouters89f507f2006-12-13 04:49:30 +0000473
474 def sin(x):
475 with localcontext(ExtendedContext):
476 # Rest of sin calculation algorithm
477 # uses the Extended Context from the
478 # General Decimal Arithmetic Specification
Guido van Rossumd8faa362007-04-27 19:54:29 +0000479 return +s # Convert result to normal context
Thomas Wouters89f507f2006-12-13 04:49:30 +0000480
481 """
482 # The string below can't be included in the docstring until Python 2.6
483 # as the doctest module doesn't understand __future__ statements
484 """
485 >>> from __future__ import with_statement
Guido van Rossum7131f842007-02-09 20:13:25 +0000486 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000487 28
488 >>> with localcontext():
489 ... ctx = getcontext()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000490 ... ctx.prec += 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000491 ... print(ctx.prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000492 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000493 30
494 >>> with localcontext(ExtendedContext):
Guido van Rossum7131f842007-02-09 20:13:25 +0000495 ... print(getcontext().prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000496 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000497 9
Guido van Rossum7131f842007-02-09 20:13:25 +0000498 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000499 28
500 """
501 if ctx is None: ctx = getcontext()
502 return _ContextManager(ctx)
503
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000504
Guido van Rossumd8faa362007-04-27 19:54:29 +0000505##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000506
507class Decimal(object):
508 """Floating point class for decimal arithmetic."""
509
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000510 __slots__ = ('_exp','_int','_sign', '_is_special')
511 # Generally, the value of the Decimal instance is given by
512 # (-1)**_sign * _int * 10**_exp
513 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000514
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000515 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000516 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000517 """Create a decimal point instance.
518
519 >>> Decimal('3.14') # string input
520 Decimal("3.14")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000521 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000522 Decimal("3.14")
523 >>> Decimal(314) # int or long
524 Decimal("314")
525 >>> Decimal(Decimal(314)) # another decimal instance
526 Decimal("314")
527 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000528
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000529 self = object.__new__(cls)
530 self._is_special = False
531
532 # From an internal working value
533 if isinstance(value, _WorkRep):
Raymond Hettinger17931de2004-10-27 06:21:46 +0000534 self._sign = value.sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000535 self._int = tuple(map(int, str(value.int)))
536 self._exp = int(value.exp)
537 return self
538
539 # From another decimal
540 if isinstance(value, Decimal):
541 self._exp = value._exp
542 self._sign = value._sign
543 self._int = value._int
544 self._is_special = value._is_special
545 return self
546
547 # From an integer
Guido van Rossume2a383d2007-01-15 16:59:06 +0000548 if isinstance(value, (int,int)):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000549 if value >= 0:
550 self._sign = 0
551 else:
552 self._sign = 1
553 self._exp = 0
554 self._int = tuple(map(int, str(abs(value))))
555 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000556
557 # tuple/list conversion (possibly from as_tuple())
558 if isinstance(value, (list,tuple)):
559 if len(value) != 3:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000560 raise ValueError('Invalid arguments')
Raymond Hettingerdbecd932005-02-06 06:57:08 +0000561 if value[0] not in (0,1):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000562 raise ValueError('Invalid sign')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000563 for digit in value[1]:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000564 if not isinstance(digit, (int,int)) or digit < 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000565 raise ValueError("The second value in the tuple must be"
566 "composed of non negative integer elements.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000567 self._sign = value[0]
568 self._int = tuple(value[1])
569 if value[2] in ('F','n','N'):
570 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000571 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000572 else:
573 self._exp = int(value[2])
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000574 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000575
Raymond Hettingerbf440692004-07-10 14:14:37 +0000576 if isinstance(value, float):
577 raise TypeError("Cannot convert float to Decimal. " +
578 "First convert the float to a string")
579
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000580 # Other argument types may require the context during interpretation
581 if context is None:
582 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000583
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000584 # From a string
585 # REs insist on real strings, so we can too.
586 if isinstance(value, basestring):
587 if _isinfinity(value):
588 self._exp = 'F'
589 self._int = (0,)
590 self._is_special = True
591 if _isinfinity(value) == 1:
592 self._sign = 0
593 else:
594 self._sign = 1
595 return self
596 if _isnan(value):
597 sig, sign, diag = _isnan(value)
598 self._is_special = True
Guido van Rossumd8faa362007-04-27 19:54:29 +0000599 if len(diag) > context.prec: # Diagnostic info too long
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000600 self._sign, self._int, self._exp = \
601 context._raise_error(ConversionSyntax)
602 return self
603 if sig == 1:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000604 self._exp = 'n' # qNaN
605 else: # sig == 2
606 self._exp = 'N' # sNaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000607 self._sign = sign
Guido van Rossumd8faa362007-04-27 19:54:29 +0000608 self._int = tuple(map(int, diag)) # Diagnostic info
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000609 return self
610 try:
611 self._sign, self._int, self._exp = _string2exact(value)
612 except ValueError:
613 self._is_special = True
Guido van Rossumd8faa362007-04-27 19:54:29 +0000614 self._sign, self._int, self._exp = \
615 context._raise_error(ConversionSyntax)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000616 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000617
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000618 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000619
620 def _isnan(self):
621 """Returns whether the number is not actually one.
622
623 0 if a number
624 1 if NaN
625 2 if sNaN
626 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000627 if self._is_special:
628 exp = self._exp
629 if exp == 'n':
630 return 1
631 elif exp == 'N':
632 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000633 return 0
634
635 def _isinfinity(self):
636 """Returns whether the number is infinite
637
638 0 if finite or not a number
639 1 if +INF
640 -1 if -INF
641 """
642 if self._exp == 'F':
643 if self._sign:
644 return -1
645 return 1
646 return 0
647
648 def _check_nans(self, other = None, context=None):
649 """Returns whether the number is not actually one.
650
651 if self, other are sNaN, signal
652 if self, other are NaN return nan
653 return 0
654
655 Done before operations.
656 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000657
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000658 self_is_nan = self._isnan()
659 if other is None:
660 other_is_nan = False
661 else:
662 other_is_nan = other._isnan()
663
664 if self_is_nan or other_is_nan:
665 if context is None:
666 context = getcontext()
667
668 if self_is_nan == 2:
669 return context._raise_error(InvalidOperation, 'sNaN',
670 1, self)
671 if other_is_nan == 2:
672 return context._raise_error(InvalidOperation, 'sNaN',
673 1, other)
674 if self_is_nan:
675 return self
676
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000677 return other
678 return 0
679
Jack Diederich4dafcc42006-11-28 19:15:13 +0000680 def __bool__(self):
Jack Diederich030debb2006-11-28 22:22:22 +0000681 """return True if the number is non-zero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000682
Jack Diederich030debb2006-11-28 22:22:22 +0000683 False if self == 0
684 True if self != 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000685 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000686 if self._is_special:
Jack Diederich4dafcc42006-11-28 19:15:13 +0000687 return True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000688 return sum(self._int) != 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000689
690 def __cmp__(self, other, context=None):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000691 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000692 if other is NotImplemented:
693 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000694
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000695 if self._is_special or other._is_special:
696 ans = self._check_nans(other, context)
697 if ans:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000698 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000699
700 # INF = INF
701 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000702
703 if not self and not other:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000704 return 0 # If both 0, sign comparison isn't certain.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000705
Guido van Rossumd8faa362007-04-27 19:54:29 +0000706 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000707 if other._sign < self._sign:
708 return -1
709 if self._sign < other._sign:
710 return 1
711
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000712 self_adjusted = self.adjusted()
713 other_adjusted = other.adjusted()
714 if self_adjusted == other_adjusted and \
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000715 self._int + (0,)*(self._exp - other._exp) == \
716 other._int + (0,)*(other._exp - self._exp):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000717 return 0 # equal, except in precision. ([0]*(-x) = [])
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000718 elif self_adjusted > other_adjusted and self._int[0] != 0:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000719 return (-1)**self._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000720 elif self_adjusted < other_adjusted and other._int[0] != 0:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000721 return -((-1)**self._sign)
722
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000723 # Need to round, so make sure we have a valid context
724 if context is None:
725 context = getcontext()
726
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000727 context = context._shallow_copy()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000728 rounding = context._set_rounding(ROUND_UP) # round away from 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000729
730 flags = context._ignore_all_flags()
731 res = self.__sub__(other, context=context)
732
733 context._regard_flags(*flags)
734
735 context.rounding = rounding
736
737 if not res:
738 return 0
739 elif res._sign:
740 return -1
741 return 1
742
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000743 def __eq__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000744 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000745 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000746 return self.__cmp__(other) == 0
747
748 def __ne__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000749 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000750 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000751 return self.__cmp__(other) != 0
752
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000753 def __lt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000754 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000755 return NotImplemented
756 return self.__cmp__(other) < 0
757
758 def __le__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000759 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000760 return NotImplemented
761 return self.__cmp__(other) <= 0
762
763 def __gt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000764 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000765 return NotImplemented
766 return self.__cmp__(other) > 0
767
768 def __ge__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000769 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000770 return NotImplemented
771 return self.__cmp__(other) >= 0
772
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000773 def compare(self, other, context=None):
774 """Compares one to another.
775
776 -1 => a < b
777 0 => a = b
778 1 => a > b
779 NaN => one is NaN
780 Like __cmp__, but returns Decimal instances.
781 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000782 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000783 if other is NotImplemented:
784 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000785
Guido van Rossumd8faa362007-04-27 19:54:29 +0000786 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000787 if (self._is_special or other and other._is_special):
788 ans = self._check_nans(other, context)
789 if ans:
790 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000791
792 return Decimal(self.__cmp__(other, context))
793
794 def __hash__(self):
795 """x.__hash__() <==> hash(x)"""
796 # Decimal integers must hash the same as the ints
797 # Non-integer decimals are normalized and hashed as strings
Thomas Wouters477c8d52006-05-27 19:21:47 +0000798 # Normalization assures that hash(100E-1) == hash(10)
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000799 if self._is_special:
800 if self._isnan():
801 raise TypeError('Cannot hash a NaN value.')
802 return hash(str(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000803 i = int(self)
804 if self == Decimal(i):
805 return hash(i)
Jack Diederich4dafcc42006-11-28 19:15:13 +0000806 assert self.__bool__() # '-0' handled by integer case
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000807 return hash(str(self.normalize()))
808
809 def as_tuple(self):
810 """Represents the number as a triple tuple.
811
812 To show the internals exactly as they are.
813 """
814 return (self._sign, self._int, self._exp)
815
816 def __repr__(self):
817 """Represents the number as an instance of Decimal."""
818 # Invariant: eval(repr(d)) == d
819 return 'Decimal("%s")' % str(self)
820
821 def __str__(self, eng = 0, context=None):
822 """Return string representation of the number in scientific notation.
823
824 Captures all of the information in the underlying representation.
825 """
826
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000827 if self._is_special:
828 if self._isnan():
829 minus = '-'*self._sign
830 if self._int == (0,):
831 info = ''
832 else:
833 info = ''.join(map(str, self._int))
834 if self._isnan() == 2:
835 return minus + 'sNaN' + info
836 return minus + 'NaN' + info
837 if self._isinfinity():
838 minus = '-'*self._sign
839 return minus + 'Infinity'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000840
841 if context is None:
842 context = getcontext()
843
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000844 tmp = list(map(str, self._int))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000845 numdigits = len(self._int)
846 leftdigits = self._exp + numdigits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000847 if eng and not self: # self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
848 if self._exp < 0 and self._exp >= -6: # short, no need for e/E
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000849 s = '-'*self._sign + '0.' + '0'*(abs(self._exp))
850 return s
Guido van Rossumd8faa362007-04-27 19:54:29 +0000851 # exp is closest mult. of 3 >= self._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000852 exp = ((self._exp - 1)// 3 + 1) * 3
853 if exp != self._exp:
854 s = '0.'+'0'*(exp - self._exp)
855 else:
856 s = '0'
857 if exp != 0:
858 if context.capitals:
859 s += 'E'
860 else:
861 s += 'e'
862 if exp > 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000863 s += '+' # 0.0e+3, not 0.0e3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000864 s += str(exp)
865 s = '-'*self._sign + s
866 return s
867 if eng:
868 dotplace = (leftdigits-1)%3+1
869 adjexp = leftdigits -1 - (leftdigits-1)%3
870 else:
871 adjexp = leftdigits-1
872 dotplace = 1
873 if self._exp == 0:
874 pass
875 elif self._exp < 0 and adjexp >= 0:
876 tmp.insert(leftdigits, '.')
877 elif self._exp < 0 and adjexp >= -6:
878 tmp[0:0] = ['0'] * int(-leftdigits)
879 tmp.insert(0, '0.')
880 else:
881 if numdigits > dotplace:
882 tmp.insert(dotplace, '.')
883 elif numdigits < dotplace:
884 tmp.extend(['0']*(dotplace-numdigits))
885 if adjexp:
886 if not context.capitals:
887 tmp.append('e')
888 else:
889 tmp.append('E')
890 if adjexp > 0:
891 tmp.append('+')
892 tmp.append(str(adjexp))
893 if eng:
894 while tmp[0:1] == ['0']:
895 tmp[0:1] = []
896 if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e':
897 tmp[0:0] = ['0']
898 if self._sign:
899 tmp.insert(0, '-')
900
901 return ''.join(tmp)
902
903 def to_eng_string(self, context=None):
904 """Convert to engineering-type string.
905
906 Engineering notation has an exponent which is a multiple of 3, so there
907 are up to 3 digits left of the decimal place.
908
909 Same rules for when in exponential and when as a value as in __str__.
910 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000911 return self.__str__(eng=1, context=context)
912
913 def __neg__(self, context=None):
914 """Returns a copy with the sign switched.
915
916 Rounds, if it has reason.
917 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000918 if self._is_special:
919 ans = self._check_nans(context=context)
920 if ans:
921 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000922
923 if not self:
924 # -Decimal('0') is Decimal('0'), not Decimal('-0')
925 sign = 0
926 elif self._sign:
927 sign = 0
928 else:
929 sign = 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000930
931 if context is None:
932 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000933 if context._rounding_decision == ALWAYS_ROUND:
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000934 return Decimal((sign, self._int, self._exp))._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000935 return Decimal( (sign, self._int, self._exp))
936
937 def __pos__(self, context=None):
938 """Returns a copy, unless it is a sNaN.
939
940 Rounds the number (if more then precision digits)
941 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000942 if self._is_special:
943 ans = self._check_nans(context=context)
944 if ans:
945 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000946
947 sign = self._sign
948 if not self:
949 # + (-0) = 0
950 sign = 0
951
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000952 if context is None:
953 context = getcontext()
954
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000955 if context._rounding_decision == ALWAYS_ROUND:
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000956 ans = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000957 else:
958 ans = Decimal(self)
959 ans._sign = sign
960 return ans
961
962 def __abs__(self, round=1, context=None):
963 """Returns the absolute value of self.
964
965 If the second argument is 0, do not round.
966 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000967 if self._is_special:
968 ans = self._check_nans(context=context)
969 if ans:
970 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000971
972 if not round:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000973 if context is None:
974 context = getcontext()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000975 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000976 context._set_rounding_decision(NEVER_ROUND)
977
978 if self._sign:
979 ans = self.__neg__(context=context)
980 else:
981 ans = self.__pos__(context=context)
982
983 return ans
984
985 def __add__(self, other, context=None):
986 """Returns self + other.
987
988 -INF + INF (or the reverse) cause InvalidOperation errors.
989 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000990 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000991 if other is NotImplemented:
992 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000993
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000994 if context is None:
995 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000996
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000997 if self._is_special or other._is_special:
998 ans = self._check_nans(other, context)
999 if ans:
1000 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001001
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001002 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001003 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001004 if self._sign != other._sign and other._isinfinity():
1005 return context._raise_error(InvalidOperation, '-INF + INF')
1006 return Decimal(self)
1007 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001008 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001009
1010 shouldround = context._rounding_decision == ALWAYS_ROUND
1011
1012 exp = min(self._exp, other._exp)
1013 negativezero = 0
1014 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001015 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001016 negativezero = 1
1017
1018 if not self and not other:
1019 sign = min(self._sign, other._sign)
1020 if negativezero:
1021 sign = 1
1022 return Decimal( (sign, (0,), exp))
1023 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001024 exp = max(exp, other._exp - context.prec-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001025 ans = other._rescale(exp, watchexp=0, context=context)
1026 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001027 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001028 return ans
1029 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001030 exp = max(exp, self._exp - context.prec-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001031 ans = self._rescale(exp, watchexp=0, context=context)
1032 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001033 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001034 return ans
1035
1036 op1 = _WorkRep(self)
1037 op2 = _WorkRep(other)
1038 op1, op2 = _normalize(op1, op2, shouldround, context.prec)
1039
1040 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001041 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001042 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001043 if op1.int == op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001044 if exp < context.Etiny():
1045 exp = context.Etiny()
1046 context._raise_error(Clamped)
1047 return Decimal((negativezero, (0,), exp))
Raymond Hettinger17931de2004-10-27 06:21:46 +00001048 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001049 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001050 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001051 if op1.sign == 1:
1052 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001053 op1.sign, op2.sign = op2.sign, op1.sign
1054 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001055 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001056 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001057 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001058 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001059 op1.sign, op2.sign = (0, 0)
1060 else:
1061 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001062 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001063
Raymond Hettinger17931de2004-10-27 06:21:46 +00001064 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001065 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001066 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001067 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001068
1069 result.exp = op1.exp
1070 ans = Decimal(result)
1071 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001072 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001073 return ans
1074
1075 __radd__ = __add__
1076
1077 def __sub__(self, other, context=None):
1078 """Return self + (-other)"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001079 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001080 if other is NotImplemented:
1081 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001082
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001083 if self._is_special or other._is_special:
1084 ans = self._check_nans(other, context=context)
1085 if ans:
1086 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001087
1088 # -Decimal(0) = Decimal(0), which we don't want since
1089 # (-0 - 0 = -0 + (-0) = -0, but -0 + 0 = 0.)
1090 # so we change the sign directly to a copy
1091 tmp = Decimal(other)
1092 tmp._sign = 1-tmp._sign
1093
1094 return self.__add__(tmp, context=context)
1095
1096 def __rsub__(self, other, context=None):
1097 """Return other + (-self)"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001098 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001099 if other is NotImplemented:
1100 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001101
1102 tmp = Decimal(self)
1103 tmp._sign = 1 - tmp._sign
1104 return other.__add__(tmp, context=context)
1105
1106 def _increment(self, round=1, context=None):
1107 """Special case of add, adding 1eExponent
1108
1109 Since it is common, (rounding, for example) this adds
1110 (sign)*one E self._exp to the number more efficiently than add.
1111
1112 For example:
1113 Decimal('5.624e10')._increment() == Decimal('5.625e10')
1114 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001115 if self._is_special:
1116 ans = self._check_nans(context=context)
1117 if ans:
1118 return ans
1119
Guido van Rossumd8faa362007-04-27 19:54:29 +00001120 # Must be infinite, and incrementing makes no difference
1121 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001122
1123 L = list(self._int)
1124 L[-1] += 1
1125 spot = len(L)-1
1126 while L[spot] == 10:
1127 L[spot] = 0
1128 if spot == 0:
1129 L[0:0] = [1]
1130 break
1131 L[spot-1] += 1
1132 spot -= 1
1133 ans = Decimal((self._sign, L, self._exp))
1134
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001135 if context is None:
1136 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001137 if round and context._rounding_decision == ALWAYS_ROUND:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001138 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001139 return ans
1140
1141 def __mul__(self, other, context=None):
1142 """Return self * other.
1143
1144 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1145 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001146 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001147 if other is NotImplemented:
1148 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001149
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001150 if context is None:
1151 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001152
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001153 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001154
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001155 if self._is_special or other._is_special:
1156 ans = self._check_nans(other, context)
1157 if ans:
1158 return ans
1159
1160 if self._isinfinity():
1161 if not other:
1162 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1163 return Infsign[resultsign]
1164
1165 if other._isinfinity():
1166 if not self:
1167 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1168 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001169
1170 resultexp = self._exp + other._exp
1171 shouldround = context._rounding_decision == ALWAYS_ROUND
1172
1173 # Special case for multiplying by zero
1174 if not self or not other:
1175 ans = Decimal((resultsign, (0,), resultexp))
1176 if shouldround:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001177 # Fixing in case the exponent is out of bounds
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001178 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001179 return ans
1180
1181 # Special case for multiplying by power of 10
1182 if self._int == (1,):
1183 ans = Decimal((resultsign, other._int, resultexp))
1184 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001185 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001186 return ans
1187 if other._int == (1,):
1188 ans = Decimal((resultsign, self._int, resultexp))
1189 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001190 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001191 return ans
1192
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001193 op1 = _WorkRep(self)
1194 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001195
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001196 ans = Decimal((resultsign,
1197 tuple(map(int, str(op1.int * op2.int))),
1198 resultexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001199 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001200 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001201
1202 return ans
1203 __rmul__ = __mul__
1204
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001205 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001206 """Return self / other."""
1207 return self._divide(other, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001208
1209 def _divide(self, other, divmod = 0, context=None):
1210 """Return a / b, to context.prec precision.
1211
1212 divmod:
1213 0 => true division
1214 1 => (a //b, a%b)
1215 2 => a //b
1216 3 => a%b
1217
1218 Actually, if divmod is 2 or 3 a tuple is returned, but errors for
1219 computing the other value are not raised.
1220 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001221 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001222 if other is NotImplemented:
1223 if divmod in (0, 1):
1224 return NotImplemented
1225 return (NotImplemented, NotImplemented)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001226
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001227 if context is None:
1228 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001229
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001230 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001231
1232 if self._is_special or other._is_special:
1233 ans = self._check_nans(other, context)
1234 if ans:
1235 if divmod:
1236 return (ans, ans)
1237 return ans
1238
1239 if self._isinfinity() and other._isinfinity():
1240 if divmod:
1241 return (context._raise_error(InvalidOperation,
1242 '(+-)INF // (+-)INF'),
1243 context._raise_error(InvalidOperation,
1244 '(+-)INF % (+-)INF'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001245 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001246
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001247 if self._isinfinity():
1248 if divmod == 1:
1249 return (Infsign[sign],
1250 context._raise_error(InvalidOperation, 'INF % x'))
1251 elif divmod == 2:
1252 return (Infsign[sign], NaN)
1253 elif divmod == 3:
1254 return (Infsign[sign],
1255 context._raise_error(InvalidOperation, 'INF % x'))
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001256 return Infsign[sign]
1257
1258 if other._isinfinity():
1259 if divmod:
1260 return (Decimal((sign, (0,), 0)), Decimal(self))
1261 context._raise_error(Clamped, 'Division by infinity')
1262 return Decimal((sign, (0,), context.Etiny()))
1263
1264 # Special cases for zeroes
1265 if not self and not other:
1266 if divmod:
1267 return context._raise_error(DivisionUndefined, '0 / 0', 1)
1268 return context._raise_error(DivisionUndefined, '0 / 0')
1269
1270 if not self:
1271 if divmod:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001272 otherside = Decimal(self)
1273 otherside._exp = min(self._exp, other._exp)
1274 return (Decimal((sign, (0,), 0)), otherside)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001275 exp = self._exp - other._exp
1276 if exp < context.Etiny():
1277 exp = context.Etiny()
1278 context._raise_error(Clamped, '0e-x / y')
1279 if exp > context.Emax:
1280 exp = context.Emax
1281 context._raise_error(Clamped, '0e+x / y')
1282 return Decimal( (sign, (0,), exp) )
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001283
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001284 if not other:
1285 if divmod:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001286 return context._raise_error(DivisionByZero, 'divmod(x,0)',
1287 sign, 1)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001288 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001289
Guido van Rossumd8faa362007-04-27 19:54:29 +00001290 # OK, so neither = 0, INF or NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001291 shouldround = context._rounding_decision == ALWAYS_ROUND
1292
Guido van Rossumd8faa362007-04-27 19:54:29 +00001293 # If we're dividing into ints, and self < other, stop.
1294 # self.__abs__(0) does not round.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001295 if divmod and (self.__abs__(0, context) < other.__abs__(0, context)):
1296
1297 if divmod == 1 or divmod == 3:
1298 exp = min(self._exp, other._exp)
1299 ans2 = self._rescale(exp, context=context, watchexp=0)
1300 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001301 ans2 = ans2._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001302 return (Decimal( (sign, (0,), 0) ),
1303 ans2)
1304
1305 elif divmod == 2:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001306 # Don't round the mod part, if we don't need it.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001307 return (Decimal( (sign, (0,), 0) ), Decimal(self))
1308
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001309 op1 = _WorkRep(self)
1310 op2 = _WorkRep(other)
1311 op1, op2, adjust = _adjust_coefficients(op1, op2)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001312 res = _WorkRep( (sign, 0, (op1.exp - op2.exp)) )
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001313 if divmod and res.exp > context.prec + 1:
1314 return context._raise_error(DivisionImpossible)
1315
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001316 prec_limit = 10 ** context.prec
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001317 while 1:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001318 while op2.int <= op1.int:
1319 res.int += 1
1320 op1.int -= op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001321 if res.exp == 0 and divmod:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001322 if res.int >= prec_limit and shouldround:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001323 return context._raise_error(DivisionImpossible)
1324 otherside = Decimal(op1)
1325 frozen = context._ignore_all_flags()
1326
1327 exp = min(self._exp, other._exp)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001328 otherside = otherside._rescale(exp, context=context, watchexp=0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001329 context._regard_flags(*frozen)
1330 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001331 otherside = otherside._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001332 return (Decimal(res), otherside)
1333
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001334 if op1.int == 0 and adjust >= 0 and not divmod:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001335 break
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001336 if res.int >= prec_limit and shouldround:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001337 if divmod:
1338 return context._raise_error(DivisionImpossible)
1339 shouldround=1
1340 # Really, the answer is a bit higher, so adding a one to
1341 # the end will make sure the rounding is right.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001342 if op1.int != 0:
1343 res.int *= 10
1344 res.int += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001345 res.exp -= 1
1346
1347 break
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001348 res.int *= 10
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001349 res.exp -= 1
1350 adjust += 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001351 op1.int *= 10
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001352 op1.exp -= 1
1353
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001354 if res.exp == 0 and divmod and op2.int > op1.int:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001355 # Solves an error in precision. Same as a previous block.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001356
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001357 if res.int >= prec_limit and shouldround:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001358 return context._raise_error(DivisionImpossible)
1359 otherside = Decimal(op1)
1360 frozen = context._ignore_all_flags()
1361
1362 exp = min(self._exp, other._exp)
1363 otherside = otherside._rescale(exp, context=context)
1364
1365 context._regard_flags(*frozen)
1366
1367 return (Decimal(res), otherside)
1368
1369 ans = Decimal(res)
1370 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001371 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001372 return ans
1373
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001374 def __rtruediv__(self, other, context=None):
1375 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001376 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001377 if other is NotImplemented:
1378 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001379 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001380
1381 def __divmod__(self, other, context=None):
1382 """
1383 (self // other, self % other)
1384 """
1385 return self._divide(other, 1, context)
1386
1387 def __rdivmod__(self, other, context=None):
1388 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001389 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001390 if other is NotImplemented:
1391 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001392 return other.__divmod__(self, context=context)
1393
1394 def __mod__(self, other, context=None):
1395 """
1396 self % other
1397 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001398 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001399 if other is NotImplemented:
1400 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001401
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001402 if self._is_special or other._is_special:
1403 ans = self._check_nans(other, context)
1404 if ans:
1405 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001406
1407 if self and not other:
1408 return context._raise_error(InvalidOperation, 'x % 0')
1409
1410 return self._divide(other, 3, context)[1]
1411
1412 def __rmod__(self, other, context=None):
1413 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001414 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001415 if other is NotImplemented:
1416 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001417 return other.__mod__(self, context=context)
1418
1419 def remainder_near(self, other, context=None):
1420 """
1421 Remainder nearest to 0- abs(remainder-near) <= other/2
1422 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001423 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001424 if other is NotImplemented:
1425 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001426
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001427 if self._is_special or other._is_special:
1428 ans = self._check_nans(other, context)
1429 if ans:
1430 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001431 if self and not other:
1432 return context._raise_error(InvalidOperation, 'x % 0')
1433
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001434 if context is None:
1435 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001436 # If DivisionImpossible causes an error, do not leave Rounded/Inexact
1437 # ignored in the calling function.
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00001438 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001439 flags = context._ignore_flags(Rounded, Inexact)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001440 # Keep DivisionImpossible flags
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001441 (side, r) = self.__divmod__(other, context=context)
1442
1443 if r._isnan():
1444 context._regard_flags(*flags)
1445 return r
1446
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00001447 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001448 rounding = context._set_rounding_decision(NEVER_ROUND)
1449
1450 if other._sign:
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001451 comparison = other.__truediv__(Decimal(-2), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001452 else:
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001453 comparison = other.__truediv__(Decimal(2), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001454
1455 context._set_rounding_decision(rounding)
1456 context._regard_flags(*flags)
1457
1458 s1, s2 = r._sign, comparison._sign
1459 r._sign, comparison._sign = 0, 0
1460
1461 if r < comparison:
1462 r._sign, comparison._sign = s1, s2
Guido van Rossumd8faa362007-04-27 19:54:29 +00001463 # Get flags now
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001464 self.__divmod__(other, context=context)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001465 return r._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001466 r._sign, comparison._sign = s1, s2
1467
1468 rounding = context._set_rounding_decision(NEVER_ROUND)
1469
1470 (side, r) = self.__divmod__(other, context=context)
1471 context._set_rounding_decision(rounding)
1472 if r._isnan():
1473 return r
1474
1475 decrease = not side._iseven()
1476 rounding = context._set_rounding_decision(NEVER_ROUND)
1477 side = side.__abs__(context=context)
1478 context._set_rounding_decision(rounding)
1479
1480 s1, s2 = r._sign, comparison._sign
1481 r._sign, comparison._sign = 0, 0
1482 if r > comparison or decrease and r == comparison:
1483 r._sign, comparison._sign = s1, s2
1484 context.prec += 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001485 numbsquant = len(side.__add__(Decimal(1), context=context)._int)
1486 if numbsquant >= context.prec:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001487 context.prec -= 1
1488 return context._raise_error(DivisionImpossible)[1]
1489 context.prec -= 1
1490 if self._sign == other._sign:
1491 r = r.__sub__(other, context=context)
1492 else:
1493 r = r.__add__(other, context=context)
1494 else:
1495 r._sign, comparison._sign = s1, s2
1496
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001497 return r._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001498
1499 def __floordiv__(self, other, context=None):
1500 """self // other"""
1501 return self._divide(other, 2, context)[0]
1502
1503 def __rfloordiv__(self, other, context=None):
1504 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001505 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001506 if other is NotImplemented:
1507 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001508 return other.__floordiv__(self, context=context)
1509
1510 def __float__(self):
1511 """Float representation."""
1512 return float(str(self))
1513
1514 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001515 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001516 if self._is_special:
1517 if self._isnan():
1518 context = getcontext()
1519 return context._raise_error(InvalidContext)
1520 elif self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001521 raise OverflowError("Cannot convert infinity to long")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001522 if self._exp >= 0:
Raymond Hettinger605ed022004-11-24 07:28:48 +00001523 s = ''.join(map(str, self._int)) + '0'*self._exp
1524 else:
1525 s = ''.join(map(str, self._int))[:self._exp]
1526 if s == '':
1527 s = '0'
1528 sign = '-'*self._sign
1529 return int(sign + s)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001530
1531 def __long__(self):
1532 """Converts to a long.
1533
1534 Equivalent to long(int(self))
1535 """
Guido van Rossume2a383d2007-01-15 16:59:06 +00001536 return int(self.__int__())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001537
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001538 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001539 """Round if it is necessary to keep self within prec precision.
1540
1541 Rounds and fixes the exponent. Does not raise on a sNaN.
1542
1543 Arguments:
1544 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001545 context - context used.
1546 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001547 if self._is_special:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001548 return self
1549 if context is None:
1550 context = getcontext()
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001551 prec = context.prec
Facundo Batista99b55482004-10-26 23:38:46 +00001552 ans = self._fixexponents(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001553 if len(ans._int) > prec:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001554 ans = ans._round(prec, context=context)
Facundo Batista99b55482004-10-26 23:38:46 +00001555 ans = ans._fixexponents(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001556 return ans
1557
Facundo Batista99b55482004-10-26 23:38:46 +00001558 def _fixexponents(self, context):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001559 """Fix the exponents and return a copy with the exponent in bounds.
1560 Only call if known to not be a special value.
1561 """
1562 folddown = context._clamp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001563 Emin = context.Emin
Facundo Batista99b55482004-10-26 23:38:46 +00001564 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001565 ans_adjusted = ans.adjusted()
1566 if ans_adjusted < Emin:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001567 Etiny = context.Etiny()
1568 if ans._exp < Etiny:
1569 if not ans:
Facundo Batista99b55482004-10-26 23:38:46 +00001570 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001571 ans._exp = Etiny
1572 context._raise_error(Clamped)
1573 return ans
1574 ans = ans._rescale(Etiny, context=context)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001575 # It isn't zero, and exp < Emin => subnormal
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001576 context._raise_error(Subnormal)
1577 if context.flags[Inexact]:
1578 context._raise_error(Underflow)
1579 else:
1580 if ans:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001581 # Only raise subnormal if non-zero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001582 context._raise_error(Subnormal)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001583 else:
1584 Etop = context.Etop()
1585 if folddown and ans._exp > Etop:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001586 context._raise_error(Clamped)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001587 ans = ans._rescale(Etop, context=context)
1588 else:
1589 Emax = context.Emax
1590 if ans_adjusted > Emax:
1591 if not ans:
Facundo Batista99b55482004-10-26 23:38:46 +00001592 ans = Decimal(self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001593 ans._exp = Emax
1594 context._raise_error(Clamped)
1595 return ans
1596 context._raise_error(Inexact)
1597 context._raise_error(Rounded)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001598 c = context._raise_error(Overflow, 'above Emax', ans._sign)
1599 return c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001600 return ans
1601
1602 def _round(self, prec=None, rounding=None, context=None):
1603 """Returns a rounded version of self.
1604
1605 You can specify the precision or rounding method. Otherwise, the
1606 context determines it.
1607 """
1608
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001609 if self._is_special:
1610 ans = self._check_nans(context=context)
1611 if ans:
1612 return ans
1613
1614 if self._isinfinity():
1615 return Decimal(self)
1616
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001617 if context is None:
1618 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001619
1620 if rounding is None:
1621 rounding = context.rounding
1622 if prec is None:
1623 prec = context.prec
1624
1625 if not self:
1626 if prec <= 0:
1627 dig = (0,)
1628 exp = len(self._int) - prec + self._exp
1629 else:
1630 dig = (0,) * prec
1631 exp = len(self._int) + self._exp - prec
1632 ans = Decimal((self._sign, dig, exp))
1633 context._raise_error(Rounded)
1634 return ans
1635
1636 if prec == 0:
1637 temp = Decimal(self)
1638 temp._int = (0,)+temp._int
1639 prec = 1
1640 elif prec < 0:
1641 exp = self._exp + len(self._int) - prec - 1
1642 temp = Decimal( (self._sign, (0, 1), exp))
1643 prec = 1
1644 else:
1645 temp = Decimal(self)
1646
1647 numdigits = len(temp._int)
1648 if prec == numdigits:
1649 return temp
1650
1651 # See if we need to extend precision
1652 expdiff = prec - numdigits
1653 if expdiff > 0:
1654 tmp = list(temp._int)
1655 tmp.extend([0] * expdiff)
1656 ans = Decimal( (temp._sign, tmp, temp._exp - expdiff))
1657 return ans
1658
Guido van Rossumd8faa362007-04-27 19:54:29 +00001659 # OK, but maybe all the lost digits are 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001660 lostdigits = self._int[expdiff:]
1661 if lostdigits == (0,) * len(lostdigits):
1662 ans = Decimal( (temp._sign, temp._int[:prec], temp._exp - expdiff))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001663 # Rounded, but not Inexact
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001664 context._raise_error(Rounded)
1665 return ans
1666
1667 # Okay, let's round and lose data
1668
1669 this_function = getattr(temp, self._pick_rounding_function[rounding])
Guido van Rossumd8faa362007-04-27 19:54:29 +00001670 # Now we've got the rounding function
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001671
1672 if prec != context.prec:
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00001673 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001674 context.prec = prec
1675 ans = this_function(prec, expdiff, context)
1676 context._raise_error(Rounded)
1677 context._raise_error(Inexact, 'Changed in rounding')
1678
1679 return ans
1680
1681 _pick_rounding_function = {}
1682
1683 def _round_down(self, prec, expdiff, context):
1684 """Also known as round-towards-0, truncate."""
1685 return Decimal( (self._sign, self._int[:prec], self._exp - expdiff) )
1686
1687 def _round_half_up(self, prec, expdiff, context, tmp = None):
1688 """Rounds 5 up (away from 0)"""
1689
1690 if tmp is None:
1691 tmp = Decimal( (self._sign,self._int[:prec], self._exp - expdiff))
1692 if self._int[prec] >= 5:
1693 tmp = tmp._increment(round=0, context=context)
1694 if len(tmp._int) > prec:
1695 return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1))
1696 return tmp
1697
1698 def _round_half_even(self, prec, expdiff, context):
1699 """Round 5 to even, rest to nearest."""
1700
1701 tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff))
1702 half = (self._int[prec] == 5)
1703 if half:
1704 for digit in self._int[prec+1:]:
1705 if digit != 0:
1706 half = 0
1707 break
1708 if half:
Raymond Hettinger61992ef2004-08-06 23:42:16 +00001709 if self._int[prec-1] & 1 == 0:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001710 return tmp
1711 return self._round_half_up(prec, expdiff, context, tmp)
1712
1713 def _round_half_down(self, prec, expdiff, context):
1714 """Round 5 down"""
1715
1716 tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff))
1717 half = (self._int[prec] == 5)
1718 if half:
1719 for digit in self._int[prec+1:]:
1720 if digit != 0:
1721 half = 0
1722 break
1723 if half:
1724 return tmp
1725 return self._round_half_up(prec, expdiff, context, tmp)
1726
1727 def _round_up(self, prec, expdiff, context):
1728 """Rounds away from 0."""
1729 tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff) )
1730 for digit in self._int[prec:]:
1731 if digit != 0:
1732 tmp = tmp._increment(round=1, context=context)
1733 if len(tmp._int) > prec:
1734 return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1))
1735 else:
1736 return tmp
1737 return tmp
1738
1739 def _round_ceiling(self, prec, expdiff, context):
1740 """Rounds up (not away from 0 if negative.)"""
1741 if self._sign:
1742 return self._round_down(prec, expdiff, context)
1743 else:
1744 return self._round_up(prec, expdiff, context)
1745
1746 def _round_floor(self, prec, expdiff, context):
1747 """Rounds down (not towards 0 if negative)"""
1748 if not self._sign:
1749 return self._round_down(prec, expdiff, context)
1750 else:
1751 return self._round_up(prec, expdiff, context)
1752
1753 def __pow__(self, n, modulo = None, context=None):
1754 """Return self ** n (mod modulo)
1755
1756 If modulo is None (default), don't take it mod modulo.
1757 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001758 n = _convert_other(n)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001759 if n is NotImplemented:
1760 return n
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001761
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001762 if context is None:
1763 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001764
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001765 if self._is_special or n._is_special or n.adjusted() > 8:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001766 # Because the spot << doesn't work with really big exponents
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001767 if n._isinfinity() or n.adjusted() > 8:
1768 return context._raise_error(InvalidOperation, 'x ** INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001769
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001770 ans = self._check_nans(n, context)
1771 if ans:
1772 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001773
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001774 if not n._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001775 return context._raise_error(InvalidOperation, 'x ** (non-integer)')
1776
1777 if not self and not n:
1778 return context._raise_error(InvalidOperation, '0 ** 0')
1779
1780 if not n:
1781 return Decimal(1)
1782
1783 if self == Decimal(1):
1784 return Decimal(1)
1785
1786 sign = self._sign and not n._iseven()
1787 n = int(n)
1788
1789 if self._isinfinity():
1790 if modulo:
1791 return context._raise_error(InvalidOperation, 'INF % x')
1792 if n > 0:
1793 return Infsign[sign]
1794 return Decimal( (sign, (0,), 0) )
1795
Guido van Rossumd8faa362007-04-27 19:54:29 +00001796 # With ludicrously large exponent, just raise an overflow
1797 # and return inf.
1798 if not modulo and n > 0 and \
1799 (self._exp + len(self._int) - 1) * n > context.Emax and self:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001800
1801 tmp = Decimal('inf')
1802 tmp._sign = sign
1803 context._raise_error(Rounded)
1804 context._raise_error(Inexact)
1805 context._raise_error(Overflow, 'Big power', sign)
1806 return tmp
1807
1808 elength = len(str(abs(n)))
1809 firstprec = context.prec
1810
Raymond Hettinger99148e72004-07-14 19:56:56 +00001811 if not modulo and firstprec + elength + 1 > DefaultContext.Emax:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001812 return context._raise_error(Overflow, 'Too much precision.', sign)
1813
1814 mul = Decimal(self)
1815 val = Decimal(1)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00001816 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001817 context.prec = firstprec + elength + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001818 if n < 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001819 # n is a long now, not Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001820 n = -n
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001821 mul = Decimal(1).__truediv__(mul, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001822
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001823 spot = 1
1824 while spot <= n:
1825 spot <<= 1
1826
1827 spot >>= 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001828 # spot is the highest power of 2 less than n
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001829 while spot:
1830 val = val.__mul__(val, context=context)
1831 if val._isinfinity():
1832 val = Infsign[sign]
1833 break
1834 if spot & n:
1835 val = val.__mul__(mul, context=context)
1836 if modulo is not None:
1837 val = val.__mod__(modulo, context=context)
1838 spot >>= 1
1839 context.prec = firstprec
1840
Raymond Hettinger76e60d62004-10-20 06:58:28 +00001841 if context._rounding_decision == ALWAYS_ROUND:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001842 return val._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001843 return val
1844
1845 def __rpow__(self, other, context=None):
1846 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001847 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001848 if other is NotImplemented:
1849 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001850 return other.__pow__(self, context=context)
1851
1852 def normalize(self, context=None):
1853 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001854
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001855 if self._is_special:
1856 ans = self._check_nans(context=context)
1857 if ans:
1858 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001859
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001860 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001861 if dup._isinfinity():
1862 return dup
1863
1864 if not dup:
1865 return Decimal( (dup._sign, (0,), 0) )
1866 end = len(dup._int)
1867 exp = dup._exp
1868 while dup._int[end-1] == 0:
1869 exp += 1
1870 end -= 1
1871 return Decimal( (dup._sign, dup._int[:end], exp) )
1872
1873
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001874 def quantize(self, exp, rounding=None, context=None, watchexp=1):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001875 """Quantize self so its exponent is the same as that of exp.
1876
1877 Similar to self._rescale(exp._exp) but with error checking.
1878 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001879 if self._is_special or exp._is_special:
1880 ans = self._check_nans(exp, context)
1881 if ans:
1882 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001883
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001884 if exp._isinfinity() or self._isinfinity():
1885 if exp._isinfinity() and self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001886 return self # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001887 if context is None:
1888 context = getcontext()
1889 return context._raise_error(InvalidOperation,
1890 'quantize with one INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001891 return self._rescale(exp._exp, rounding, context, watchexp)
1892
1893 def same_quantum(self, other):
1894 """Test whether self and other have the same exponent.
1895
1896 same as self._exp == other._exp, except NaN == sNaN
1897 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001898 if self._is_special or other._is_special:
1899 if self._isnan() or other._isnan():
1900 return self._isnan() and other._isnan() and True
1901 if self._isinfinity() or other._isinfinity():
1902 return self._isinfinity() and other._isinfinity() and True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001903 return self._exp == other._exp
1904
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001905 def _rescale(self, exp, rounding=None, context=None, watchexp=1):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001906 """Rescales so that the exponent is exp.
1907
1908 exp = exp to scale to (an integer)
1909 rounding = rounding version
1910 watchexp: if set (default) an error is returned if exp is greater
1911 than Emax or less than Etiny.
1912 """
1913 if context is None:
1914 context = getcontext()
1915
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001916 if self._is_special:
1917 if self._isinfinity():
1918 return context._raise_error(InvalidOperation, 'rescale with an INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001919
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001920 ans = self._check_nans(context=context)
1921 if ans:
1922 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001923
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001924 if watchexp and (context.Emax < exp or context.Etiny() > exp):
1925 return context._raise_error(InvalidOperation, 'rescale(a, INF)')
1926
1927 if not self:
1928 ans = Decimal(self)
1929 ans._int = (0,)
1930 ans._exp = exp
1931 return ans
1932
1933 diff = self._exp - exp
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001934 digits = len(self._int) + diff
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001935
1936 if watchexp and digits > context.prec:
1937 return context._raise_error(InvalidOperation, 'Rescale > prec')
1938
1939 tmp = Decimal(self)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001940 tmp._int = (0,) + tmp._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001941 digits += 1
1942
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001943 if digits < 0:
1944 tmp._exp = -digits + tmp._exp
1945 tmp._int = (0,1)
1946 digits = 1
1947 tmp = tmp._round(digits, rounding, context=context)
1948
1949 if tmp._int[0] == 0 and len(tmp._int) > 1:
1950 tmp._int = tmp._int[1:]
1951 tmp._exp = exp
1952
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001953 tmp_adjusted = tmp.adjusted()
1954 if tmp and tmp_adjusted < context.Emin:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001955 context._raise_error(Subnormal)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001956 elif tmp and tmp_adjusted > context.Emax:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001957 return context._raise_error(InvalidOperation, 'rescale(a, INF)')
1958 return tmp
1959
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001960 def to_integral(self, rounding=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001961 """Rounds to the nearest integer, without raising inexact, rounded."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001962 if self._is_special:
1963 ans = self._check_nans(context=context)
1964 if ans:
1965 return ans
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001966 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001967 if self._exp >= 0:
1968 return self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001969 if context is None:
1970 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001971 flags = context._ignore_flags(Rounded, Inexact)
1972 ans = self._rescale(0, rounding, context=context)
1973 context._regard_flags(flags)
1974 return ans
1975
1976 def sqrt(self, context=None):
1977 """Return the square root of self.
1978
1979 Uses a converging algorithm (Xn+1 = 0.5*(Xn + self / Xn))
1980 Should quadratically approach the right answer.
1981 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001982 if self._is_special:
1983 ans = self._check_nans(context=context)
1984 if ans:
1985 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001986
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001987 if self._isinfinity() and self._sign == 0:
1988 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001989
1990 if not self:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001991 # exponent = self._exp / 2, using round_down.
1992 # if self._exp < 0:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001993 # exp = (self._exp+1) // 2
Guido van Rossumd8faa362007-04-27 19:54:29 +00001994 # else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001995 exp = (self._exp) // 2
1996 if self._sign == 1:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001997 # sqrt(-0) = -0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001998 return Decimal( (1, (0,), exp))
1999 else:
2000 return Decimal( (0, (0,), exp))
2001
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002002 if context is None:
2003 context = getcontext()
2004
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002005 if self._sign == 1:
2006 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2007
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002008 tmp = Decimal(self)
2009
Raymond Hettinger4837a222004-09-27 14:23:40 +00002010 expadd = tmp._exp // 2
Raymond Hettinger61992ef2004-08-06 23:42:16 +00002011 if tmp._exp & 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002012 tmp._int += (0,)
2013 tmp._exp = 0
2014 else:
2015 tmp._exp = 0
2016
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00002017 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002018 flags = context._ignore_all_flags()
2019 firstprec = context.prec
2020 context.prec = 3
Raymond Hettinger61992ef2004-08-06 23:42:16 +00002021 if tmp.adjusted() & 1 == 0:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002022 ans = Decimal( (0, (8,1,9), tmp.adjusted() - 2) )
2023 ans = ans.__add__(tmp.__mul__(Decimal((0, (2,5,9), -2)),
2024 context=context), context=context)
Raymond Hettinger4837a222004-09-27 14:23:40 +00002025 ans._exp -= 1 + tmp.adjusted() // 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002026 else:
2027 ans = Decimal( (0, (2,5,9), tmp._exp + len(tmp._int)- 3) )
2028 ans = ans.__add__(tmp.__mul__(Decimal((0, (8,1,9), -3)),
2029 context=context), context=context)
Raymond Hettinger4837a222004-09-27 14:23:40 +00002030 ans._exp -= 1 + tmp.adjusted() // 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002031
Guido van Rossumd8faa362007-04-27 19:54:29 +00002032 # ans is now a linear approximation.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002033 Emax, Emin = context.Emax, context.Emin
Raymond Hettinger99148e72004-07-14 19:56:56 +00002034 context.Emax, context.Emin = DefaultContext.Emax, DefaultContext.Emin
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002035
2036 half = Decimal('0.5')
2037
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002038 maxp = firstprec + 2
2039 rounding = context._set_rounding(ROUND_HALF_EVEN)
2040 while 1:
2041 context.prec = min(2*context.prec - 2, maxp)
Neal Norwitzbcc0db82006-03-24 08:14:36 +00002042 ans = half.__mul__(ans.__add__(tmp.__truediv__(ans, context=context),
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002043 context=context), context=context)
2044 if context.prec == maxp:
2045 break
2046
Guido van Rossumd8faa362007-04-27 19:54:29 +00002047 # Round to the answer's precision-- the only error can be 1 ulp.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002048 context.prec = firstprec
2049 prevexp = ans.adjusted()
2050 ans = ans._round(context=context)
2051
Guido van Rossumd8faa362007-04-27 19:54:29 +00002052 # Now, check if the other last digits are better.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002053 context.prec = firstprec + 1
2054 # In case we rounded up another digit and we should actually go lower.
2055 if prevexp != ans.adjusted():
2056 ans._int += (0,)
2057 ans._exp -= 1
2058
2059
2060 lower = ans.__sub__(Decimal((0, (5,), ans._exp-1)), context=context)
2061 context._set_rounding(ROUND_UP)
2062 if lower.__mul__(lower, context=context) > (tmp):
2063 ans = ans.__sub__(Decimal((0, (1,), ans._exp)), context=context)
2064
2065 else:
2066 upper = ans.__add__(Decimal((0, (5,), ans._exp-1)),context=context)
2067 context._set_rounding(ROUND_DOWN)
2068 if upper.__mul__(upper, context=context) < tmp:
2069 ans = ans.__add__(Decimal((0, (1,), ans._exp)),context=context)
2070
2071 ans._exp += expadd
2072
2073 context.prec = firstprec
2074 context.rounding = rounding
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002075 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002076
2077 rounding = context._set_rounding_decision(NEVER_ROUND)
2078 if not ans.__mul__(ans, context=context) == self:
2079 # Only rounded/inexact if here.
2080 context._regard_flags(flags)
2081 context._raise_error(Rounded)
2082 context._raise_error(Inexact)
2083 else:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002084 # Exact answer, so let's set the exponent right.
2085 # if self._exp < 0:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002086 # exp = (self._exp +1)// 2
Guido van Rossumd8faa362007-04-27 19:54:29 +00002087 # else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002088 exp = self._exp // 2
2089 context.prec += ans._exp - exp
2090 ans = ans._rescale(exp, context=context)
2091 context.prec = firstprec
2092 context._regard_flags(flags)
2093 context.Emax, context.Emin = Emax, Emin
2094
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002095 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002096
2097 def max(self, other, context=None):
2098 """Returns the larger value.
2099
2100 like max(self, other) except if one is not a number, returns
2101 NaN (and signals if one is sNaN). Also rounds.
2102 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002103 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002104 if other is NotImplemented:
2105 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002106
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002107 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002108 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002109 # number is always returned
2110 sn = self._isnan()
2111 on = other._isnan()
2112 if sn or on:
2113 if on == 1 and sn != 2:
2114 return self
2115 if sn == 1 and on != 2:
2116 return other
2117 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002118
2119 ans = self
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002120 c = self.__cmp__(other)
2121 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002122 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002123 # then an ordering is applied:
2124 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002125 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002126 # positive sign and min returns the operand with the negative sign
2127 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002128 # If the signs are the same then the exponent is used to select
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002129 # the result.
2130 if self._sign != other._sign:
2131 if self._sign:
2132 ans = other
2133 elif self._exp < other._exp and not self._sign:
2134 ans = other
2135 elif self._exp > other._exp and self._sign:
2136 ans = other
2137 elif c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002138 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002139
2140 if context is None:
2141 context = getcontext()
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002142 if context._rounding_decision == ALWAYS_ROUND:
2143 return ans._fix(context)
2144 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002145
2146 def min(self, other, context=None):
2147 """Returns the smaller value.
2148
Guido van Rossumd8faa362007-04-27 19:54:29 +00002149 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002150 NaN (and signals if one is sNaN). Also rounds.
2151 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002152 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002153 if other is NotImplemented:
2154 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002155
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002156 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002157 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002158 # number is always returned
2159 sn = self._isnan()
2160 on = other._isnan()
2161 if sn or on:
2162 if on == 1 and sn != 2:
2163 return self
2164 if sn == 1 and on != 2:
2165 return other
2166 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002167
2168 ans = self
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002169 c = self.__cmp__(other)
2170 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002171 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002172 # then an ordering is applied:
2173 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002174 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002175 # positive sign and min returns the operand with the negative sign
2176 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002177 # If the signs are the same then the exponent is used to select
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002178 # the result.
2179 if self._sign != other._sign:
2180 if other._sign:
2181 ans = other
2182 elif self._exp > other._exp and not self._sign:
2183 ans = other
2184 elif self._exp < other._exp and self._sign:
2185 ans = other
2186 elif c == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002187 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002188
2189 if context is None:
2190 context = getcontext()
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002191 if context._rounding_decision == ALWAYS_ROUND:
2192 return ans._fix(context)
2193 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002194
2195 def _isinteger(self):
2196 """Returns whether self is an integer"""
2197 if self._exp >= 0:
2198 return True
2199 rest = self._int[self._exp:]
2200 return rest == (0,)*len(rest)
2201
2202 def _iseven(self):
2203 """Returns 1 if self is even. Assumes self is an integer."""
2204 if self._exp > 0:
2205 return 1
Raymond Hettinger61992ef2004-08-06 23:42:16 +00002206 return self._int[-1+self._exp] & 1 == 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002207
2208 def adjusted(self):
2209 """Return the adjusted exponent of self"""
2210 try:
2211 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002212 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002213 except TypeError:
2214 return 0
2215
Guido van Rossumd8faa362007-04-27 19:54:29 +00002216 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002217 def __reduce__(self):
2218 return (self.__class__, (str(self),))
2219
2220 def __copy__(self):
2221 if type(self) == Decimal:
2222 return self # I'm immutable; therefore I am my own clone
2223 return self.__class__(str(self))
2224
2225 def __deepcopy__(self, memo):
2226 if type(self) == Decimal:
2227 return self # My components are also immutable
2228 return self.__class__(str(self))
2229
Guido van Rossumd8faa362007-04-27 19:54:29 +00002230##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00002231
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002232
2233# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002234rounding_functions = [name for name in Decimal.__dict__.keys()
2235 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002236for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002237 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002238 globalname = name[1:].upper()
2239 val = globals()[globalname]
2240 Decimal._pick_rounding_function[val] = name
2241
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002242del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002243
Thomas Wouters89f507f2006-12-13 04:49:30 +00002244class _ContextManager(object):
2245 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002246
Thomas Wouters89f507f2006-12-13 04:49:30 +00002247 Sets a copy of the supplied context in __enter__() and restores
2248 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002249 """
2250 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00002251 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002252 def __enter__(self):
2253 self.saved_context = getcontext()
2254 setcontext(self.new_context)
2255 return self.new_context
2256 def __exit__(self, t, v, tb):
2257 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00002258
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002259class Context(object):
2260 """Contains the context for a Decimal instance.
2261
2262 Contains:
2263 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002264 rounding - rounding type (how you round)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002265 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
Raymond Hettingerbf440692004-07-10 14:14:37 +00002266 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002267 raised when it is caused. Otherwise, a value is
2268 substituted in.
2269 flags - When an exception is caused, flags[exception] is incremented.
2270 (Whether or not the trap_enabler is set)
2271 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00002272 Emin - Minimum exponent
2273 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002274 capitals - If 1, 1*10^1 is printed as 1E+1.
2275 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00002276 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002277 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002278
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002279 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00002280 traps=None, flags=None,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002281 _rounding_decision=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00002282 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00002283 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00002284 _ignored_flags=None):
2285 if flags is None:
2286 flags = []
2287 if _ignored_flags is None:
2288 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00002289 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00002290 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00002291 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00002292 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002293 for name, val in locals().items():
2294 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00002295 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002296 else:
2297 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002298 del self.self
2299
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00002300 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00002301 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00002302 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00002303 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
2304 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
2305 % vars(self))
2306 names = [f.__name__ for f, v in self.flags.items() if v]
2307 s.append('flags=[' + ', '.join(names) + ']')
2308 names = [t.__name__ for t, v in self.traps.items() if v]
2309 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00002310 return ', '.join(s) + ')'
2311
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00002312 def clear_flags(self):
2313 """Reset all flags to zero"""
2314 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00002315 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00002316
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00002317 def _shallow_copy(self):
2318 """Returns a shallow copy from self."""
Raymond Hettingerbf440692004-07-10 14:14:37 +00002319 nc = Context(self.prec, self.rounding, self.traps, self.flags,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002320 self._rounding_decision, self.Emin, self.Emax,
2321 self.capitals, self._clamp, self._ignored_flags)
2322 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00002323
2324 def copy(self):
2325 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00002326 nc = Context(self.prec, self.rounding, self.traps.copy(),
2327 self.flags.copy(), self._rounding_decision, self.Emin,
2328 self.Emax, self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00002329 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002330 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002331
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00002332 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002333 """Handles an error
2334
2335 If the flag is in _ignored_flags, returns the default response.
2336 Otherwise, it increments the flag, then, if the corresponding
2337 trap_enabler is set, it reaises the exception. Otherwise, it returns
2338 the default value after incrementing the flag.
2339 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00002340 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002341 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002342 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002343 return error().handle(self, *args)
2344
2345 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00002346 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002347 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00002348 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002349
2350 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00002351 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002352 raise error, explanation
2353
2354 def _ignore_all_flags(self):
2355 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00002356 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002357
2358 def _ignore_flags(self, *flags):
2359 """Ignore the flags, if they are raised"""
2360 # Do not mutate-- This way, copies of a context leave the original
2361 # alone.
2362 self._ignored_flags = (self._ignored_flags + list(flags))
2363 return list(flags)
2364
2365 def _regard_flags(self, *flags):
2366 """Stop ignoring the flags, if they are raised"""
2367 if flags and isinstance(flags[0], (tuple,list)):
2368 flags = flags[0]
2369 for flag in flags:
2370 self._ignored_flags.remove(flag)
2371
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00002372 def __hash__(self):
2373 """A Context cannot be hashed."""
2374 # We inherit object.__hash__, so we must deny this explicitly
Guido van Rossumd8faa362007-04-27 19:54:29 +00002375 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00002376
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002377 def Etiny(self):
2378 """Returns Etiny (= Emin - prec + 1)"""
2379 return int(self.Emin - self.prec + 1)
2380
2381 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00002382 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002383 return int(self.Emax - self.prec + 1)
2384
2385 def _set_rounding_decision(self, type):
2386 """Sets the rounding decision.
2387
2388 Sets the rounding decision, and returns the current (previous)
2389 rounding decision. Often used like:
2390
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00002391 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002392 # That so you don't change the calling context
2393 # if an error occurs in the middle (say DivisionImpossible is raised).
2394
2395 rounding = context._set_rounding_decision(NEVER_ROUND)
2396 instance = instance / Decimal(2)
2397 context._set_rounding_decision(rounding)
2398
2399 This will make it not round for that operation.
2400 """
2401
2402 rounding = self._rounding_decision
2403 self._rounding_decision = type
2404 return rounding
2405
2406 def _set_rounding(self, type):
2407 """Sets the rounding type.
2408
2409 Sets the rounding type, and returns the current (previous)
2410 rounding type. Often used like:
2411
2412 context = context.copy()
2413 # so you don't change the calling context
2414 # if an error occurs in the middle.
2415 rounding = context._set_rounding(ROUND_UP)
2416 val = self.__sub__(other, context=context)
2417 context._set_rounding(rounding)
2418
2419 This will make it round up for that operation.
2420 """
2421 rounding = self.rounding
2422 self.rounding= type
2423 return rounding
2424
Raymond Hettingerfed52962004-07-14 15:41:57 +00002425 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002426 """Creates a new Decimal instance but using self as context."""
2427 d = Decimal(num, context=self)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002428 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002429
Guido van Rossumd8faa362007-04-27 19:54:29 +00002430 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002431 def abs(self, a):
2432 """Returns the absolute value of the operand.
2433
2434 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00002435 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002436 the plus operation on the operand.
2437
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002438 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002439 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002440 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002441 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002442 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002443 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002444 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002445 Decimal("101.5")
2446 """
2447 return a.__abs__(context=self)
2448
2449 def add(self, a, b):
2450 """Return the sum of the two operands.
2451
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002452 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002453 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002454 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002455 Decimal("1.02E+4")
2456 """
2457 return a.__add__(b, context=self)
2458
2459 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002460 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002461
2462 def compare(self, a, b):
2463 """Compares values numerically.
2464
2465 If the signs of the operands differ, a value representing each operand
2466 ('-1' if the operand is less than zero, '0' if the operand is zero or
2467 negative zero, or '1' if the operand is greater than zero) is used in
2468 place of that operand for the comparison instead of the actual
2469 operand.
2470
2471 The comparison is then effected by subtracting the second operand from
2472 the first and then returning a value according to the result of the
2473 subtraction: '-1' if the result is less than zero, '0' if the result is
2474 zero or negative zero, or '1' if the result is greater than zero.
2475
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002476 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002477 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002478 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002479 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002480 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002481 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002482 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002483 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002484 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002485 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002486 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002487 Decimal("-1")
2488 """
2489 return a.compare(b, context=self)
2490
2491 def divide(self, a, b):
2492 """Decimal division in a specified context.
2493
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002494 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002495 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002496 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002497 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002498 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002499 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002500 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002501 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002502 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002503 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002504 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002505 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002506 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002507 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002508 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002509 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002510 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002511 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002512 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002513 Decimal("1.20E+6")
2514 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00002515 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002516
2517 def divide_int(self, a, b):
2518 """Divides two numbers and returns the integer part of the result.
2519
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002520 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002521 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002522 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002523 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002524 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002525 Decimal("3")
2526 """
2527 return a.__floordiv__(b, context=self)
2528
2529 def divmod(self, a, b):
2530 return a.__divmod__(b, context=self)
2531
2532 def max(self, a,b):
2533 """max compares two values numerically and returns the maximum.
2534
2535 If either operand is a NaN then the general rules apply.
2536 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00002537 operation. If they are numerically equal then the left-hand operand
2538 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002539 infinity) of the two operands is chosen as the result.
2540
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002541 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002542 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002543 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002544 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002545 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002546 Decimal("1")
2547 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
2548 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002549 """
2550 return a.max(b, context=self)
2551
2552 def min(self, a,b):
2553 """min compares two values numerically and returns the minimum.
2554
2555 If either operand is a NaN then the general rules apply.
2556 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00002557 operation. If they are numerically equal then the left-hand operand
2558 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002559 infinity) of the two operands is chosen as the result.
2560
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002561 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002562 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002563 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002564 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002565 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002566 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002567 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
2568 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002569 """
2570 return a.min(b, context=self)
2571
2572 def minus(self, a):
2573 """Minus corresponds to unary prefix minus in Python.
2574
2575 The operation is evaluated using the same rules as subtract; the
2576 operation minus(a) is calculated as subtract('0', a) where the '0'
2577 has the same exponent as the operand.
2578
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002579 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002580 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002581 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002582 Decimal("1.3")
2583 """
2584 return a.__neg__(context=self)
2585
2586 def multiply(self, a, b):
2587 """multiply multiplies two operands.
2588
2589 If either operand is a special value then the general rules apply.
2590 Otherwise, the operands are multiplied together ('long multiplication'),
2591 resulting in a number which may be as long as the sum of the lengths
2592 of the two operands.
2593
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002594 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002595 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002596 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002597 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002598 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002599 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002600 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002601 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002602 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002603 Decimal("4.28135971E+11")
2604 """
2605 return a.__mul__(b, context=self)
2606
2607 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00002608 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002609
2610 Essentially a plus operation with all trailing zeros removed from the
2611 result.
2612
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002613 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002614 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002615 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002616 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002617 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002618 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002619 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002620 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002621 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002622 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002623 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002624 Decimal("0")
2625 """
2626 return a.normalize(context=self)
2627
2628 def plus(self, a):
2629 """Plus corresponds to unary prefix plus in Python.
2630
2631 The operation is evaluated using the same rules as add; the
2632 operation plus(a) is calculated as add('0', a) where the '0'
2633 has the same exponent as the operand.
2634
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002635 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002636 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002637 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002638 Decimal("-1.3")
2639 """
2640 return a.__pos__(context=self)
2641
2642 def power(self, a, b, modulo=None):
2643 """Raises a to the power of b, to modulo if given.
2644
2645 The right-hand operand must be a whole number whose integer part (after
2646 any exponent has been applied) has no more than 9 digits and whose
Guido van Rossumd8faa362007-04-27 19:54:29 +00002647 fractional part (if any) is all zeros before any rounding. The operand
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002648 may be positive, negative, or zero; if negative, the absolute value of
2649 the power is used, and the left-hand operand is inverted (divided into
2650 1) before use.
2651
2652 If the increased precision needed for the intermediate calculations
Guido van Rossumd8faa362007-04-27 19:54:29 +00002653 exceeds the capabilities of the implementation then an Invalid
2654 operation condition is raised.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002655
2656 If, when raising to a negative power, an underflow occurs during the
2657 division into 1, the operation is not halted at that point but
2658 continues.
2659
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002660 >>> ExtendedContext.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002661 Decimal("8")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002662 >>> ExtendedContext.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002663 Decimal("0.125")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002664 >>> ExtendedContext.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002665 Decimal("69.7575744")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002666 >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002667 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002668 >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002669 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002670 >>> ExtendedContext.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002671 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002672 >>> ExtendedContext.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002673 Decimal("Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002674 >>> ExtendedContext.power(Decimal('Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002675 Decimal("Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002676 >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002677 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002678 >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002679 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002680 >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002681 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002682 >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002683 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002684 >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002685 Decimal("Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002686 >>> ExtendedContext.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002687 Decimal("NaN")
2688 """
2689 return a.__pow__(b, modulo, context=self)
2690
2691 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002692 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002693
2694 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00002695 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002696 exponent is being increased), multiplied by a positive power of ten (if
2697 the exponent is being decreased), or is unchanged (if the exponent is
2698 already equal to that of the right-hand operand).
2699
2700 Unlike other operations, if the length of the coefficient after the
2701 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00002702 operation condition is raised. This guarantees that, unless there is
2703 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002704 equal to that of the right-hand operand.
2705
2706 Also unlike other operations, quantize will never raise Underflow, even
2707 if the result is subnormal and inexact.
2708
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002709 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002710 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002711 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002712 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002713 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002714 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002715 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002716 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002717 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002718 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002719 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002720 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002721 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002722 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002723 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002724 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002725 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002726 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002727 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002728 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002729 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002730 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002731 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002732 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002733 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002734 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002735 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002736 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002737 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002738 Decimal("2E+2")
2739 """
2740 return a.quantize(b, context=self)
2741
2742 def remainder(self, a, b):
2743 """Returns the remainder from integer division.
2744
2745 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00002746 calculating integer division as described for divide-integer, rounded
2747 to precision digits if necessary. The sign of the result, if
2748 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002749
2750 This operation will fail under the same conditions as integer division
2751 (that is, if integer division on the same two operands would fail, the
2752 remainder cannot be calculated).
2753
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002754 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002755 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002756 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002757 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002758 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002759 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002760 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002761 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002762 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002763 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002764 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002765 Decimal("1.0")
2766 """
2767 return a.__mod__(b, context=self)
2768
2769 def remainder_near(self, a, b):
2770 """Returns to be "a - b * n", where n is the integer nearest the exact
2771 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00002772 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002773 sign of a.
2774
2775 This operation will fail under the same conditions as integer division
2776 (that is, if integer division on the same two operands would fail, the
2777 remainder cannot be calculated).
2778
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002779 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002780 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002781 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002782 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002783 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002784 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002785 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002786 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002787 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002788 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002789 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002790 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002791 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002792 Decimal("-0.3")
2793 """
2794 return a.remainder_near(b, context=self)
2795
2796 def same_quantum(self, a, b):
2797 """Returns True if the two operands have the same exponent.
2798
2799 The result is never affected by either the sign or the coefficient of
2800 either operand.
2801
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002802 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002803 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002804 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002805 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002806 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002807 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002808 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002809 True
2810 """
2811 return a.same_quantum(b)
2812
2813 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002814 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002815
2816 If the result must be inexact, it is rounded using the round-half-even
2817 algorithm.
2818
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002819 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002820 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002821 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002822 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002823 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002824 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002825 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002826 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002827 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002828 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002829 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002830 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002831 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002832 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002833 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002834 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002835 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002836 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002837 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00002838 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002839 """
2840 return a.sqrt(context=self)
2841
2842 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00002843 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002844
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002845 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002846 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002847 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002848 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002849 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002850 Decimal("-0.77")
2851 """
2852 return a.__sub__(b, context=self)
2853
2854 def to_eng_string(self, a):
2855 """Converts a number to a string, using scientific notation.
2856
2857 The operation is not affected by the context.
2858 """
2859 return a.to_eng_string(context=self)
2860
2861 def to_sci_string(self, a):
2862 """Converts a number to a string, using scientific notation.
2863
2864 The operation is not affected by the context.
2865 """
2866 return a.__str__(context=self)
2867
2868 def to_integral(self, a):
2869 """Rounds to an integer.
2870
2871 When the operand has a negative exponent, the result is the same
2872 as using the quantize() operation using the given operand as the
2873 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
2874 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00002875 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002876
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002877 >>> ExtendedContext.to_integral(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002878 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002879 >>> ExtendedContext.to_integral(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002880 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002881 >>> ExtendedContext.to_integral(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002882 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002883 >>> ExtendedContext.to_integral(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002884 Decimal("102")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002885 >>> ExtendedContext.to_integral(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002886 Decimal("-102")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002887 >>> ExtendedContext.to_integral(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002888 Decimal("1.0E+6")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002889 >>> ExtendedContext.to_integral(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002890 Decimal("7.89E+77")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00002891 >>> ExtendedContext.to_integral(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002892 Decimal("-Infinity")
2893 """
2894 return a.to_integral(context=self)
2895
2896class _WorkRep(object):
2897 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00002898 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002899 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002900 # exp: None, int, or string
2901
2902 def __init__(self, value=None):
2903 if value is None:
2904 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002905 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002906 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00002907 elif isinstance(value, Decimal):
2908 self.sign = value._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002909 cum = 0
Raymond Hettinger17931de2004-10-27 06:21:46 +00002910 for digit in value._int:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002911 cum = cum * 10 + digit
2912 self.int = cum
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002913 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00002914 else:
2915 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002916 self.sign = value[0]
2917 self.int = value[1]
2918 self.exp = value[2]
2919
2920 def __repr__(self):
2921 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
2922
2923 __str__ = __repr__
2924
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002925
2926
2927def _normalize(op1, op2, shouldround = 0, prec = 0):
2928 """Normalizes op1, op2 to have the same exp and length of coefficient.
2929
2930 Done during addition.
2931 """
2932 # Yes, the exponent is a long, but the difference between exponents
2933 # must be an int-- otherwise you'd get a big memory problem.
2934 numdigits = int(op1.exp - op2.exp)
2935 if numdigits < 0:
2936 numdigits = -numdigits
2937 tmp = op2
2938 other = op1
2939 else:
2940 tmp = op1
2941 other = op2
2942
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002943
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002944 if shouldround and numdigits > prec + 1:
2945 # Big difference in exponents - check the adjusted exponents
2946 tmp_len = len(str(tmp.int))
2947 other_len = len(str(other.int))
2948 if numdigits > (other_len + prec + 1 - tmp_len):
2949 # If the difference in adjusted exps is > prec+1, we know
Guido van Rossumd8faa362007-04-27 19:54:29 +00002950 # other is insignificant, so might as well put a 1 after the
2951 # precision (since this is only for addition). Also stops
2952 # use of massive longs.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002953
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002954 extend = prec + 2 - tmp_len
2955 if extend <= 0:
2956 extend = 1
2957 tmp.int *= 10 ** extend
2958 tmp.exp -= extend
2959 other.int = 1
2960 other.exp = tmp.exp
2961 return op1, op2
2962
2963 tmp.int *= 10 ** numdigits
2964 tmp.exp -= numdigits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002965 return op1, op2
2966
2967def _adjust_coefficients(op1, op2):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002968 """Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002969
2970 Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp.
2971
2972 Used on _WorkRep instances during division.
2973 """
2974 adjust = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00002975 # If op1 is smaller, make it larger
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002976 while op2.int > op1.int:
2977 op1.int *= 10
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002978 op1.exp -= 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002979 adjust += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002980
Guido van Rossumd8faa362007-04-27 19:54:29 +00002981 # If op2 is too small, make it larger
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002982 while op1.int >= (10 * op2.int):
2983 op2.int *= 10
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002984 op2.exp -= 1
2985 adjust -= 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002986
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002987 return op1, op2, adjust
2988
Guido van Rossumd8faa362007-04-27 19:54:29 +00002989##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002990
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002991def _convert_other(other):
2992 """Convert other to Decimal.
2993
2994 Verifies that it's ok to use in an implicit construction.
2995 """
2996 if isinstance(other, Decimal):
2997 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00002998 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002999 return Decimal(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00003000 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00003001
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003002_infinity_map = {
3003 'inf' : 1,
3004 'infinity' : 1,
3005 '+inf' : 1,
3006 '+infinity' : 1,
3007 '-inf' : -1,
3008 '-infinity' : -1
3009}
3010
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003011def _isinfinity(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003012 """Determines whether a string or float is infinity.
3013
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003014 +1 for negative infinity; 0 for finite ; +1 for positive infinity
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003015 """
3016 num = str(num).lower()
3017 return _infinity_map.get(num, 0)
3018
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003019def _isnan(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003020 """Determines whether a string or float is NaN
3021
3022 (1, sign, diagnostic info as string) => NaN
3023 (2, sign, diagnostic info as string) => sNaN
3024 0 => not a NaN
3025 """
3026 num = str(num).lower()
3027 if not num:
3028 return 0
3029
Guido van Rossumd8faa362007-04-27 19:54:29 +00003030 # Get the sign, get rid of trailing [+-]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003031 sign = 0
3032 if num[0] == '+':
3033 num = num[1:]
Guido van Rossumd8faa362007-04-27 19:54:29 +00003034 elif num[0] == '-': # elif avoids '+-nan'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003035 num = num[1:]
3036 sign = 1
3037
3038 if num.startswith('nan'):
Guido van Rossumd8faa362007-04-27 19:54:29 +00003039 if len(num) > 3 and not num[3:].isdigit(): # diagnostic info
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003040 return 0
3041 return (1, sign, num[3:].lstrip('0'))
3042 if num.startswith('snan'):
3043 if len(num) > 4 and not num[4:].isdigit():
3044 return 0
3045 return (2, sign, num[4:].lstrip('0'))
3046 return 0
3047
3048
Guido van Rossumd8faa362007-04-27 19:54:29 +00003049##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003050
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003051# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00003052# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003053
3054DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00003055 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00003056 traps=[DivisionByZero, Overflow, InvalidOperation],
3057 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003058 _rounding_decision=ALWAYS_ROUND,
Raymond Hettinger99148e72004-07-14 19:56:56 +00003059 Emax=999999999,
3060 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003061 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003062)
3063
3064# Pre-made alternate contexts offered by the specification
3065# Don't change these; the user should be able to select these
3066# contexts and be able to reproduce results from other implementations
3067# of the spec.
3068
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003069BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003070 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00003071 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
3072 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003073)
3074
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003075ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00003076 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00003077 traps=[],
3078 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003079)
3080
3081
Guido van Rossumd8faa362007-04-27 19:54:29 +00003082##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003083
Guido van Rossumd8faa362007-04-27 19:54:29 +00003084# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003085Inf = Decimal('Inf')
3086negInf = Decimal('-Inf')
3087
Guido van Rossumd8faa362007-04-27 19:54:29 +00003088# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003089Infsign = (Inf, negInf)
3090
3091NaN = Decimal('NaN')
3092
3093
Guido van Rossumd8faa362007-04-27 19:54:29 +00003094##### crud for parsing strings #############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003095import re
3096
3097# There's an optional sign at the start, and an optional exponent
3098# at the end. The exponent has an optional sign and at least one
3099# digit. In between, must have either at least one digit followed
3100# by an optional fraction, or a decimal point followed by at least
3101# one digit. Yuck.
3102
3103_parser = re.compile(r"""
3104# \s*
3105 (?P<sign>[-+])?
3106 (
3107 (?P<int>\d+) (\. (?P<frac>\d*))?
3108 |
3109 \. (?P<onlyfrac>\d+)
3110 )
3111 ([eE](?P<exp>[-+]? \d+))?
3112# \s*
3113 $
Guido van Rossumd8faa362007-04-27 19:54:29 +00003114""", re.VERBOSE).match # Uncomment the \s* to allow leading or trailing spaces.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003115
3116del re
3117
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003118def _string2exact(s):
Guido van Rossumd8faa362007-04-27 19:54:29 +00003119 """Return sign, n, p s.t.
3120
3121 Float string value == -1**sign * n * 10**p exactly
3122 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003123 m = _parser(s)
3124 if m is None:
3125 raise ValueError("invalid literal for Decimal: %r" % s)
3126
3127 if m.group('sign') == "-":
3128 sign = 1
3129 else:
3130 sign = 0
3131
3132 exp = m.group('exp')
3133 if exp is None:
3134 exp = 0
3135 else:
3136 exp = int(exp)
3137
3138 intpart = m.group('int')
3139 if intpart is None:
3140 intpart = ""
3141 fracpart = m.group('onlyfrac')
3142 else:
3143 fracpart = m.group('frac')
3144 if fracpart is None:
3145 fracpart = ""
3146
3147 exp -= len(fracpart)
3148
3149 mantissa = intpart + fracpart
Guido van Rossumc1f779c2007-07-03 08:25:58 +00003150 tmp = list(map(int, mantissa))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003151 backup = tmp
3152 while tmp and tmp[0] == 0:
3153 del tmp[0]
3154
3155 # It's a zero
3156 if not tmp:
3157 if backup:
3158 return (sign, tuple(backup), exp)
3159 return (sign, (0,), exp)
3160 mantissa = tuple(tmp)
3161
3162 return (sign, mantissa, exp)
3163
3164
3165if __name__ == '__main__':
3166 import doctest, sys
3167 doctest.testmod(sys.modules[__name__])