blob: 6481d6c3f293d948ba67858944d5b052a534218b [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
Facundo Batista59c58842007-04-10 12:58:45 +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)
59>>> print dig / Decimal(3)
600.333333333
61>>> getcontext().prec = 18
62>>> print dig / Decimal(3)
630.333333333333333333
64>>> print dig.sqrt()
651
66>>> print Decimal(3).sqrt()
671.73205080756887729
68>>> print Decimal(3) ** 123
694.85192780976896427E+58
70>>> inf = Decimal(1) / Decimal(0)
71>>> print inf
72Infinity
73>>> neginf = Decimal(-1) / Decimal(0)
74>>> print neginf
75-Infinity
76>>> print neginf + inf
77NaN
78>>> print neginf * inf
79-Infinity
80>>> print dig / 0
81Infinity
Raymond Hettingerbf440692004-07-10 14:14:37 +000082>>> getcontext().traps[DivisionByZero] = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000083>>> print dig / 0
84Traceback (most recent call last):
85 ...
86 ...
87 ...
88DivisionByZero: x / 0
89>>> c = Context()
Raymond Hettingerbf440692004-07-10 14:14:37 +000090>>> c.traps[InvalidOperation] = 0
Raymond Hettinger5aa478b2004-07-09 10:02:53 +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
Raymond Hettinger5aa478b2004-07-09 10:02:53 +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
99>>> print c.flags[InvalidOperation]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000
101>>> print c.divide(Decimal(0), Decimal(0))
102Traceback (most recent call last):
103 ...
104 ...
105 ...
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000106InvalidOperation: 0 / 0
107>>> 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
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000111>>> print c.divide(Decimal(0), Decimal(0))
112NaN
Raymond Hettinger5aa478b2004-07-09 10:02:53 +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',
Facundo Batista353750c2007-09-13 18:13:15 +0000131 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000132
133 # Functions for manipulating contexts
Nick Coghlan8b6999b2006-08-31 12:00:43 +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
Facundo Batista59c58842007-04-10 12:58:45 +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'
Facundo Batista353750c2007-09-13 18:13:15 +0000147ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000148
Facundo Batista59c58842007-04-10 12:58:45 +0000149# Rounding decision (not part of the public API)
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000150NEVER_ROUND = 'NEVER_ROUND' # Round in division (non-divmod), sqrt ONLY
151ALWAYS_ROUND = 'ALWAYS_ROUND' # Every operation rounds at end.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000152
Facundo Batista59c58842007-04-10 12:58:45 +0000153# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000154
155class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000156 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000157
158 Used exceptions derive from this.
159 If an exception derives from another exception besides this (such as
160 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
161 called if the others are present. This isn't actually used for
162 anything, though.
163
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000164 handle -- Called when context._raise_error is called and the
165 trap_enabler is set. First argument is self, second is the
166 context. More arguments can be given, those being after
167 the explanation in _raise_error (For example,
168 context._raise_error(NewError, '(-x)!', self._sign) would
169 call NewError().handle(context, self._sign).)
170
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000171 To define a new exception, it should be sufficient to have it derive
172 from DecimalException.
173 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000174 def handle(self, context, *args):
175 pass
176
177
178class Clamped(DecimalException):
179 """Exponent of a 0 changed to fit bounds.
180
181 This occurs and signals clamped if the exponent of a result has been
182 altered in order to fit the constraints of a specific concrete
Facundo Batista59c58842007-04-10 12:58:45 +0000183 representation. This may occur when the exponent of a zero result would
184 be outside the bounds of a representation, or when a large normal
185 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000186 this latter case, the exponent is reduced to fit and the corresponding
187 number of zero digits are appended to the coefficient ("fold-down").
188 """
189
190
191class InvalidOperation(DecimalException):
192 """An invalid operation was performed.
193
194 Various bad things cause this:
195
196 Something creates a signaling NaN
197 -INF + INF
Facundo Batista59c58842007-04-10 12:58:45 +0000198 0 * (+-)INF
199 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000200 x % 0
201 (+-)INF % x
202 x._rescale( non-integer )
203 sqrt(-x) , x > 0
204 0 ** 0
205 x ** (non-integer)
206 x ** (+-)INF
207 An operand is invalid
Facundo Batista353750c2007-09-13 18:13:15 +0000208
209 The result of the operation after these is a quiet positive NaN,
210 except when the cause is a signaling NaN, in which case the result is
211 also a quiet NaN, but with the original sign, and an optional
212 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000213 """
214 def handle(self, context, *args):
215 if args:
Facundo Batista59c58842007-04-10 12:58:45 +0000216 if args[0] == 1: # sNaN, must drop 's' but keep diagnostics
Facundo Batista353750c2007-09-13 18:13:15 +0000217 ans = Decimal((args[1]._sign, args[1]._int, 'n'))
218 return ans._fix_nan(context)
219 elif args[0] == 2:
220 return Decimal( (args[1], args[2], 'n') )
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000221 return NaN
222
Facundo Batista353750c2007-09-13 18:13:15 +0000223
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000224class ConversionSyntax(InvalidOperation):
225 """Trying to convert badly formed string.
226
227 This occurs and signals invalid-operation if an string is being
228 converted to a number and it does not conform to the numeric string
Facundo Batista59c58842007-04-10 12:58:45 +0000229 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000230 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000231 def handle(self, context, *args):
Facundo Batista353750c2007-09-13 18:13:15 +0000232 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000233
234class DivisionByZero(DecimalException, ZeroDivisionError):
235 """Division by 0.
236
237 This occurs and signals division-by-zero if division of a finite number
238 by zero was attempted (during a divide-integer or divide operation, or a
239 power operation with negative right-hand operand), and the dividend was
240 not zero.
241
242 The result of the operation is [sign,inf], where sign is the exclusive
243 or of the signs of the operands for divide, or is 1 for an odd power of
244 -0, for power.
245 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000246
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000247 def handle(self, context, sign, double = None, *args):
248 if double is not None:
249 return (Infsign[sign],)*2
250 return Infsign[sign]
251
252class DivisionImpossible(InvalidOperation):
253 """Cannot perform the division adequately.
254
255 This occurs and signals invalid-operation if the integer result of a
256 divide-integer or remainder operation had too many digits (would be
Facundo Batista59c58842007-04-10 12:58:45 +0000257 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000258 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000259
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000260 def handle(self, context, *args):
261 return (NaN, NaN)
262
263class DivisionUndefined(InvalidOperation, ZeroDivisionError):
264 """Undefined result of division.
265
266 This occurs and signals invalid-operation if division by zero was
267 attempted (during a divide-integer, divide, or remainder operation), and
Facundo Batista59c58842007-04-10 12:58:45 +0000268 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000269 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000270
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000271 def handle(self, context, tup=None, *args):
272 if tup is not None:
Facundo Batista59c58842007-04-10 12:58:45 +0000273 return (NaN, NaN) # for 0 %0, 0 // 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000274 return NaN
275
276class Inexact(DecimalException):
277 """Had to round, losing information.
278
279 This occurs and signals inexact whenever the result of an operation is
280 not exact (that is, it needed to be rounded and any discarded digits
Facundo Batista59c58842007-04-10 12:58:45 +0000281 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000282 result in all cases is unchanged.
283
284 The inexact signal may be tested (or trapped) to determine if a given
285 operation (or sequence of operations) was inexact.
286 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000287 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000288
289class InvalidContext(InvalidOperation):
290 """Invalid context. Unknown rounding, for example.
291
292 This occurs and signals invalid-operation if an invalid context was
Facundo Batista59c58842007-04-10 12:58:45 +0000293 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000294 on creation and either the precision exceeds the capability of the
295 underlying concrete representation or an unknown or unsupported rounding
Facundo Batista59c58842007-04-10 12:58:45 +0000296 was specified. These aspects of the context need only be checked when
297 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000298 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000299
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000300 def handle(self, context, *args):
301 return NaN
302
303class Rounded(DecimalException):
304 """Number got rounded (not necessarily changed during rounding).
305
306 This occurs and signals rounded whenever the result of an operation is
307 rounded (that is, some zero or non-zero digits were discarded from the
Facundo Batista59c58842007-04-10 12:58:45 +0000308 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000309 result in all cases is unchanged.
310
311 The rounded signal may be tested (or trapped) to determine if a given
312 operation (or sequence of operations) caused a loss of precision.
313 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000314 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000315
316class Subnormal(DecimalException):
317 """Exponent < Emin before rounding.
318
319 This occurs and signals subnormal whenever the result of a conversion or
320 operation is subnormal (that is, its adjusted exponent is less than
Facundo Batista59c58842007-04-10 12:58:45 +0000321 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000322
323 The subnormal signal may be tested (or trapped) to determine if a given
324 or operation (or sequence of operations) yielded a subnormal result.
325 """
326 pass
327
328class Overflow(Inexact, Rounded):
329 """Numerical overflow.
330
331 This occurs and signals overflow if the adjusted exponent of a result
332 (from a conversion or from an operation that is not an attempt to divide
333 by zero), after rounding, would be greater than the largest value that
334 can be handled by the implementation (the value Emax).
335
336 The result depends on the rounding mode:
337
338 For round-half-up and round-half-even (and for round-half-down and
339 round-up, if implemented), the result of the operation is [sign,inf],
Facundo Batista59c58842007-04-10 12:58:45 +0000340 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000341 result is the largest finite number that can be represented in the
Facundo Batista59c58842007-04-10 12:58:45 +0000342 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000343 round-ceiling, the result is the same as for round-down if the sign of
Facundo Batista59c58842007-04-10 12:58:45 +0000344 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000345 the result is the same as for round-down if the sign of the intermediate
Facundo Batista59c58842007-04-10 12:58:45 +0000346 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000347 will also be raised.
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000348 """
349
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000350 def handle(self, context, sign, *args):
351 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Facundo Batista353750c2007-09-13 18:13:15 +0000352 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000353 return Infsign[sign]
354 if sign == 0:
355 if context.rounding == ROUND_CEILING:
356 return Infsign[sign]
357 return Decimal((sign, (9,)*context.prec,
358 context.Emax-context.prec+1))
359 if sign == 1:
360 if context.rounding == ROUND_FLOOR:
361 return Infsign[sign]
362 return Decimal( (sign, (9,)*context.prec,
363 context.Emax-context.prec+1))
364
365
366class Underflow(Inexact, Rounded, Subnormal):
367 """Numerical underflow with result rounded to 0.
368
369 This occurs and signals underflow if a result is inexact and the
370 adjusted exponent of the result would be smaller (more negative) than
371 the smallest value that can be handled by the implementation (the value
Facundo Batista59c58842007-04-10 12:58:45 +0000372 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000373
374 The result after an underflow will be a subnormal number rounded, if
Facundo Batista59c58842007-04-10 12:58:45 +0000375 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000376 in 0 with the sign of the intermediate result and an exponent of Etiny.
377
378 In all cases, Inexact, Rounded, and Subnormal will also be raised.
379 """
380
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000381# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000382_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000383 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000384
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000385# Map conditions (per the spec) to signals
386_condition_map = {ConversionSyntax:InvalidOperation,
387 DivisionImpossible:InvalidOperation,
388 DivisionUndefined:InvalidOperation,
389 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000390
Facundo Batista59c58842007-04-10 12:58:45 +0000391##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000392
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000393# The getcontext() and setcontext() function manage access to a thread-local
394# current context. Py2.4 offers direct support for thread locals. If that
395# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000396# work for older Pythons. If threads are not part of the build, create a
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000397# mock threading object with threading.local() returning the module namespace.
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000398
399try:
400 import threading
401except ImportError:
402 # Python was compiled without threads; create a mock object instead
403 import sys
Facundo Batista59c58842007-04-10 12:58:45 +0000404 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000405 def local(self, sys=sys):
406 return sys.modules[__name__]
407 threading = MockThreading()
408 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000409
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000410try:
411 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000412
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000413except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000414
Facundo Batista59c58842007-04-10 12:58:45 +0000415 # To fix reloading, force it to create a new context
416 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000417 if hasattr(threading.currentThread(), '__decimal_context__'):
418 del threading.currentThread().__decimal_context__
419
420 def setcontext(context):
421 """Set this thread's context to context."""
422 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000423 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000424 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000425 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000426
427 def getcontext():
428 """Returns this thread's context.
429
430 If this thread does not yet have a context, returns
431 a new context and sets this thread's context.
432 New contexts are copies of DefaultContext.
433 """
434 try:
435 return threading.currentThread().__decimal_context__
436 except AttributeError:
437 context = Context()
438 threading.currentThread().__decimal_context__ = context
439 return context
440
441else:
442
443 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000444 if hasattr(local, '__decimal_context__'):
445 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000446
447 def getcontext(_local=local):
448 """Returns this thread's context.
449
450 If this thread does not yet have a context, returns
451 a new context and sets this thread's context.
452 New contexts are copies of DefaultContext.
453 """
454 try:
455 return _local.__decimal_context__
456 except AttributeError:
457 context = Context()
458 _local.__decimal_context__ = context
459 return context
460
461 def setcontext(context, _local=local):
462 """Set this thread's context to context."""
463 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000464 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000465 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000466 _local.__decimal_context__ = context
467
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000468 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000469
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000470def localcontext(ctx=None):
471 """Return a context manager for a copy of the supplied context
472
473 Uses a copy of the current context if no context is specified
474 The returned context manager creates a local decimal context
475 in a with statement:
476 def sin(x):
477 with localcontext() as ctx:
478 ctx.prec += 2
479 # Rest of sin calculation algorithm
480 # uses a precision 2 greater than normal
Facundo Batista59c58842007-04-10 12:58:45 +0000481 return +s # Convert result to normal precision
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000482
483 def sin(x):
484 with localcontext(ExtendedContext):
485 # Rest of sin calculation algorithm
486 # uses the Extended Context from the
487 # General Decimal Arithmetic Specification
Facundo Batista59c58842007-04-10 12:58:45 +0000488 return +s # Convert result to normal context
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000489
490 """
Neal Norwitz681d8672006-09-02 18:51:34 +0000491 # The string below can't be included in the docstring until Python 2.6
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000492 # as the doctest module doesn't understand __future__ statements
493 """
494 >>> from __future__ import with_statement
495 >>> print getcontext().prec
496 28
497 >>> with localcontext():
498 ... ctx = getcontext()
Raymond Hettinger495df472007-02-08 01:42:35 +0000499 ... ctx.prec += 2
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000500 ... print ctx.prec
501 ...
502 30
503 >>> with localcontext(ExtendedContext):
504 ... print getcontext().prec
505 ...
506 9
507 >>> print getcontext().prec
508 28
509 """
Nick Coghlanced12182006-09-02 03:54:17 +0000510 if ctx is None: ctx = getcontext()
511 return _ContextManager(ctx)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000512
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000513
Facundo Batista59c58842007-04-10 12:58:45 +0000514##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000515
516class Decimal(object):
517 """Floating point class for decimal arithmetic."""
518
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000519 __slots__ = ('_exp','_int','_sign', '_is_special')
520 # Generally, the value of the Decimal instance is given by
521 # (-1)**_sign * _int * 10**_exp
522 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000523
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000524 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000525 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000526 """Create a decimal point instance.
527
528 >>> Decimal('3.14') # string input
529 Decimal("3.14")
Facundo Batista59c58842007-04-10 12:58:45 +0000530 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000531 Decimal("3.14")
532 >>> Decimal(314) # int or long
533 Decimal("314")
534 >>> Decimal(Decimal(314)) # another decimal instance
535 Decimal("314")
536 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000537
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000538 self = object.__new__(cls)
539 self._is_special = False
540
541 # From an internal working value
542 if isinstance(value, _WorkRep):
Raymond Hettinger17931de2004-10-27 06:21:46 +0000543 self._sign = value.sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000544 self._int = tuple(map(int, str(value.int)))
545 self._exp = int(value.exp)
546 return self
547
548 # From another decimal
549 if isinstance(value, Decimal):
550 self._exp = value._exp
551 self._sign = value._sign
552 self._int = value._int
553 self._is_special = value._is_special
554 return self
555
556 # From an integer
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000557 if isinstance(value, (int,long)):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000558 if value >= 0:
559 self._sign = 0
560 else:
561 self._sign = 1
562 self._exp = 0
563 self._int = tuple(map(int, str(abs(value))))
564 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000565
566 # tuple/list conversion (possibly from as_tuple())
567 if isinstance(value, (list,tuple)):
568 if len(value) != 3:
Facundo Batista59c58842007-04-10 12:58:45 +0000569 raise ValueError('Invalid arguments')
Raymond Hettingerdbecd932005-02-06 06:57:08 +0000570 if value[0] not in (0,1):
Facundo Batista59c58842007-04-10 12:58:45 +0000571 raise ValueError('Invalid sign')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000572 for digit in value[1]:
573 if not isinstance(digit, (int,long)) or digit < 0:
Facundo Batista353750c2007-09-13 18:13:15 +0000574 raise ValueError("The second value in the tuple must be "
Facundo Batista59c58842007-04-10 12:58:45 +0000575 "composed of non negative integer elements.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000576 self._sign = value[0]
577 self._int = tuple(value[1])
578 if value[2] in ('F','n','N'):
579 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000580 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000581 else:
582 self._exp = int(value[2])
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000583 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000584
Raymond Hettingerbf440692004-07-10 14:14:37 +0000585 if isinstance(value, float):
586 raise TypeError("Cannot convert float to Decimal. " +
587 "First convert the float to a string")
588
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000589 # Other argument types may require the context during interpretation
590 if context is None:
591 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000592
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000593 # From a string
594 # REs insist on real strings, so we can too.
595 if isinstance(value, basestring):
596 if _isinfinity(value):
597 self._exp = 'F'
598 self._int = (0,)
599 self._is_special = True
600 if _isinfinity(value) == 1:
601 self._sign = 0
602 else:
603 self._sign = 1
604 return self
605 if _isnan(value):
606 sig, sign, diag = _isnan(value)
607 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000608 if sig == 1:
Facundo Batista59c58842007-04-10 12:58:45 +0000609 self._exp = 'n' # qNaN
610 else: # sig == 2
611 self._exp = 'N' # sNaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000612 self._sign = sign
Facundo Batista59c58842007-04-10 12:58:45 +0000613 self._int = tuple(map(int, diag)) # Diagnostic info
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000614 return self
615 try:
616 self._sign, self._int, self._exp = _string2exact(value)
617 except ValueError:
618 self._is_special = True
Facundo Batista353750c2007-09-13 18:13:15 +0000619 return context._raise_error(ConversionSyntax,
620 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000621 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000622
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000623 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000624
625 def _isnan(self):
626 """Returns whether the number is not actually one.
627
628 0 if a number
Facundo Batista353750c2007-09-13 18:13:15 +0000629 1 if NaN (it could be a normal quiet NaN or a phantom one)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000630 2 if sNaN
631 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000632 if self._is_special:
633 exp = self._exp
634 if exp == 'n':
635 return 1
636 elif exp == 'N':
637 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000638 return 0
639
640 def _isinfinity(self):
641 """Returns whether the number is infinite
642
643 0 if finite or not a number
644 1 if +INF
645 -1 if -INF
646 """
647 if self._exp == 'F':
648 if self._sign:
649 return -1
650 return 1
651 return 0
652
Facundo Batista353750c2007-09-13 18:13:15 +0000653 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000654 """Returns whether the number is not actually one.
655
656 if self, other are sNaN, signal
657 if self, other are NaN return nan
658 return 0
659
660 Done before operations.
661 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000662
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000663 self_is_nan = self._isnan()
664 if other is None:
665 other_is_nan = False
666 else:
667 other_is_nan = other._isnan()
668
669 if self_is_nan or other_is_nan:
670 if context is None:
671 context = getcontext()
672
673 if self_is_nan == 2:
674 return context._raise_error(InvalidOperation, 'sNaN',
675 1, self)
676 if other_is_nan == 2:
677 return context._raise_error(InvalidOperation, 'sNaN',
678 1, other)
679 if self_is_nan:
Facundo Batista353750c2007-09-13 18:13:15 +0000680 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000681
Facundo Batista353750c2007-09-13 18:13:15 +0000682 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000683 return 0
684
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000685 def __nonzero__(self):
686 """Is the number non-zero?
687
688 0 if self == 0
689 1 if self != 0
690 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000691 if self._is_special:
Facundo Batista353750c2007-09-13 18:13:15 +0000692 return True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000693 return sum(self._int) != 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000694
Facundo Batista353750c2007-09-13 18:13:15 +0000695 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000696 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000697 if other is NotImplemented:
Facundo Batista353750c2007-09-13 18:13:15 +0000698 # Never return NotImplemented
699 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000700
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000701 if self._is_special or other._is_special:
Facundo Batista353750c2007-09-13 18:13:15 +0000702 # check for nans, without raising on a signaling nan
703 if self._isnan() or other._isnan():
Facundo Batista59c58842007-04-10 12:58:45 +0000704 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000705
706 # INF = INF
707 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000708
Facundo Batista353750c2007-09-13 18:13:15 +0000709 # check for zeros; note that cmp(0, -0) should return 0
710 if not self:
711 if not other:
712 return 0
713 else:
714 return -((-1)**other._sign)
715 if not other:
716 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000717
Facundo Batista59c58842007-04-10 12:58:45 +0000718 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000719 if other._sign < self._sign:
720 return -1
721 if self._sign < other._sign:
722 return 1
723
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000724 self_adjusted = self.adjusted()
725 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000726 if self_adjusted == other_adjusted:
727 self_padded = self._int + (0,)*(self._exp - other._exp)
728 other_padded = other._int + (0,)*(other._exp - self._exp)
729 return cmp(self_padded, other_padded) * (-1)**self._sign
730 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000731 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000732 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000733 return -((-1)**self._sign)
734
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000735 def __eq__(self, other):
736 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000737 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000738 return self.__cmp__(other) == 0
739
740 def __ne__(self, other):
741 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000742 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000743 return self.__cmp__(other) != 0
744
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000745 def compare(self, other, context=None):
746 """Compares one to another.
747
748 -1 => a < b
749 0 => a = b
750 1 => a > b
751 NaN => one is NaN
752 Like __cmp__, but returns Decimal instances.
753 """
Facundo Batista353750c2007-09-13 18:13:15 +0000754 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000755
Facundo Batista59c58842007-04-10 12:58:45 +0000756 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000757 if (self._is_special or other and other._is_special):
758 ans = self._check_nans(other, context)
759 if ans:
760 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000761
Facundo Batista353750c2007-09-13 18:13:15 +0000762 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000763
764 def __hash__(self):
765 """x.__hash__() <==> hash(x)"""
766 # Decimal integers must hash the same as the ints
767 # Non-integer decimals are normalized and hashed as strings
Georg Brandl1fb9f522006-05-11 19:57:09 +0000768 # Normalization assures that hash(100E-1) == hash(10)
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000769 if self._is_special:
770 if self._isnan():
771 raise TypeError('Cannot hash a NaN value.')
772 return hash(str(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000773 i = int(self)
774 if self == Decimal(i):
775 return hash(i)
776 assert self.__nonzero__() # '-0' handled by integer case
777 return hash(str(self.normalize()))
778
779 def as_tuple(self):
780 """Represents the number as a triple tuple.
781
782 To show the internals exactly as they are.
783 """
784 return (self._sign, self._int, self._exp)
785
786 def __repr__(self):
787 """Represents the number as an instance of Decimal."""
788 # Invariant: eval(repr(d)) == d
789 return 'Decimal("%s")' % str(self)
790
Facundo Batista353750c2007-09-13 18:13:15 +0000791 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000792 """Return string representation of the number in scientific notation.
793
794 Captures all of the information in the underlying representation.
795 """
796
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000797 if self._is_special:
798 if self._isnan():
799 minus = '-'*self._sign
800 if self._int == (0,):
801 info = ''
802 else:
803 info = ''.join(map(str, self._int))
804 if self._isnan() == 2:
805 return minus + 'sNaN' + info
806 return minus + 'NaN' + info
807 if self._isinfinity():
808 minus = '-'*self._sign
809 return minus + 'Infinity'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000810
811 if context is None:
812 context = getcontext()
813
814 tmp = map(str, self._int)
815 numdigits = len(self._int)
816 leftdigits = self._exp + numdigits
Facundo Batista59c58842007-04-10 12:58:45 +0000817 if eng and not self: # self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
818 if self._exp < 0 and self._exp >= -6: # short, no need for e/E
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000819 s = '-'*self._sign + '0.' + '0'*(abs(self._exp))
820 return s
Facundo Batista59c58842007-04-10 12:58:45 +0000821 # exp is closest mult. of 3 >= self._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000822 exp = ((self._exp - 1)// 3 + 1) * 3
823 if exp != self._exp:
824 s = '0.'+'0'*(exp - self._exp)
825 else:
826 s = '0'
827 if exp != 0:
828 if context.capitals:
829 s += 'E'
830 else:
831 s += 'e'
832 if exp > 0:
Facundo Batista59c58842007-04-10 12:58:45 +0000833 s += '+' # 0.0e+3, not 0.0e3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000834 s += str(exp)
835 s = '-'*self._sign + s
836 return s
837 if eng:
838 dotplace = (leftdigits-1)%3+1
839 adjexp = leftdigits -1 - (leftdigits-1)%3
840 else:
841 adjexp = leftdigits-1
842 dotplace = 1
843 if self._exp == 0:
844 pass
845 elif self._exp < 0 and adjexp >= 0:
846 tmp.insert(leftdigits, '.')
847 elif self._exp < 0 and adjexp >= -6:
848 tmp[0:0] = ['0'] * int(-leftdigits)
849 tmp.insert(0, '0.')
850 else:
851 if numdigits > dotplace:
852 tmp.insert(dotplace, '.')
853 elif numdigits < dotplace:
854 tmp.extend(['0']*(dotplace-numdigits))
855 if adjexp:
856 if not context.capitals:
857 tmp.append('e')
858 else:
859 tmp.append('E')
860 if adjexp > 0:
861 tmp.append('+')
862 tmp.append(str(adjexp))
863 if eng:
864 while tmp[0:1] == ['0']:
865 tmp[0:1] = []
866 if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e':
867 tmp[0:0] = ['0']
868 if self._sign:
869 tmp.insert(0, '-')
870
871 return ''.join(tmp)
872
873 def to_eng_string(self, context=None):
874 """Convert to engineering-type string.
875
876 Engineering notation has an exponent which is a multiple of 3, so there
877 are up to 3 digits left of the decimal place.
878
879 Same rules for when in exponential and when as a value as in __str__.
880 """
Facundo Batista353750c2007-09-13 18:13:15 +0000881 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000882
883 def __neg__(self, context=None):
884 """Returns a copy with the sign switched.
885
886 Rounds, if it has reason.
887 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000888 if self._is_special:
889 ans = self._check_nans(context=context)
890 if ans:
891 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000892
893 if not self:
894 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +0000895 ans = self.copy_sign(Dec_0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000896 else:
Facundo Batista353750c2007-09-13 18:13:15 +0000897 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000898
899 if context is None:
900 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000901 if context._rounding_decision == ALWAYS_ROUND:
Facundo Batista353750c2007-09-13 18:13:15 +0000902 return ans._fix(context)
903 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000904
905 def __pos__(self, context=None):
906 """Returns a copy, unless it is a sNaN.
907
908 Rounds the number (if more then precision digits)
909 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000910 if self._is_special:
911 ans = self._check_nans(context=context)
912 if ans:
913 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000914
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000915 if not self:
916 # + (-0) = 0
Facundo Batista353750c2007-09-13 18:13:15 +0000917 ans = self.copy_sign(Dec_0)
918 else:
919 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000920
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000921 if context is None:
922 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000923 if context._rounding_decision == ALWAYS_ROUND:
Facundo Batista353750c2007-09-13 18:13:15 +0000924 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000925 return ans
926
927 def __abs__(self, round=1, context=None):
928 """Returns the absolute value of self.
929
930 If the second argument is 0, do not round.
931 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000932 if self._is_special:
933 ans = self._check_nans(context=context)
934 if ans:
935 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000936
937 if not round:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000938 if context is None:
939 context = getcontext()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000940 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000941 context._set_rounding_decision(NEVER_ROUND)
942
943 if self._sign:
944 ans = self.__neg__(context=context)
945 else:
946 ans = self.__pos__(context=context)
947
948 return ans
949
950 def __add__(self, other, context=None):
951 """Returns self + other.
952
953 -INF + INF (or the reverse) cause InvalidOperation errors.
954 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000955 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000956 if other is NotImplemented:
957 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000958
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000959 if context is None:
960 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000961
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000962 if self._is_special or other._is_special:
963 ans = self._check_nans(other, context)
964 if ans:
965 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000966
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000967 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000968 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000969 if self._sign != other._sign and other._isinfinity():
970 return context._raise_error(InvalidOperation, '-INF + INF')
971 return Decimal(self)
972 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000973 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000974
975 shouldround = context._rounding_decision == ALWAYS_ROUND
976
977 exp = min(self._exp, other._exp)
978 negativezero = 0
979 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +0000980 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000981 negativezero = 1
982
983 if not self and not other:
984 sign = min(self._sign, other._sign)
985 if negativezero:
986 sign = 1
Facundo Batista353750c2007-09-13 18:13:15 +0000987 ans = Decimal( (sign, (0,), exp))
988 if shouldround:
989 ans = ans._fix(context)
990 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000991 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +0000992 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +0000993 ans = other._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000994 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000995 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000996 return ans
997 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +0000998 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +0000999 ans = self._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001001 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001002 return ans
1003
1004 op1 = _WorkRep(self)
1005 op2 = _WorkRep(other)
1006 op1, op2 = _normalize(op1, op2, shouldround, context.prec)
1007
1008 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001009 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001010 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001011 if op1.int == op2.int:
Facundo Batista353750c2007-09-13 18:13:15 +00001012 ans = Decimal((negativezero, (0,), exp))
1013 if shouldround:
1014 ans = ans._fix(context)
1015 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001016 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001017 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001018 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001019 if op1.sign == 1:
1020 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001021 op1.sign, op2.sign = op2.sign, op1.sign
1022 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001023 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001024 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001025 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001026 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001027 op1.sign, op2.sign = (0, 0)
1028 else:
1029 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001030 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001031
Raymond Hettinger17931de2004-10-27 06:21:46 +00001032 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001033 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001034 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001035 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001036
1037 result.exp = op1.exp
1038 ans = Decimal(result)
1039 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001040 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001041 return ans
1042
1043 __radd__ = __add__
1044
1045 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001046 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001047 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001048 if other is NotImplemented:
1049 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001050
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001051 if self._is_special or other._is_special:
1052 ans = self._check_nans(other, context=context)
1053 if ans:
1054 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001055
Facundo Batista353750c2007-09-13 18:13:15 +00001056 # self - other is computed as self + other.copy_negate()
1057 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001058
1059 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001060 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001061 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001062 if other is NotImplemented:
1063 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001064
Facundo Batista353750c2007-09-13 18:13:15 +00001065 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001066
Facundo Batista353750c2007-09-13 18:13:15 +00001067 def _increment(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001068 """Special case of add, adding 1eExponent
1069
1070 Since it is common, (rounding, for example) this adds
1071 (sign)*one E self._exp to the number more efficiently than add.
1072
Facundo Batista353750c2007-09-13 18:13:15 +00001073 Assumes that self is nonspecial.
1074
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001075 For example:
1076 Decimal('5.624e10')._increment() == Decimal('5.625e10')
1077 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001078 L = list(self._int)
1079 L[-1] += 1
1080 spot = len(L)-1
1081 while L[spot] == 10:
1082 L[spot] = 0
1083 if spot == 0:
1084 L[0:0] = [1]
1085 break
1086 L[spot-1] += 1
1087 spot -= 1
Facundo Batista353750c2007-09-13 18:13:15 +00001088 return Decimal((self._sign, L, self._exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001089
1090 def __mul__(self, other, context=None):
1091 """Return self * other.
1092
1093 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1094 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001095 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001096 if other is NotImplemented:
1097 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001098
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001099 if context is None:
1100 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001101
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001102 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001103
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001104 if self._is_special or other._is_special:
1105 ans = self._check_nans(other, context)
1106 if ans:
1107 return ans
1108
1109 if self._isinfinity():
1110 if not other:
1111 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1112 return Infsign[resultsign]
1113
1114 if other._isinfinity():
1115 if not self:
1116 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1117 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001118
1119 resultexp = self._exp + other._exp
1120 shouldround = context._rounding_decision == ALWAYS_ROUND
1121
1122 # Special case for multiplying by zero
1123 if not self or not other:
1124 ans = Decimal((resultsign, (0,), resultexp))
1125 if shouldround:
Facundo Batista59c58842007-04-10 12:58:45 +00001126 # Fixing in case the exponent is out of bounds
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001127 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001128 return ans
1129
1130 # Special case for multiplying by power of 10
1131 if self._int == (1,):
1132 ans = Decimal((resultsign, other._int, resultexp))
1133 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001134 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001135 return ans
1136 if other._int == (1,):
1137 ans = Decimal((resultsign, self._int, resultexp))
1138 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001139 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001140 return ans
1141
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001142 op1 = _WorkRep(self)
1143 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001144
Facundo Batista59c58842007-04-10 12:58:45 +00001145 ans = Decimal((resultsign, map(int, str(op1.int * op2.int)), resultexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001146 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001147 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001148
1149 return ans
1150 __rmul__ = __mul__
1151
1152 def __div__(self, other, context=None):
1153 """Return self / other."""
1154 return self._divide(other, context=context)
1155 __truediv__ = __div__
1156
1157 def _divide(self, other, divmod = 0, context=None):
1158 """Return a / b, to context.prec precision.
1159
1160 divmod:
1161 0 => true division
1162 1 => (a //b, a%b)
1163 2 => a //b
1164 3 => a%b
1165
1166 Actually, if divmod is 2 or 3 a tuple is returned, but errors for
1167 computing the other value are not raised.
1168 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001169 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001170 if other is NotImplemented:
1171 if divmod in (0, 1):
1172 return NotImplemented
1173 return (NotImplemented, NotImplemented)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001174
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001175 if context is None:
1176 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001177
Facundo Batista353750c2007-09-13 18:13:15 +00001178 shouldround = context._rounding_decision == ALWAYS_ROUND
1179
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001180 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001181
1182 if self._is_special or other._is_special:
1183 ans = self._check_nans(other, context)
1184 if ans:
1185 if divmod:
1186 return (ans, ans)
1187 return ans
1188
1189 if self._isinfinity() and other._isinfinity():
1190 if divmod:
Facundo Batista353750c2007-09-13 18:13:15 +00001191 reloco = (context._raise_error(InvalidOperation,
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001192 '(+-)INF // (+-)INF'),
1193 context._raise_error(InvalidOperation,
1194 '(+-)INF % (+-)INF'))
Facundo Batista353750c2007-09-13 18:13:15 +00001195 return reloco
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001196 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001197
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001198 if self._isinfinity():
1199 if divmod == 1:
1200 return (Infsign[sign],
1201 context._raise_error(InvalidOperation, 'INF % x'))
1202 elif divmod == 2:
1203 return (Infsign[sign], NaN)
1204 elif divmod == 3:
1205 return (Infsign[sign],
1206 context._raise_error(InvalidOperation, 'INF % x'))
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001207 return Infsign[sign]
1208
1209 if other._isinfinity():
1210 if divmod:
Facundo Batista353750c2007-09-13 18:13:15 +00001211 otherside = Decimal(self)
1212 if shouldround and (divmod == 1 or divmod == 3):
1213 otherside = otherside._fix(context)
1214 return (Decimal((sign, (0,), 0)), otherside)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001215 context._raise_error(Clamped, 'Division by infinity')
1216 return Decimal((sign, (0,), context.Etiny()))
1217
1218 # Special cases for zeroes
1219 if not self and not other:
1220 if divmod:
1221 return context._raise_error(DivisionUndefined, '0 / 0', 1)
1222 return context._raise_error(DivisionUndefined, '0 / 0')
1223
1224 if not self:
1225 if divmod:
Facundo Batista353750c2007-09-13 18:13:15 +00001226 otherside = Decimal((self._sign, (0,), min(self._exp, other._exp)))
1227 if shouldround and (divmod == 1 or divmod == 3):
1228 otherside = otherside._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001229 return (Decimal((sign, (0,), 0)), otherside)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001230 exp = self._exp - other._exp
Facundo Batista353750c2007-09-13 18:13:15 +00001231 ans = Decimal((sign, (0,), exp))
1232 ans = ans._fix(context)
1233 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001234
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001235 if not other:
1236 if divmod:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001237 return context._raise_error(DivisionByZero, 'divmod(x,0)',
1238 sign, 1)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001239 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001240
Facundo Batista59c58842007-04-10 12:58:45 +00001241 # OK, so neither = 0, INF or NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001242
Facundo Batista59c58842007-04-10 12:58:45 +00001243 # If we're dividing into ints, and self < other, stop.
1244 # self.__abs__(0) does not round.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001245 if divmod and (self.__abs__(0, context) < other.__abs__(0, context)):
1246
1247 if divmod == 1 or divmod == 3:
1248 exp = min(self._exp, other._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00001249 ans2 = self._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001250 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001251 ans2 = ans2._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001252 return (Decimal( (sign, (0,), 0) ),
1253 ans2)
1254
1255 elif divmod == 2:
Facundo Batista59c58842007-04-10 12:58:45 +00001256 # Don't round the mod part, if we don't need it.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001257 return (Decimal( (sign, (0,), 0) ), Decimal(self))
1258
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001259 op1 = _WorkRep(self)
1260 op2 = _WorkRep(other)
1261 op1, op2, adjust = _adjust_coefficients(op1, op2)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001262 res = _WorkRep( (sign, 0, (op1.exp - op2.exp)) )
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001263 if divmod and res.exp > context.prec + 1:
1264 return context._raise_error(DivisionImpossible)
1265
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001266 prec_limit = 10 ** context.prec
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001267 while 1:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001268 while op2.int <= op1.int:
1269 res.int += 1
1270 op1.int -= op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001271 if res.exp == 0 and divmod:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001272 if res.int >= prec_limit and shouldround:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001273 return context._raise_error(DivisionImpossible)
1274 otherside = Decimal(op1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001275 exp = min(self._exp, other._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00001276 otherside = otherside._rescale(exp, context.rounding)
1277 if shouldround and (divmod == 1 or divmod == 3):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001278 otherside = otherside._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001279 return (Decimal(res), otherside)
1280
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001281 if op1.int == 0 and adjust >= 0 and not divmod:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001282 break
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001283 if res.int >= prec_limit and shouldround:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001284 if divmod:
1285 return context._raise_error(DivisionImpossible)
1286 shouldround=1
1287 # Really, the answer is a bit higher, so adding a one to
1288 # the end will make sure the rounding is right.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001289 if op1.int != 0:
1290 res.int *= 10
1291 res.int += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001292 res.exp -= 1
1293
1294 break
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001295 res.int *= 10
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001296 res.exp -= 1
1297 adjust += 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001298 op1.int *= 10
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001299 op1.exp -= 1
1300
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001301 ans = Decimal(res)
1302 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001303 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001304 return ans
1305
1306 def __rdiv__(self, other, context=None):
1307 """Swaps self/other and returns __div__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001308 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001309 if other is NotImplemented:
1310 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001311 return other.__div__(self, context=context)
1312 __rtruediv__ = __rdiv__
1313
1314 def __divmod__(self, other, context=None):
1315 """
1316 (self // other, self % other)
1317 """
1318 return self._divide(other, 1, context)
1319
1320 def __rdivmod__(self, other, context=None):
1321 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001322 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001323 if other is NotImplemented:
1324 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001325 return other.__divmod__(self, context=context)
1326
1327 def __mod__(self, other, context=None):
1328 """
1329 self % other
1330 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001331 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001332 if other is NotImplemented:
1333 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001334
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001335 if self._is_special or other._is_special:
1336 ans = self._check_nans(other, context)
1337 if ans:
1338 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001339
1340 if self and not other:
1341 return context._raise_error(InvalidOperation, 'x % 0')
1342
1343 return self._divide(other, 3, context)[1]
1344
1345 def __rmod__(self, other, context=None):
1346 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001347 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001348 if other is NotImplemented:
1349 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001350 return other.__mod__(self, context=context)
1351
1352 def remainder_near(self, other, context=None):
1353 """
1354 Remainder nearest to 0- abs(remainder-near) <= other/2
1355 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001356 if context is None:
1357 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001358
Facundo Batista353750c2007-09-13 18:13:15 +00001359 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001360
Facundo Batista353750c2007-09-13 18:13:15 +00001361 ans = self._check_nans(other, context)
1362 if ans:
1363 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001364
Facundo Batista353750c2007-09-13 18:13:15 +00001365 # self == +/-infinity -> InvalidOperation
1366 if self._isinfinity():
1367 return context._raise_error(InvalidOperation,
1368 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001369
Facundo Batista353750c2007-09-13 18:13:15 +00001370 # other == 0 -> either InvalidOperation or DivisionUndefined
1371 if not other:
1372 if self:
1373 return context._raise_error(InvalidOperation,
1374 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001375 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001376 return context._raise_error(DivisionUndefined,
1377 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001378
Facundo Batista353750c2007-09-13 18:13:15 +00001379 # other = +/-infinity -> remainder = self
1380 if other._isinfinity():
1381 ans = Decimal(self)
1382 return ans._fix(context)
1383
1384 # self = 0 -> remainder = self, with ideal exponent
1385 ideal_exponent = min(self._exp, other._exp)
1386 if not self:
1387 ans = Decimal((self._sign, (0,), ideal_exponent))
1388 return ans._fix(context)
1389
1390 # catch most cases of large or small quotient
1391 expdiff = self.adjusted() - other.adjusted()
1392 if expdiff >= context.prec + 1:
1393 # expdiff >= prec+1 => abs(self/other) > 10**prec
1394 return context._raise_error(DivisionImpossible)[0]
1395 if expdiff <= -2:
1396 # expdiff <= -2 => abs(self/other) < 0.1
1397 ans = self._rescale(ideal_exponent, context.rounding)
1398 return ans._fix(context)
1399
1400 # adjust both arguments to have the same exponent, then divide
1401 op1 = _WorkRep(self)
1402 op2 = _WorkRep(other)
1403 if op1.exp >= op2.exp:
1404 op1.int *= 10**(op1.exp - op2.exp)
1405 else:
1406 op2.int *= 10**(op2.exp - op1.exp)
1407 q, r = divmod(op1.int, op2.int)
1408 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1409 # 10**ideal_exponent. Apply correction to ensure that
1410 # abs(remainder) <= abs(other)/2
1411 if 2*r + (q&1) > op2.int:
1412 r -= op2.int
1413 q += 1
1414
1415 if q >= 10**context.prec:
1416 return context._raise_error(DivisionImpossible)[0]
1417
1418 # result has same sign as self unless r is negative
1419 sign = self._sign
1420 if r < 0:
1421 sign = 1-sign
1422 r = -r
1423
1424 ans = Decimal((sign, map(int, str(r)), ideal_exponent))
1425 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001426
1427 def __floordiv__(self, other, context=None):
1428 """self // other"""
1429 return self._divide(other, 2, context)[0]
1430
1431 def __rfloordiv__(self, other, context=None):
1432 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001433 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001434 if other is NotImplemented:
1435 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001436 return other.__floordiv__(self, context=context)
1437
1438 def __float__(self):
1439 """Float representation."""
1440 return float(str(self))
1441
1442 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001443 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001444 if self._is_special:
1445 if self._isnan():
1446 context = getcontext()
1447 return context._raise_error(InvalidContext)
1448 elif self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001449 raise OverflowError("Cannot convert infinity to long")
Facundo Batista353750c2007-09-13 18:13:15 +00001450 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001451 if self._exp >= 0:
Facundo Batista353750c2007-09-13 18:13:15 +00001452 return s*int(''.join(map(str, self._int)))*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001453 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001454 return s*int(''.join(map(str, self._int))[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001455
1456 def __long__(self):
1457 """Converts to a long.
1458
1459 Equivalent to long(int(self))
1460 """
1461 return long(self.__int__())
1462
Facundo Batista353750c2007-09-13 18:13:15 +00001463 def _fix_nan(self, context):
1464 """Decapitate the payload of a NaN to fit the context"""
1465 payload = self._int
1466
1467 # maximum length of payload is precision if _clamp=0,
1468 # precision-1 if _clamp=1.
1469 max_payload_len = context.prec - context._clamp
1470 if len(payload) > max_payload_len:
1471 pos = len(payload)-max_payload_len
1472 while pos < len(payload) and payload[pos] == 0:
1473 pos += 1
1474 payload = payload[pos:]
1475 return Decimal((self._sign, payload, self._exp))
Facundo Batista6c398da2007-09-17 17:30:13 +00001476 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001477
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001478 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001479 """Round if it is necessary to keep self within prec precision.
1480
1481 Rounds and fixes the exponent. Does not raise on a sNaN.
1482
1483 Arguments:
1484 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001485 context - context used.
1486 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001487
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001488 if context is None:
1489 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001490
Facundo Batista353750c2007-09-13 18:13:15 +00001491 if self._is_special:
1492 if self._isnan():
1493 # decapitate payload if necessary
1494 return self._fix_nan(context)
1495 else:
1496 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001497 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001498
Facundo Batista353750c2007-09-13 18:13:15 +00001499 # if self is zero then exponent should be between Etiny and
1500 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1501 Etiny = context.Etiny()
1502 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001503 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001504 exp_max = [context.Emax, Etop][context._clamp]
1505 new_exp = min(max(self._exp, Etiny), exp_max)
1506 if new_exp != self._exp:
1507 context._raise_error(Clamped)
1508 return Decimal((self._sign, (0,), new_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001509 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001510 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001511
1512 # exp_min is the smallest allowable exponent of the result,
1513 # equal to max(self.adjusted()-context.prec+1, Etiny)
1514 exp_min = len(self._int) + self._exp - context.prec
1515 if exp_min > Etop:
1516 # overflow: exp_min > Etop iff self.adjusted() > Emax
1517 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001518 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001519 return context._raise_error(Overflow, 'above Emax', self._sign)
1520 self_is_subnormal = exp_min < Etiny
1521 if self_is_subnormal:
1522 context._raise_error(Subnormal)
1523 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001524
Facundo Batista353750c2007-09-13 18:13:15 +00001525 # round if self has too many digits
1526 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001527 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001528 ans = self._rescale(exp_min, context.rounding)
1529 if ans != self:
1530 context._raise_error(Inexact)
1531 if self_is_subnormal:
1532 context._raise_error(Underflow)
1533 if not ans:
1534 # raise Clamped on underflow to 0
1535 context._raise_error(Clamped)
1536 elif len(ans._int) == context.prec+1:
1537 # we get here only if rescaling rounds the
1538 # cofficient up to exactly 10**context.prec
1539 if ans._exp < Etop:
1540 ans = Decimal((ans._sign, ans._int[:-1], ans._exp+1))
1541 else:
1542 # Inexact and Rounded have already been raised
1543 ans = context._raise_error(Overflow, 'above Emax',
1544 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001545 return ans
1546
Facundo Batista353750c2007-09-13 18:13:15 +00001547 # fold down if _clamp == 1 and self has too few digits
1548 if context._clamp == 1 and self._exp > Etop:
1549 context._raise_error(Clamped)
1550 self_padded = self._int + (0,)*(self._exp - Etop)
1551 return Decimal((self._sign, self_padded, Etop))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001552
Facundo Batista353750c2007-09-13 18:13:15 +00001553 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001554 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001555
1556 _pick_rounding_function = {}
1557
Facundo Batista353750c2007-09-13 18:13:15 +00001558 # for each of the rounding functions below:
1559 # self is a finite, nonzero Decimal
1560 # prec is an integer satisfying 0 <= prec < len(self._int)
1561 # the rounded result will have exponent self._exp + len(self._int) - prec;
1562
1563 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001564 """Also known as round-towards-0, truncate."""
Facundo Batista353750c2007-09-13 18:13:15 +00001565 newexp = self._exp + len(self._int) - prec
1566 return Decimal((self._sign, self._int[:prec] or (0,), newexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001567
Facundo Batista353750c2007-09-13 18:13:15 +00001568 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001569 """Rounds away from 0."""
Facundo Batista353750c2007-09-13 18:13:15 +00001570 newexp = self._exp + len(self._int) - prec
1571 tmp = Decimal((self._sign, self._int[:prec] or (0,), newexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001572 for digit in self._int[prec:]:
1573 if digit != 0:
Facundo Batista353750c2007-09-13 18:13:15 +00001574 return tmp._increment()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001575 return tmp
1576
Facundo Batista353750c2007-09-13 18:13:15 +00001577 def _round_half_up(self, prec):
1578 """Rounds 5 up (away from 0)"""
1579 if self._int[prec] >= 5:
1580 return self._round_up(prec)
1581 else:
1582 return self._round_down(prec)
1583
1584 def _round_half_down(self, prec):
1585 """Round 5 down"""
1586 if self._int[prec] == 5:
1587 for digit in self._int[prec+1:]:
1588 if digit != 0:
1589 break
1590 else:
1591 return self._round_down(prec)
1592 return self._round_half_up(prec)
1593
1594 def _round_half_even(self, prec):
1595 """Round 5 to even, rest to nearest."""
1596 if prec and self._int[prec-1] & 1:
1597 return self._round_half_up(prec)
1598 else:
1599 return self._round_half_down(prec)
1600
1601 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001602 """Rounds up (not away from 0 if negative.)"""
1603 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001604 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001605 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001606 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001607
Facundo Batista353750c2007-09-13 18:13:15 +00001608 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001609 """Rounds down (not towards 0 if negative)"""
1610 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001611 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001612 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001613 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001614
Facundo Batista353750c2007-09-13 18:13:15 +00001615 def _round_05up(self, prec):
1616 """Round down unless digit prec-1 is 0 or 5."""
1617 if prec == 0 or self._int[prec-1] in (0, 5):
1618 return self._round_up(prec)
1619 else:
1620 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001621
Facundo Batista353750c2007-09-13 18:13:15 +00001622 def fma(self, other, third, context=None):
1623 """Fused multiply-add.
1624
1625 Returns self*other+third with no rounding of the intermediate
1626 product self*other.
1627
1628 self and other are multiplied together, with no rounding of
1629 the result. The third operand is then added to the result,
1630 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001631 """
Facundo Batista353750c2007-09-13 18:13:15 +00001632
1633 other = _convert_other(other, raiseit=True)
1634 third = _convert_other(third, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001635
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001636 if context is None:
1637 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001638
Facundo Batista353750c2007-09-13 18:13:15 +00001639 # do self*other in fresh context with no traps and no rounding
1640 mul_context = Context(traps=[], flags=[],
1641 _rounding_decision=NEVER_ROUND)
1642 product = self.__mul__(other, mul_context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001643
Facundo Batista353750c2007-09-13 18:13:15 +00001644 if mul_context.flags[InvalidOperation]:
1645 # reraise in current context
1646 return context._raise_error(InvalidOperation,
1647 'invalid multiplication in fma',
1648 1, product)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001649
Facundo Batista353750c2007-09-13 18:13:15 +00001650 ans = product.__add__(third, context)
1651 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001652
Facundo Batista353750c2007-09-13 18:13:15 +00001653 def _power_modulo(self, other, modulo, context=None):
1654 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001655
Facundo Batista353750c2007-09-13 18:13:15 +00001656 # if can't convert other and modulo to Decimal, raise
1657 # TypeError; there's no point returning NotImplemented (no
1658 # equivalent of __rpow__ for three argument pow)
1659 other = _convert_other(other, raiseit=True)
1660 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001661
Facundo Batista353750c2007-09-13 18:13:15 +00001662 if context is None:
1663 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001664
Facundo Batista353750c2007-09-13 18:13:15 +00001665 # deal with NaNs: if there are any sNaNs then first one wins,
1666 # (i.e. behaviour for NaNs is identical to that of fma)
1667 self_is_nan = self._isnan()
1668 other_is_nan = other._isnan()
1669 modulo_is_nan = modulo._isnan()
1670 if self_is_nan or other_is_nan or modulo_is_nan:
1671 if self_is_nan == 2:
1672 return context._raise_error(InvalidOperation, 'sNaN',
1673 1, self)
1674 if other_is_nan == 2:
1675 return context._raise_error(InvalidOperation, 'sNaN',
1676 1, other)
1677 if modulo_is_nan == 2:
1678 return context._raise_error(InvalidOperation, 'sNaN',
1679 1, modulo)
1680 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001681 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001682 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001683 return other._fix_nan(context)
1684 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001685
Facundo Batista353750c2007-09-13 18:13:15 +00001686 # check inputs: we apply same restrictions as Python's pow()
1687 if not (self._isinteger() and
1688 other._isinteger() and
1689 modulo._isinteger()):
1690 return context._raise_error(InvalidOperation,
1691 'pow() 3rd argument not allowed '
1692 'unless all arguments are integers')
1693 if other < 0:
1694 return context._raise_error(InvalidOperation,
1695 'pow() 2nd argument cannot be '
1696 'negative when 3rd argument specified')
1697 if not modulo:
1698 return context._raise_error(InvalidOperation,
1699 'pow() 3rd argument cannot be 0')
1700
1701 # additional restriction for decimal: the modulus must be less
1702 # than 10**prec in absolute value
1703 if modulo.adjusted() >= context.prec:
1704 return context._raise_error(InvalidOperation,
1705 'insufficient precision: pow() 3rd '
1706 'argument must not have more than '
1707 'precision digits')
1708
1709 # define 0**0 == NaN, for consistency with two-argument pow
1710 # (even though it hurts!)
1711 if not other and not self:
1712 return context._raise_error(InvalidOperation,
1713 'at least one of pow() 1st argument '
1714 'and 2nd argument must be nonzero ;'
1715 '0**0 is not defined')
1716
1717 # compute sign of result
1718 if other._iseven():
1719 sign = 0
1720 else:
1721 sign = self._sign
1722
1723 # convert modulo to a Python integer, and self and other to
1724 # Decimal integers (i.e. force their exponents to be >= 0)
1725 modulo = abs(int(modulo))
1726 base = _WorkRep(self.to_integral_value())
1727 exponent = _WorkRep(other.to_integral_value())
1728
1729 # compute result using integer pow()
1730 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1731 for i in xrange(exponent.exp):
1732 base = pow(base, 10, modulo)
1733 base = pow(base, exponent.int, modulo)
1734
1735 return Decimal((sign, map(int, str(base)), 0))
1736
1737 def _power_exact(self, other, p):
1738 """Attempt to compute self**other exactly.
1739
1740 Given Decimals self and other and an integer p, attempt to
1741 compute an exact result for the power self**other, with p
1742 digits of precision. Return None if self**other is not
1743 exactly representable in p digits.
1744
1745 Assumes that elimination of special cases has already been
1746 performed: self and other must both be nonspecial; self must
1747 be positive and not numerically equal to 1; other must be
1748 nonzero. For efficiency, other._exp should not be too large,
1749 so that 10**abs(other._exp) is a feasible calculation."""
1750
1751 # In the comments below, we write x for the value of self and
1752 # y for the value of other. Write x = xc*10**xe and y =
1753 # yc*10**ye.
1754
1755 # The main purpose of this method is to identify the *failure*
1756 # of x**y to be exactly representable with as little effort as
1757 # possible. So we look for cheap and easy tests that
1758 # eliminate the possibility of x**y being exact. Only if all
1759 # these tests are passed do we go on to actually compute x**y.
1760
1761 # Here's the main idea. First normalize both x and y. We
1762 # express y as a rational m/n, with m and n relatively prime
1763 # and n>0. Then for x**y to be exactly representable (at
1764 # *any* precision), xc must be the nth power of a positive
1765 # integer and xe must be divisible by n. If m is negative
1766 # then additionally xc must be a power of either 2 or 5, hence
1767 # a power of 2**n or 5**n.
1768 #
1769 # There's a limit to how small |y| can be: if y=m/n as above
1770 # then:
1771 #
1772 # (1) if xc != 1 then for the result to be representable we
1773 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1774 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1775 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1776 # representable.
1777 #
1778 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1779 # |y| < 1/|xe| then the result is not representable.
1780 #
1781 # Note that since x is not equal to 1, at least one of (1) and
1782 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1783 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1784 #
1785 # There's also a limit to how large y can be, at least if it's
1786 # positive: the normalized result will have coefficient xc**y,
1787 # so if it's representable then xc**y < 10**p, and y <
1788 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1789 # not exactly representable.
1790
1791 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1792 # so |y| < 1/xe and the result is not representable.
1793 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1794 # < 1/nbits(xc).
1795
1796 x = _WorkRep(self)
1797 xc, xe = x.int, x.exp
1798 while xc % 10 == 0:
1799 xc //= 10
1800 xe += 1
1801
1802 y = _WorkRep(other)
1803 yc, ye = y.int, y.exp
1804 while yc % 10 == 0:
1805 yc //= 10
1806 ye += 1
1807
1808 # case where xc == 1: result is 10**(xe*y), with xe*y
1809 # required to be an integer
1810 if xc == 1:
1811 if ye >= 0:
1812 exponent = xe*yc*10**ye
1813 else:
1814 exponent, remainder = divmod(xe*yc, 10**-ye)
1815 if remainder:
1816 return None
1817 if y.sign == 1:
1818 exponent = -exponent
1819 # if other is a nonnegative integer, use ideal exponent
1820 if other._isinteger() and other._sign == 0:
1821 ideal_exponent = self._exp*int(other)
1822 zeros = min(exponent-ideal_exponent, p-1)
1823 else:
1824 zeros = 0
1825 return Decimal((0, (1,) + (0,)*zeros, exponent-zeros))
1826
1827 # case where y is negative: xc must be either a power
1828 # of 2 or a power of 5.
1829 if y.sign == 1:
1830 last_digit = xc % 10
1831 if last_digit in (2,4,6,8):
1832 # quick test for power of 2
1833 if xc & -xc != xc:
1834 return None
1835 # now xc is a power of 2; e is its exponent
1836 e = _nbits(xc)-1
1837 # find e*y and xe*y; both must be integers
1838 if ye >= 0:
1839 y_as_int = yc*10**ye
1840 e = e*y_as_int
1841 xe = xe*y_as_int
1842 else:
1843 ten_pow = 10**-ye
1844 e, remainder = divmod(e*yc, ten_pow)
1845 if remainder:
1846 return None
1847 xe, remainder = divmod(xe*yc, ten_pow)
1848 if remainder:
1849 return None
1850
1851 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1852 return None
1853 xc = 5**e
1854
1855 elif last_digit == 5:
1856 # e >= log_5(xc) if xc is a power of 5; we have
1857 # equality all the way up to xc=5**2658
1858 e = _nbits(xc)*28//65
1859 xc, remainder = divmod(5**e, xc)
1860 if remainder:
1861 return None
1862 while xc % 5 == 0:
1863 xc //= 5
1864 e -= 1
1865 if ye >= 0:
1866 y_as_integer = yc*10**ye
1867 e = e*y_as_integer
1868 xe = xe*y_as_integer
1869 else:
1870 ten_pow = 10**-ye
1871 e, remainder = divmod(e*yc, ten_pow)
1872 if remainder:
1873 return None
1874 xe, remainder = divmod(xe*yc, ten_pow)
1875 if remainder:
1876 return None
1877 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1878 return None
1879 xc = 2**e
1880 else:
1881 return None
1882
1883 if xc >= 10**p:
1884 return None
1885 xe = -e-xe
1886 return Decimal((0, map(int, str(xc)), xe))
1887
1888 # now y is positive; find m and n such that y = m/n
1889 if ye >= 0:
1890 m, n = yc*10**ye, 1
1891 else:
1892 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1893 return None
1894 xc_bits = _nbits(xc)
1895 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1896 return None
1897 m, n = yc, 10**(-ye)
1898 while m % 2 == n % 2 == 0:
1899 m //= 2
1900 n //= 2
1901 while m % 5 == n % 5 == 0:
1902 m //= 5
1903 n //= 5
1904
1905 # compute nth root of xc*10**xe
1906 if n > 1:
1907 # if 1 < xc < 2**n then xc isn't an nth power
1908 if xc != 1 and xc_bits <= n:
1909 return None
1910
1911 xe, rem = divmod(xe, n)
1912 if rem != 0:
1913 return None
1914
1915 # compute nth root of xc using Newton's method
1916 a = 1L << -(-_nbits(xc)//n) # initial estimate
1917 while True:
1918 q, r = divmod(xc, a**(n-1))
1919 if a <= q:
1920 break
1921 else:
1922 a = (a*(n-1) + q)//n
1923 if not (a == q and r == 0):
1924 return None
1925 xc = a
1926
1927 # now xc*10**xe is the nth root of the original xc*10**xe
1928 # compute mth power of xc*10**xe
1929
1930 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1931 # 10**p and the result is not representable.
1932 if xc > 1 and m > p*100//_log10_lb(xc):
1933 return None
1934 xc = xc**m
1935 xe *= m
1936 if xc > 10**p:
1937 return None
1938
1939 # by this point the result *is* exactly representable
1940 # adjust the exponent to get as close as possible to the ideal
1941 # exponent, if necessary
1942 str_xc = str(xc)
1943 if other._isinteger() and other._sign == 0:
1944 ideal_exponent = self._exp*int(other)
1945 zeros = min(xe-ideal_exponent, p-len(str_xc))
1946 else:
1947 zeros = 0
1948 return Decimal((0, map(int, str_xc)+[0,]*zeros, xe-zeros))
1949
1950 def __pow__(self, other, modulo=None, context=None):
1951 """Return self ** other [ % modulo].
1952
1953 With two arguments, compute self**other.
1954
1955 With three arguments, compute (self**other) % modulo. For the
1956 three argument form, the following restrictions on the
1957 arguments hold:
1958
1959 - all three arguments must be integral
1960 - other must be nonnegative
1961 - either self or other (or both) must be nonzero
1962 - modulo must be nonzero and must have at most p digits,
1963 where p is the context precision.
1964
1965 If any of these restrictions is violated the InvalidOperation
1966 flag is raised.
1967
1968 The result of pow(self, other, modulo) is identical to the
1969 result that would be obtained by computing (self**other) %
1970 modulo with unbounded precision, but is computed more
1971 efficiently. It is always exact.
1972 """
1973
1974 if modulo is not None:
1975 return self._power_modulo(other, modulo, context)
1976
1977 other = _convert_other(other)
1978 if other is NotImplemented:
1979 return other
1980
1981 if context is None:
1982 context = getcontext()
1983
1984 # either argument is a NaN => result is NaN
1985 ans = self._check_nans(other, context)
1986 if ans:
1987 return ans
1988
1989 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
1990 if not other:
1991 if not self:
1992 return context._raise_error(InvalidOperation, '0 ** 0')
1993 else:
1994 return Dec_p1
1995
1996 # result has sign 1 iff self._sign is 1 and other is an odd integer
1997 result_sign = 0
1998 if self._sign == 1:
1999 if other._isinteger():
2000 if not other._iseven():
2001 result_sign = 1
2002 else:
2003 # -ve**noninteger = NaN
2004 # (-0)**noninteger = 0**noninteger
2005 if self:
2006 return context._raise_error(InvalidOperation,
2007 'x ** y with x negative and y not an integer')
2008 # negate self, without doing any unwanted rounding
2009 self = Decimal((0, self._int, self._exp))
2010
2011 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2012 if not self:
2013 if other._sign == 0:
2014 return Decimal((result_sign, (0,), 0))
2015 else:
2016 return Infsign[result_sign]
2017
2018 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002019 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002020 if other._sign == 0:
2021 return Infsign[result_sign]
2022 else:
2023 return Decimal((result_sign, (0,), 0))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002024
Facundo Batista353750c2007-09-13 18:13:15 +00002025 # 1**other = 1, but the choice of exponent and the flags
2026 # depend on the exponent of self, and on whether other is a
2027 # positive integer, a negative integer, or neither
2028 if self == Dec_p1:
2029 if other._isinteger():
2030 # exp = max(self._exp*max(int(other), 0),
2031 # 1-context.prec) but evaluating int(other) directly
2032 # is dangerous until we know other is small (other
2033 # could be 1e999999999)
2034 if other._sign == 1:
2035 multiplier = 0
2036 elif other > context.prec:
2037 multiplier = context.prec
2038 else:
2039 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002040
Facundo Batista353750c2007-09-13 18:13:15 +00002041 exp = self._exp * multiplier
2042 if exp < 1-context.prec:
2043 exp = 1-context.prec
2044 context._raise_error(Rounded)
2045 else:
2046 context._raise_error(Inexact)
2047 context._raise_error(Rounded)
2048 exp = 1-context.prec
2049
2050 return Decimal((result_sign, (1,)+(0,)*-exp, exp))
2051
2052 # compute adjusted exponent of self
2053 self_adj = self.adjusted()
2054
2055 # self ** infinity is infinity if self > 1, 0 if self < 1
2056 # self ** -infinity is infinity if self < 1, 0 if self > 1
2057 if other._isinfinity():
2058 if (other._sign == 0) == (self_adj < 0):
2059 return Decimal((result_sign, (0,), 0))
2060 else:
2061 return Infsign[result_sign]
2062
2063 # from here on, the result always goes through the call
2064 # to _fix at the end of this function.
2065 ans = None
2066
2067 # crude test to catch cases of extreme overflow/underflow. If
2068 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2069 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2070 # self**other >= 10**(Emax+1), so overflow occurs. The test
2071 # for underflow is similar.
2072 bound = self._log10_exp_bound() + other.adjusted()
2073 if (self_adj >= 0) == (other._sign == 0):
2074 # self > 1 and other +ve, or self < 1 and other -ve
2075 # possibility of overflow
2076 if bound >= len(str(context.Emax)):
2077 ans = Decimal((result_sign, (1,), context.Emax+1))
2078 else:
2079 # self > 1 and other -ve, or self < 1 and other +ve
2080 # possibility of underflow to 0
2081 Etiny = context.Etiny()
2082 if bound >= len(str(-Etiny)):
2083 ans = Decimal((result_sign, (1,), Etiny-1))
2084
2085 # try for an exact result with precision +1
2086 if ans is None:
2087 ans = self._power_exact(other, context.prec + 1)
2088 if ans is not None and result_sign == 1:
2089 ans = Decimal((1, ans._int, ans._exp))
2090
2091 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2092 if ans is None:
2093 p = context.prec
2094 x = _WorkRep(self)
2095 xc, xe = x.int, x.exp
2096 y = _WorkRep(other)
2097 yc, ye = y.int, y.exp
2098 if y.sign == 1:
2099 yc = -yc
2100
2101 # compute correctly rounded result: start with precision +3,
2102 # then increase precision until result is unambiguously roundable
2103 extra = 3
2104 while True:
2105 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2106 if coeff % (5*10**(len(str(coeff))-p-1)):
2107 break
2108 extra += 3
2109
2110 ans = Decimal((result_sign, map(int, str(coeff)), exp))
2111
2112 # the specification says that for non-integer other we need to
2113 # raise Inexact, even when the result is actually exact. In
2114 # the same way, we need to raise Underflow here if the result
2115 # is subnormal. (The call to _fix will take care of raising
2116 # Rounded and Subnormal, as usual.)
2117 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002118 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002119 # pad with zeros up to length context.prec+1 if necessary
2120 if len(ans._int) <= context.prec:
2121 expdiff = context.prec+1 - len(ans._int)
2122 ans = Decimal((ans._sign, ans._int+(0,)*expdiff, ans._exp-expdiff))
2123 if ans.adjusted() < context.Emin:
2124 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002125
Facundo Batista353750c2007-09-13 18:13:15 +00002126 # unlike exp, ln and log10, the power function respects the
2127 # rounding mode; no need to use ROUND_HALF_EVEN here
2128 ans = ans._fix(context)
2129 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002130
2131 def __rpow__(self, other, context=None):
2132 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002133 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002134 if other is NotImplemented:
2135 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002136 return other.__pow__(self, context=context)
2137
2138 def normalize(self, context=None):
2139 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002140
Facundo Batista353750c2007-09-13 18:13:15 +00002141 if context is None:
2142 context = getcontext()
2143
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002144 if self._is_special:
2145 ans = self._check_nans(context=context)
2146 if ans:
2147 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002148
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002149 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002150 if dup._isinfinity():
2151 return dup
2152
2153 if not dup:
2154 return Decimal( (dup._sign, (0,), 0) )
Facundo Batista353750c2007-09-13 18:13:15 +00002155 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002156 end = len(dup._int)
2157 exp = dup._exp
Facundo Batista353750c2007-09-13 18:13:15 +00002158 while dup._int[end-1] == 0 and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002159 exp += 1
2160 end -= 1
2161 return Decimal( (dup._sign, dup._int[:end], exp) )
2162
Facundo Batistabd2fe832007-09-13 18:42:09 +00002163 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002164 """Quantize self so its exponent is the same as that of exp.
2165
2166 Similar to self._rescale(exp._exp) but with error checking.
2167 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002168 exp = _convert_other(exp, raiseit=True)
2169
Facundo Batista353750c2007-09-13 18:13:15 +00002170 if context is None:
2171 context = getcontext()
2172 if rounding is None:
2173 rounding = context.rounding
2174
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002175 if self._is_special or exp._is_special:
2176 ans = self._check_nans(exp, context)
2177 if ans:
2178 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002179
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002180 if exp._isinfinity() or self._isinfinity():
2181 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002182 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002183 return context._raise_error(InvalidOperation,
2184 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002185
Facundo Batistabd2fe832007-09-13 18:42:09 +00002186 # if we're not watching exponents, do a simple rescale
2187 if not watchexp:
2188 ans = self._rescale(exp._exp, rounding)
2189 # raise Inexact and Rounded where appropriate
2190 if ans._exp > self._exp:
2191 context._raise_error(Rounded)
2192 if ans != self:
2193 context._raise_error(Inexact)
2194 return ans
2195
Facundo Batista353750c2007-09-13 18:13:15 +00002196 # exp._exp should be between Etiny and Emax
2197 if not (context.Etiny() <= exp._exp <= context.Emax):
2198 return context._raise_error(InvalidOperation,
2199 'target exponent out of bounds in quantize')
2200
2201 if not self:
2202 ans = Decimal((self._sign, (0,), exp._exp))
2203 return ans._fix(context)
2204
2205 self_adjusted = self.adjusted()
2206 if self_adjusted > context.Emax:
2207 return context._raise_error(InvalidOperation,
2208 'exponent of quantize result too large for current context')
2209 if self_adjusted - exp._exp + 1 > context.prec:
2210 return context._raise_error(InvalidOperation,
2211 'quantize result has too many digits for current context')
2212
2213 ans = self._rescale(exp._exp, rounding)
2214 if ans.adjusted() > context.Emax:
2215 return context._raise_error(InvalidOperation,
2216 'exponent of quantize result too large for current context')
2217 if len(ans._int) > context.prec:
2218 return context._raise_error(InvalidOperation,
2219 'quantize result has too many digits for current context')
2220
2221 # raise appropriate flags
2222 if ans._exp > self._exp:
2223 context._raise_error(Rounded)
2224 if ans != self:
2225 context._raise_error(Inexact)
2226 if ans and ans.adjusted() < context.Emin:
2227 context._raise_error(Subnormal)
2228
2229 # call to fix takes care of any necessary folddown
2230 ans = ans._fix(context)
2231 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002232
2233 def same_quantum(self, other):
2234 """Test whether self and other have the same exponent.
2235
2236 same as self._exp == other._exp, except NaN == sNaN
2237 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002238 if self._is_special or other._is_special:
2239 if self._isnan() or other._isnan():
2240 return self._isnan() and other._isnan() and True
2241 if self._isinfinity() or other._isinfinity():
2242 return self._isinfinity() and other._isinfinity() and True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002243 return self._exp == other._exp
2244
Facundo Batista353750c2007-09-13 18:13:15 +00002245 def _rescale(self, exp, rounding):
2246 """Rescale self so that the exponent is exp, either by padding with zeros
2247 or by truncating digits, using the given rounding mode.
2248
2249 Specials are returned without change. This operation is
2250 quiet: it raises no flags, and uses no information from the
2251 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002252
2253 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002254 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002255 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002256 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002257 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002258 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002259 return Decimal((self._sign, (0,), exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002260
Facundo Batista353750c2007-09-13 18:13:15 +00002261 if self._exp >= exp:
2262 # pad answer with zeros if necessary
2263 return Decimal((self._sign, self._int + (0,)*(self._exp - exp), exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002264
Facundo Batista353750c2007-09-13 18:13:15 +00002265 # too many digits; round and lose data. If self.adjusted() <
2266 # exp-1, replace self by 10**(exp-1) before rounding
2267 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002268 if digits < 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002269 self = Decimal((self._sign, (1,), exp-1))
2270 digits = 0
2271 this_function = getattr(self, self._pick_rounding_function[rounding])
2272 return this_function(digits)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002273
Facundo Batista353750c2007-09-13 18:13:15 +00002274 def to_integral_exact(self, rounding=None, context=None):
2275 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002276
Facundo Batista353750c2007-09-13 18:13:15 +00002277 If no rounding mode is specified, take the rounding mode from
2278 the context. This method raises the Rounded and Inexact flags
2279 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002280
Facundo Batista353750c2007-09-13 18:13:15 +00002281 See also: to_integral_value, which does exactly the same as
2282 this method except that it doesn't raise Inexact or Rounded.
2283 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002284 if self._is_special:
2285 ans = self._check_nans(context=context)
2286 if ans:
2287 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002288 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002289 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002290 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002291 if not self:
2292 return Decimal((self._sign, (0,), 0))
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002293 if context is None:
2294 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002295 if rounding is None:
2296 rounding = context.rounding
2297 context._raise_error(Rounded)
2298 ans = self._rescale(0, rounding)
2299 if ans != self:
2300 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002301 return ans
2302
Facundo Batista353750c2007-09-13 18:13:15 +00002303 def to_integral_value(self, rounding=None, context=None):
2304 """Rounds to the nearest integer, without raising inexact, rounded."""
2305 if context is None:
2306 context = getcontext()
2307 if rounding is None:
2308 rounding = context.rounding
2309 if self._is_special:
2310 ans = self._check_nans(context=context)
2311 if ans:
2312 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002313 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002314 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002315 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002316 else:
2317 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002318
Facundo Batista353750c2007-09-13 18:13:15 +00002319 # the method name changed, but we provide also the old one, for compatibility
2320 to_integral = to_integral_value
2321
2322 def sqrt(self, context=None):
2323 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002324 if self._is_special:
2325 ans = self._check_nans(context=context)
2326 if ans:
2327 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002328
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002329 if self._isinfinity() and self._sign == 0:
2330 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002331
2332 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002333 # exponent = self._exp // 2. sqrt(-0) = -0
2334 ans = Decimal((self._sign, (0,), self._exp // 2))
2335 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002336
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002337 if context is None:
2338 context = getcontext()
2339
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002340 if self._sign == 1:
2341 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2342
Facundo Batista353750c2007-09-13 18:13:15 +00002343 # At this point self represents a positive number. Let p be
2344 # the desired precision and express self in the form c*100**e
2345 # with c a positive real number and e an integer, c and e
2346 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2347 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2348 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2349 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2350 # the closest integer to sqrt(c) with the even integer chosen
2351 # in the case of a tie.
2352 #
2353 # To ensure correct rounding in all cases, we use the
2354 # following trick: we compute the square root to an extra
2355 # place (precision p+1 instead of precision p), rounding down.
2356 # Then, if the result is inexact and its last digit is 0 or 5,
2357 # we increase the last digit to 1 or 6 respectively; if it's
2358 # exact we leave the last digit alone. Now the final round to
2359 # p places (or fewer in the case of underflow) will round
2360 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002361
Facundo Batista353750c2007-09-13 18:13:15 +00002362 # use an extra digit of precision
2363 prec = context.prec+1
2364
2365 # write argument in the form c*100**e where e = self._exp//2
2366 # is the 'ideal' exponent, to be used if the square root is
2367 # exactly representable. l is the number of 'digits' of c in
2368 # base 100, so that 100**(l-1) <= c < 100**l.
2369 op = _WorkRep(self)
2370 e = op.exp >> 1
2371 if op.exp & 1:
2372 c = op.int * 10
2373 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002374 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002375 c = op.int
2376 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002377
Facundo Batista353750c2007-09-13 18:13:15 +00002378 # rescale so that c has exactly prec base 100 'digits'
2379 shift = prec-l
2380 if shift >= 0:
2381 c *= 100**shift
2382 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002383 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002384 c, remainder = divmod(c, 100**-shift)
2385 exact = not remainder
2386 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002387
Facundo Batista353750c2007-09-13 18:13:15 +00002388 # find n = floor(sqrt(c)) using Newton's method
2389 n = 10**prec
2390 while True:
2391 q = c//n
2392 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002393 break
Facundo Batista353750c2007-09-13 18:13:15 +00002394 else:
2395 n = n + q >> 1
2396 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002397
Facundo Batista353750c2007-09-13 18:13:15 +00002398 if exact:
2399 # result is exact; rescale to use ideal exponent e
2400 if shift >= 0:
2401 # assert n % 10**shift == 0
2402 n //= 10**shift
2403 else:
2404 n *= 10**-shift
2405 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002406 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002407 # result is not exact; fix last digit as described above
2408 if n % 5 == 0:
2409 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002410
Facundo Batista353750c2007-09-13 18:13:15 +00002411 ans = Decimal((0, map(int, str(n)), e))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002412
Facundo Batista353750c2007-09-13 18:13:15 +00002413 # round, and fit to current context
2414 context = context._shallow_copy()
2415 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002416 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002417 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002418
Facundo Batista353750c2007-09-13 18:13:15 +00002419 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002420
2421 def max(self, other, context=None):
2422 """Returns the larger value.
2423
Facundo Batista353750c2007-09-13 18:13:15 +00002424 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002425 NaN (and signals if one is sNaN). Also rounds.
2426 """
Facundo Batista353750c2007-09-13 18:13:15 +00002427 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002428
Facundo Batista6c398da2007-09-17 17:30:13 +00002429 if context is None:
2430 context = getcontext()
2431
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002432 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002433 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002434 # number is always returned
2435 sn = self._isnan()
2436 on = other._isnan()
2437 if sn or on:
2438 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002439 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002440 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002441 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002442 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002443
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002444 c = self.__cmp__(other)
2445 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002446 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002447 # then an ordering is applied:
2448 #
Facundo Batista59c58842007-04-10 12:58:45 +00002449 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002450 # positive sign and min returns the operand with the negative sign
2451 #
Facundo Batista59c58842007-04-10 12:58:45 +00002452 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002453 # the result. This is exactly the ordering used in compare_total.
2454 c = self.compare_total(other)
2455
2456 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002457 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002458 else:
2459 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002460
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002461 if context._rounding_decision == ALWAYS_ROUND:
2462 return ans._fix(context)
2463 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002464
2465 def min(self, other, context=None):
2466 """Returns the smaller value.
2467
Facundo Batista59c58842007-04-10 12:58:45 +00002468 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002469 NaN (and signals if one is sNaN). Also rounds.
2470 """
Facundo Batista353750c2007-09-13 18:13:15 +00002471 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002472
Facundo Batista6c398da2007-09-17 17:30:13 +00002473 if context is None:
2474 context = getcontext()
2475
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002476 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002477 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002478 # number is always returned
2479 sn = self._isnan()
2480 on = other._isnan()
2481 if sn or on:
2482 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002483 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002484 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002485 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002486 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002487
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002488 c = self.__cmp__(other)
2489 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002490 c = self.compare_total(other)
2491
2492 if c == -1:
2493 ans = self
2494 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002495 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002496
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002497 if context._rounding_decision == ALWAYS_ROUND:
2498 return ans._fix(context)
2499 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002500
2501 def _isinteger(self):
2502 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002503 if self._is_special:
2504 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002505 if self._exp >= 0:
2506 return True
2507 rest = self._int[self._exp:]
2508 return rest == (0,)*len(rest)
2509
2510 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002511 """Returns True if self is even. Assumes self is an integer."""
2512 if not self or self._exp > 0:
2513 return True
Raymond Hettinger61992ef2004-08-06 23:42:16 +00002514 return self._int[-1+self._exp] & 1 == 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002515
2516 def adjusted(self):
2517 """Return the adjusted exponent of self"""
2518 try:
2519 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002520 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002521 except TypeError:
2522 return 0
2523
Facundo Batista353750c2007-09-13 18:13:15 +00002524 def canonical(self, context=None):
2525 """Returns the same Decimal object.
2526
2527 As we do not have different encodings for the same number, the
2528 received object already is in its canonical form.
2529 """
2530 return self
2531
2532 def compare_signal(self, other, context=None):
2533 """Compares self to the other operand numerically.
2534
2535 It's pretty much like compare(), but all NaNs signal, with signaling
2536 NaNs taking precedence over quiet NaNs.
2537 """
2538 if context is None:
2539 context = getcontext()
2540
2541 self_is_nan = self._isnan()
2542 other_is_nan = other._isnan()
2543 if self_is_nan == 2:
2544 return context._raise_error(InvalidOperation, 'sNaN',
2545 1, self)
2546 if other_is_nan == 2:
2547 return context._raise_error(InvalidOperation, 'sNaN',
2548 1, other)
2549 if self_is_nan:
2550 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2551 1, self)
2552 if other_is_nan:
2553 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2554 1, other)
2555 return self.compare(other, context=context)
2556
2557 def compare_total(self, other):
2558 """Compares self to other using the abstract representations.
2559
2560 This is not like the standard compare, which use their numerical
2561 value. Note that a total ordering is defined for all possible abstract
2562 representations.
2563 """
2564 # if one is negative and the other is positive, it's easy
2565 if self._sign and not other._sign:
2566 return Dec_n1
2567 if not self._sign and other._sign:
2568 return Dec_p1
2569 sign = self._sign
2570
2571 # let's handle both NaN types
2572 self_nan = self._isnan()
2573 other_nan = other._isnan()
2574 if self_nan or other_nan:
2575 if self_nan == other_nan:
2576 if self._int < other._int:
2577 if sign:
2578 return Dec_p1
2579 else:
2580 return Dec_n1
2581 if self._int > other._int:
2582 if sign:
2583 return Dec_n1
2584 else:
2585 return Dec_p1
2586 return Dec_0
2587
2588 if sign:
2589 if self_nan == 1:
2590 return Dec_n1
2591 if other_nan == 1:
2592 return Dec_p1
2593 if self_nan == 2:
2594 return Dec_n1
2595 if other_nan == 2:
2596 return Dec_p1
2597 else:
2598 if self_nan == 1:
2599 return Dec_p1
2600 if other_nan == 1:
2601 return Dec_n1
2602 if self_nan == 2:
2603 return Dec_p1
2604 if other_nan == 2:
2605 return Dec_n1
2606
2607 if self < other:
2608 return Dec_n1
2609 if self > other:
2610 return Dec_p1
2611
2612 if self._exp < other._exp:
2613 if sign:
2614 return Dec_p1
2615 else:
2616 return Dec_n1
2617 if self._exp > other._exp:
2618 if sign:
2619 return Dec_n1
2620 else:
2621 return Dec_p1
2622 return Dec_0
2623
2624
2625 def compare_total_mag(self, other):
2626 """Compares self to other using abstract repr., ignoring sign.
2627
2628 Like compare_total, but with operand's sign ignored and assumed to be 0.
2629 """
2630 s = self.copy_abs()
2631 o = other.copy_abs()
2632 return s.compare_total(o)
2633
2634 def copy_abs(self):
2635 """Returns a copy with the sign set to 0. """
2636 return Decimal((0, self._int, self._exp))
2637
2638 def copy_negate(self):
2639 """Returns a copy with the sign inverted."""
2640 if self._sign:
2641 return Decimal((0, self._int, self._exp))
2642 else:
2643 return Decimal((1, self._int, self._exp))
2644
2645 def copy_sign(self, other):
2646 """Returns self with the sign of other."""
2647 return Decimal((other._sign, self._int, self._exp))
2648
2649 def exp(self, context=None):
2650 """Returns e ** self."""
2651
2652 if context is None:
2653 context = getcontext()
2654
2655 # exp(NaN) = NaN
2656 ans = self._check_nans(context=context)
2657 if ans:
2658 return ans
2659
2660 # exp(-Infinity) = 0
2661 if self._isinfinity() == -1:
2662 return Dec_0
2663
2664 # exp(0) = 1
2665 if not self:
2666 return Dec_p1
2667
2668 # exp(Infinity) = Infinity
2669 if self._isinfinity() == 1:
2670 return Decimal(self)
2671
2672 # the result is now guaranteed to be inexact (the true
2673 # mathematical result is transcendental). There's no need to
2674 # raise Rounded and Inexact here---they'll always be raised as
2675 # a result of the call to _fix.
2676 p = context.prec
2677 adj = self.adjusted()
2678
2679 # we only need to do any computation for quite a small range
2680 # of adjusted exponents---for example, -29 <= adj <= 10 for
2681 # the default context. For smaller exponent the result is
2682 # indistinguishable from 1 at the given precision, while for
2683 # larger exponent the result either overflows or underflows.
2684 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2685 # overflow
2686 ans = Decimal((0, (1,), context.Emax+1))
2687 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2688 # underflow to 0
2689 ans = Decimal((0, (1,), context.Etiny()-1))
2690 elif self._sign == 0 and adj < -p:
2691 # p+1 digits; final round will raise correct flags
2692 ans = Decimal((0, (1,) + (0,)*(p-1) + (1,), -p))
2693 elif self._sign == 1 and adj < -p-1:
2694 # p+1 digits; final round will raise correct flags
2695 ans = Decimal((0, (9,)*(p+1), -p-1))
2696 # general case
2697 else:
2698 op = _WorkRep(self)
2699 c, e = op.int, op.exp
2700 if op.sign == 1:
2701 c = -c
2702
2703 # compute correctly rounded result: increase precision by
2704 # 3 digits at a time until we get an unambiguously
2705 # roundable result
2706 extra = 3
2707 while True:
2708 coeff, exp = _dexp(c, e, p+extra)
2709 if coeff % (5*10**(len(str(coeff))-p-1)):
2710 break
2711 extra += 3
2712
2713 ans = Decimal((0, map(int, str(coeff)), exp))
2714
2715 # at this stage, ans should round correctly with *any*
2716 # rounding mode, not just with ROUND_HALF_EVEN
2717 context = context._shallow_copy()
2718 rounding = context._set_rounding(ROUND_HALF_EVEN)
2719 ans = ans._fix(context)
2720 context.rounding = rounding
2721
2722 return ans
2723
2724 def is_canonical(self):
2725 """Returns 1 if self is canonical; otherwise returns 0."""
2726 return Dec_p1
2727
2728 def is_finite(self):
2729 """Returns 1 if self is finite, otherwise returns 0.
2730
2731 For it to be finite, it must be neither infinite nor a NaN.
2732 """
2733 if self._is_special:
2734 return Dec_0
2735 else:
2736 return Dec_p1
2737
2738 def is_infinite(self):
2739 """Returns 1 if self is an Infinite, otherwise returns 0."""
2740 if self._isinfinity():
2741 return Dec_p1
2742 else:
2743 return Dec_0
2744
2745 def is_nan(self):
2746 """Returns 1 if self is qNaN or sNaN, otherwise returns 0."""
2747 if self._isnan():
2748 return Dec_p1
2749 else:
2750 return Dec_0
2751
2752 def is_normal(self, context=None):
2753 """Returns 1 if self is a normal number, otherwise returns 0."""
2754 if self._is_special:
2755 return Dec_0
2756 if not self:
2757 return Dec_0
2758 if context is None:
2759 context = getcontext()
2760 if context.Emin <= self.adjusted() <= context.Emax:
2761 return Dec_p1
2762 else:
2763 return Dec_0
2764
2765 def is_qnan(self):
2766 """Returns 1 if self is a quiet NaN, otherwise returns 0."""
2767 if self._isnan() == 1:
2768 return Dec_p1
2769 else:
2770 return Dec_0
2771
2772 def is_signed(self):
2773 """Returns 1 if self is negative, otherwise returns 0."""
2774 return Decimal(self._sign)
2775
2776 def is_snan(self):
2777 """Returns 1 if self is a signaling NaN, otherwise returns 0."""
2778 if self._isnan() == 2:
2779 return Dec_p1
2780 else:
2781 return Dec_0
2782
2783 def is_subnormal(self, context=None):
2784 """Returns 1 if self is subnormal, otherwise returns 0."""
2785 if self._is_special:
2786 return Dec_0
2787 if not self:
2788 return Dec_0
2789 if context is None:
2790 context = getcontext()
2791
2792 r = self._exp + len(self._int)
2793 if r <= context.Emin:
2794 return Dec_p1
2795 return Dec_0
2796
2797 def is_zero(self):
2798 """Returns 1 if self is a zero, otherwise returns 0."""
2799 if self:
2800 return Dec_0
2801 else:
2802 return Dec_p1
2803
2804 def _ln_exp_bound(self):
2805 """Compute a lower bound for the adjusted exponent of self.ln().
2806 In other words, compute r such that self.ln() >= 10**r. Assumes
2807 that self is finite and positive and that self != 1.
2808 """
2809
2810 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2811 adj = self._exp + len(self._int) - 1
2812 if adj >= 1:
2813 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2814 return len(str(adj*23//10)) - 1
2815 if adj <= -2:
2816 # argument <= 0.1
2817 return len(str((-1-adj)*23//10)) - 1
2818 op = _WorkRep(self)
2819 c, e = op.int, op.exp
2820 if adj == 0:
2821 # 1 < self < 10
2822 num = str(c-10**-e)
2823 den = str(c)
2824 return len(num) - len(den) - (num < den)
2825 # adj == -1, 0.1 <= self < 1
2826 return e + len(str(10**-e - c)) - 1
2827
2828
2829 def ln(self, context=None):
2830 """Returns the natural (base e) logarithm of self."""
2831
2832 if context is None:
2833 context = getcontext()
2834
2835 # ln(NaN) = NaN
2836 ans = self._check_nans(context=context)
2837 if ans:
2838 return ans
2839
2840 # ln(0.0) == -Infinity
2841 if not self:
2842 return negInf
2843
2844 # ln(Infinity) = Infinity
2845 if self._isinfinity() == 1:
2846 return Inf
2847
2848 # ln(1.0) == 0.0
2849 if self == Dec_p1:
2850 return Dec_0
2851
2852 # ln(negative) raises InvalidOperation
2853 if self._sign == 1:
2854 return context._raise_error(InvalidOperation,
2855 'ln of a negative value')
2856
2857 # result is irrational, so necessarily inexact
2858 op = _WorkRep(self)
2859 c, e = op.int, op.exp
2860 p = context.prec
2861
2862 # correctly rounded result: repeatedly increase precision by 3
2863 # until we get an unambiguously roundable result
2864 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2865 while True:
2866 coeff = _dlog(c, e, places)
2867 # assert len(str(abs(coeff)))-p >= 1
2868 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2869 break
2870 places += 3
2871 ans = Decimal((int(coeff<0), map(int, str(abs(coeff))), -places))
2872
2873 context = context._shallow_copy()
2874 rounding = context._set_rounding(ROUND_HALF_EVEN)
2875 ans = ans._fix(context)
2876 context.rounding = rounding
2877 return ans
2878
2879 def _log10_exp_bound(self):
2880 """Compute a lower bound for the adjusted exponent of self.log10().
2881 In other words, find r such that self.log10() >= 10**r.
2882 Assumes that self is finite and positive and that self != 1.
2883 """
2884
2885 # For x >= 10 or x < 0.1 we only need a bound on the integer
2886 # part of log10(self), and this comes directly from the
2887 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2888 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2889 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2890
2891 adj = self._exp + len(self._int) - 1
2892 if adj >= 1:
2893 # self >= 10
2894 return len(str(adj))-1
2895 if adj <= -2:
2896 # self < 0.1
2897 return len(str(-1-adj))-1
2898 op = _WorkRep(self)
2899 c, e = op.int, op.exp
2900 if adj == 0:
2901 # 1 < self < 10
2902 num = str(c-10**-e)
2903 den = str(231*c)
2904 return len(num) - len(den) - (num < den) + 2
2905 # adj == -1, 0.1 <= self < 1
2906 num = str(10**-e-c)
2907 return len(num) + e - (num < "231") - 1
2908
2909 def log10(self, context=None):
2910 """Returns the base 10 logarithm of self."""
2911
2912 if context is None:
2913 context = getcontext()
2914
2915 # log10(NaN) = NaN
2916 ans = self._check_nans(context=context)
2917 if ans:
2918 return ans
2919
2920 # log10(0.0) == -Infinity
2921 if not self:
2922 return negInf
2923
2924 # log10(Infinity) = Infinity
2925 if self._isinfinity() == 1:
2926 return Inf
2927
2928 # log10(negative or -Infinity) raises InvalidOperation
2929 if self._sign == 1:
2930 return context._raise_error(InvalidOperation,
2931 'log10 of a negative value')
2932
2933 # log10(10**n) = n
2934 if self._int[0] == 1 and self._int[1:] == (0,)*(len(self._int) - 1):
2935 # answer may need rounding
2936 ans = Decimal(self._exp + len(self._int) - 1)
2937 else:
2938 # result is irrational, so necessarily inexact
2939 op = _WorkRep(self)
2940 c, e = op.int, op.exp
2941 p = context.prec
2942
2943 # correctly rounded result: repeatedly increase precision
2944 # until result is unambiguously roundable
2945 places = p-self._log10_exp_bound()+2
2946 while True:
2947 coeff = _dlog10(c, e, places)
2948 # assert len(str(abs(coeff)))-p >= 1
2949 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2950 break
2951 places += 3
2952 ans = Decimal((int(coeff<0), map(int, str(abs(coeff))), -places))
2953
2954 context = context._shallow_copy()
2955 rounding = context._set_rounding(ROUND_HALF_EVEN)
2956 ans = ans._fix(context)
2957 context.rounding = rounding
2958 return ans
2959
2960 def logb(self, context=None):
2961 """ Returns the exponent of the magnitude of self's MSD.
2962
2963 The result is the integer which is the exponent of the magnitude
2964 of the most significant digit of self (as though it were truncated
2965 to a single digit while maintaining the value of that digit and
2966 without limiting the resulting exponent).
2967 """
2968 # logb(NaN) = NaN
2969 ans = self._check_nans(context=context)
2970 if ans:
2971 return ans
2972
2973 if context is None:
2974 context = getcontext()
2975
2976 # logb(+/-Inf) = +Inf
2977 if self._isinfinity():
2978 return Inf
2979
2980 # logb(0) = -Inf, DivisionByZero
2981 if not self:
2982 return context._raise_error(DivisionByZero, 'logb(0)', -1)
2983
2984 # otherwise, simply return the adjusted exponent of self, as a
2985 # Decimal. Note that no attempt is made to fit the result
2986 # into the current context.
2987 return Decimal(self.adjusted())
2988
2989 def _islogical(self):
2990 """Return True if self is a logical operand.
2991
2992 For being logical, it must be a finite numbers with a sign of 0,
2993 an exponent of 0, and a coefficient whose digits must all be
2994 either 0 or 1.
2995 """
2996 if self._sign != 0 or self._exp != 0:
2997 return False
2998 for dig in self._int:
2999 if dig not in (0, 1):
3000 return False
3001 return True
3002
3003 def _fill_logical(self, context, opa, opb):
3004 dif = context.prec - len(opa)
3005 if dif > 0:
3006 opa = (0,)*dif + opa
3007 elif dif < 0:
3008 opa = opa[-context.prec:]
3009 dif = context.prec - len(opb)
3010 if dif > 0:
3011 opb = (0,)*dif + opb
3012 elif dif < 0:
3013 opb = opb[-context.prec:]
3014 return opa, opb
3015
3016 def logical_and(self, other, context=None):
3017 """Applies an 'and' operation between self and other's digits."""
3018 if context is None:
3019 context = getcontext()
3020 if not self._islogical() or not other._islogical():
3021 return context._raise_error(InvalidOperation)
3022
3023 # fill to context.prec
3024 (opa, opb) = self._fill_logical(context, self._int, other._int)
3025
3026 # make the operation, and clean starting zeroes
3027 result = [a&b for a,b in zip(opa,opb)]
3028 for i,d in enumerate(result):
3029 if d == 1:
3030 break
3031 result = tuple(result[i:])
3032
3033 # if empty, we must have at least a zero
3034 if not result:
3035 result = (0,)
3036 return Decimal((0, result, 0))
3037
3038 def logical_invert(self, context=None):
3039 """Invert all its digits."""
3040 if context is None:
3041 context = getcontext()
3042 return self.logical_xor(Decimal((0,(1,)*context.prec,0)), context)
3043
3044 def logical_or(self, other, context=None):
3045 """Applies an 'or' operation between self and other's digits."""
3046 if context is None:
3047 context = getcontext()
3048 if not self._islogical() or not other._islogical():
3049 return context._raise_error(InvalidOperation)
3050
3051 # fill to context.prec
3052 (opa, opb) = self._fill_logical(context, self._int, other._int)
3053
3054 # make the operation, and clean starting zeroes
3055 result = [a|b for a,b in zip(opa,opb)]
3056 for i,d in enumerate(result):
3057 if d == 1:
3058 break
3059 result = tuple(result[i:])
3060
3061 # if empty, we must have at least a zero
3062 if not result:
3063 result = (0,)
3064 return Decimal((0, result, 0))
3065
3066 def logical_xor(self, other, context=None):
3067 """Applies an 'xor' operation between self and other's digits."""
3068 if context is None:
3069 context = getcontext()
3070 if not self._islogical() or not other._islogical():
3071 return context._raise_error(InvalidOperation)
3072
3073 # fill to context.prec
3074 (opa, opb) = self._fill_logical(context, self._int, other._int)
3075
3076 # make the operation, and clean starting zeroes
3077 result = [a^b for a,b in zip(opa,opb)]
3078 for i,d in enumerate(result):
3079 if d == 1:
3080 break
3081 result = tuple(result[i:])
3082
3083 # if empty, we must have at least a zero
3084 if not result:
3085 result = (0,)
3086 return Decimal((0, result, 0))
3087
3088 def max_mag(self, other, context=None):
3089 """Compares the values numerically with their sign ignored."""
3090 other = _convert_other(other, raiseit=True)
3091
Facundo Batista6c398da2007-09-17 17:30:13 +00003092 if context is None:
3093 context = getcontext()
3094
Facundo Batista353750c2007-09-13 18:13:15 +00003095 if self._is_special or other._is_special:
3096 # If one operand is a quiet NaN and the other is number, then the
3097 # number is always returned
3098 sn = self._isnan()
3099 on = other._isnan()
3100 if sn or on:
3101 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003102 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003103 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003104 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003105 return self._check_nans(other, context)
3106
3107 c = self.copy_abs().__cmp__(other.copy_abs())
3108 if c == 0:
3109 c = self.compare_total(other)
3110
3111 if c == -1:
3112 ans = other
3113 else:
3114 ans = self
3115
Facundo Batista353750c2007-09-13 18:13:15 +00003116 if context._rounding_decision == ALWAYS_ROUND:
3117 return ans._fix(context)
3118 return ans
3119
3120 def min_mag(self, other, context=None):
3121 """Compares the values numerically with their sign ignored."""
3122 other = _convert_other(other, raiseit=True)
3123
Facundo Batista6c398da2007-09-17 17:30:13 +00003124 if context is None:
3125 context = getcontext()
3126
Facundo Batista353750c2007-09-13 18:13:15 +00003127 if self._is_special or other._is_special:
3128 # If one operand is a quiet NaN and the other is number, then the
3129 # number is always returned
3130 sn = self._isnan()
3131 on = other._isnan()
3132 if sn or on:
3133 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003134 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003135 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003136 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003137 return self._check_nans(other, context)
3138
3139 c = self.copy_abs().__cmp__(other.copy_abs())
3140 if c == 0:
3141 c = self.compare_total(other)
3142
3143 if c == -1:
3144 ans = self
3145 else:
3146 ans = other
3147
Facundo Batista353750c2007-09-13 18:13:15 +00003148 if context._rounding_decision == ALWAYS_ROUND:
3149 return ans._fix(context)
3150 return ans
3151
3152 def next_minus(self, context=None):
3153 """Returns the largest representable number smaller than itself."""
3154 if context is None:
3155 context = getcontext()
3156
3157 ans = self._check_nans(context=context)
3158 if ans:
3159 return ans
3160
3161 if self._isinfinity() == -1:
3162 return negInf
3163 if self._isinfinity() == 1:
3164 return Decimal((0, (9,)*context.prec, context.Etop()))
3165
3166 context = context.copy()
3167 context._set_rounding(ROUND_FLOOR)
3168 context._ignore_all_flags()
3169 new_self = self._fix(context)
3170 if new_self != self:
3171 return new_self
3172 return self.__sub__(Decimal((0, (1,), context.Etiny()-1)), context)
3173
3174 def next_plus(self, context=None):
3175 """Returns the smallest representable number larger than itself."""
3176 if context is None:
3177 context = getcontext()
3178
3179 ans = self._check_nans(context=context)
3180 if ans:
3181 return ans
3182
3183 if self._isinfinity() == 1:
3184 return Inf
3185 if self._isinfinity() == -1:
3186 return Decimal((1, (9,)*context.prec, context.Etop()))
3187
3188 context = context.copy()
3189 context._set_rounding(ROUND_CEILING)
3190 context._ignore_all_flags()
3191 new_self = self._fix(context)
3192 if new_self != self:
3193 return new_self
3194 return self.__add__(Decimal((0, (1,), context.Etiny()-1)), context)
3195
3196 def next_toward(self, other, context=None):
3197 """Returns the number closest to self, in the direction towards other.
3198
3199 The result is the closest representable number to self
3200 (excluding self) that is in the direction towards other,
3201 unless both have the same value. If the two operands are
3202 numerically equal, then the result is a copy of self with the
3203 sign set to be the same as the sign of other.
3204 """
3205 other = _convert_other(other, raiseit=True)
3206
3207 if context is None:
3208 context = getcontext()
3209
3210 ans = self._check_nans(other, context)
3211 if ans:
3212 return ans
3213
3214 comparison = self.__cmp__(other)
3215 if comparison == 0:
3216 return Decimal((other._sign, self._int, self._exp))
3217
3218 if comparison == -1:
3219 ans = self.next_plus(context)
3220 else: # comparison == 1
3221 ans = self.next_minus(context)
3222
3223 # decide which flags to raise using value of ans
3224 if ans._isinfinity():
3225 context._raise_error(Overflow,
3226 'Infinite result from next_toward',
3227 ans._sign)
3228 context._raise_error(Rounded)
3229 context._raise_error(Inexact)
3230 elif ans.adjusted() < context.Emin:
3231 context._raise_error(Underflow)
3232 context._raise_error(Subnormal)
3233 context._raise_error(Rounded)
3234 context._raise_error(Inexact)
3235 # if precision == 1 then we don't raise Clamped for a
3236 # result 0E-Etiny.
3237 if not ans:
3238 context._raise_error(Clamped)
3239
3240 return ans
3241
3242 def number_class(self, context=None):
3243 """Returns an indication of the class of self.
3244
3245 The class is one of the following strings:
3246 -sNaN
3247 -NaN
3248 -Infinity
3249 -Normal
3250 -Subnormal
3251 -Zero
3252 +Zero
3253 +Subnormal
3254 +Normal
3255 +Infinity
3256 """
3257 if self.is_snan():
3258 return "sNaN"
3259 if self.is_qnan():
3260 return "NaN"
3261 inf = self._isinfinity()
3262 if inf == 1:
3263 return "+Infinity"
3264 if inf == -1:
3265 return "-Infinity"
3266 if self.is_zero():
3267 if self._sign:
3268 return "-Zero"
3269 else:
3270 return "+Zero"
3271 if context is None:
3272 context = getcontext()
3273 if self.is_subnormal(context=context):
3274 if self._sign:
3275 return "-Subnormal"
3276 else:
3277 return "+Subnormal"
3278 # just a normal, regular, boring number, :)
3279 if self._sign:
3280 return "-Normal"
3281 else:
3282 return "+Normal"
3283
3284 def radix(self):
3285 """Just returns 10, as this is Decimal, :)"""
3286 return Decimal(10)
3287
3288 def rotate(self, other, context=None):
3289 """Returns a rotated copy of self, value-of-other times."""
3290 if context is None:
3291 context = getcontext()
3292
3293 ans = self._check_nans(other, context)
3294 if ans:
3295 return ans
3296
3297 if other._exp != 0:
3298 return context._raise_error(InvalidOperation)
3299 if not (-context.prec <= int(other) <= context.prec):
3300 return context._raise_error(InvalidOperation)
3301
3302 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003303 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003304
3305 # get values, pad if necessary
3306 torot = int(other)
3307 rotdig = self._int
3308 topad = context.prec - len(rotdig)
3309 if topad:
3310 rotdig = ((0,)*topad) + rotdig
3311
3312 # let's rotate!
3313 rotated = rotdig[torot:] + rotdig[:torot]
3314
3315 # clean starting zeroes
3316 for i,d in enumerate(rotated):
3317 if d != 0:
3318 break
3319 rotated = rotated[i:]
3320
3321 return Decimal((self._sign, rotated, self._exp))
3322
3323
3324 def scaleb (self, other, context=None):
3325 """Returns self operand after adding the second value to its exp."""
3326 if context is None:
3327 context = getcontext()
3328
3329 ans = self._check_nans(other, context)
3330 if ans:
3331 return ans
3332
3333 if other._exp != 0:
3334 return context._raise_error(InvalidOperation)
3335 liminf = -2 * (context.Emax + context.prec)
3336 limsup = 2 * (context.Emax + context.prec)
3337 if not (liminf <= int(other) <= limsup):
3338 return context._raise_error(InvalidOperation)
3339
3340 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003341 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003342
3343 d = Decimal((self._sign, self._int, self._exp + int(other)))
3344 d = d._fix(context)
3345 return d
3346
3347 def shift(self, other, context=None):
3348 """Returns a shifted copy of self, value-of-other times."""
3349 if context is None:
3350 context = getcontext()
3351
3352 ans = self._check_nans(other, context)
3353 if ans:
3354 return ans
3355
3356 if other._exp != 0:
3357 return context._raise_error(InvalidOperation)
3358 if not (-context.prec <= int(other) <= context.prec):
3359 return context._raise_error(InvalidOperation)
3360
3361 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003362 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003363
3364 # get values, pad if necessary
3365 torot = int(other)
3366 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003367 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003368 rotdig = self._int
3369 topad = context.prec - len(rotdig)
3370 if topad:
3371 rotdig = ((0,)*topad) + rotdig
3372
3373 # let's shift!
3374 if torot < 0:
3375 rotated = rotdig[:torot]
3376 else:
3377 rotated = (rotdig + ((0,) * torot))
3378 rotated = rotated[-context.prec:]
3379
3380 # clean starting zeroes
3381 if rotated:
3382 for i,d in enumerate(rotated):
3383 if d != 0:
3384 break
3385 rotated = rotated[i:]
3386 else:
3387 rotated = (0,)
3388
3389 return Decimal((self._sign, rotated, self._exp))
3390
3391
Facundo Batista59c58842007-04-10 12:58:45 +00003392 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003393 def __reduce__(self):
3394 return (self.__class__, (str(self),))
3395
3396 def __copy__(self):
3397 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003398 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003399 return self.__class__(str(self))
3400
3401 def __deepcopy__(self, memo):
3402 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003403 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003404 return self.__class__(str(self))
3405
Facundo Batista59c58842007-04-10 12:58:45 +00003406##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003407
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003408
3409# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003410rounding_functions = [name for name in Decimal.__dict__.keys()
3411 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003412for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003413 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003414 globalname = name[1:].upper()
3415 val = globals()[globalname]
3416 Decimal._pick_rounding_function[val] = name
3417
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003418del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003419
Nick Coghlanced12182006-09-02 03:54:17 +00003420class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003421 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003422
Nick Coghlanced12182006-09-02 03:54:17 +00003423 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003424 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003425 """
3426 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003427 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003428 def __enter__(self):
3429 self.saved_context = getcontext()
3430 setcontext(self.new_context)
3431 return self.new_context
3432 def __exit__(self, t, v, tb):
3433 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003434
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003435class Context(object):
3436 """Contains the context for a Decimal instance.
3437
3438 Contains:
3439 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003440 rounding - rounding type (how you round)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003441 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
Raymond Hettingerbf440692004-07-10 14:14:37 +00003442 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003443 raised when it is caused. Otherwise, a value is
3444 substituted in.
3445 flags - When an exception is caused, flags[exception] is incremented.
3446 (Whether or not the trap_enabler is set)
3447 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003448 Emin - Minimum exponent
3449 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003450 capitals - If 1, 1*10^1 is printed as 1E+1.
3451 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003452 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003453 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003454
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003455 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003456 traps=None, flags=None,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003457 _rounding_decision=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003458 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003459 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003460 _ignored_flags=None):
3461 if flags is None:
3462 flags = []
3463 if _ignored_flags is None:
3464 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003465 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003466 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003467 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003468 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003469 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003470 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003471 for name, val in locals().items():
3472 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003473 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003474 else:
3475 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003476 del self.self
3477
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003478 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003479 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003480 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003481 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3482 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3483 % vars(self))
3484 names = [f.__name__ for f, v in self.flags.items() if v]
3485 s.append('flags=[' + ', '.join(names) + ']')
3486 names = [t.__name__ for t, v in self.traps.items() if v]
3487 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003488 return ', '.join(s) + ')'
3489
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003490 def clear_flags(self):
3491 """Reset all flags to zero"""
3492 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003493 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003494
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003495 def _shallow_copy(self):
3496 """Returns a shallow copy from self."""
Raymond Hettingerbf440692004-07-10 14:14:37 +00003497 nc = Context(self.prec, self.rounding, self.traps, self.flags,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003498 self._rounding_decision, self.Emin, self.Emax,
3499 self.capitals, self._clamp, self._ignored_flags)
3500 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003501
3502 def copy(self):
3503 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003504 nc = Context(self.prec, self.rounding, self.traps.copy(),
3505 self.flags.copy(), self._rounding_decision, self.Emin,
3506 self.Emax, self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003507 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003508 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003509
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003510 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003511 """Handles an error
3512
3513 If the flag is in _ignored_flags, returns the default response.
3514 Otherwise, it increments the flag, then, if the corresponding
3515 trap_enabler is set, it reaises the exception. Otherwise, it returns
3516 the default value after incrementing the flag.
3517 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003518 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003519 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003520 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003521 return error().handle(self, *args)
3522
3523 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003524 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003525 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003526 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003527
3528 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003529 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003530 raise error, explanation
3531
3532 def _ignore_all_flags(self):
3533 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003534 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003535
3536 def _ignore_flags(self, *flags):
3537 """Ignore the flags, if they are raised"""
3538 # Do not mutate-- This way, copies of a context leave the original
3539 # alone.
3540 self._ignored_flags = (self._ignored_flags + list(flags))
3541 return list(flags)
3542
3543 def _regard_flags(self, *flags):
3544 """Stop ignoring the flags, if they are raised"""
3545 if flags and isinstance(flags[0], (tuple,list)):
3546 flags = flags[0]
3547 for flag in flags:
3548 self._ignored_flags.remove(flag)
3549
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003550 def __hash__(self):
3551 """A Context cannot be hashed."""
3552 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista59c58842007-04-10 12:58:45 +00003553 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003554
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003555 def Etiny(self):
3556 """Returns Etiny (= Emin - prec + 1)"""
3557 return int(self.Emin - self.prec + 1)
3558
3559 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003560 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003561 return int(self.Emax - self.prec + 1)
3562
3563 def _set_rounding_decision(self, type):
3564 """Sets the rounding decision.
3565
3566 Sets the rounding decision, and returns the current (previous)
3567 rounding decision. Often used like:
3568
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003569 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003570 # That so you don't change the calling context
3571 # if an error occurs in the middle (say DivisionImpossible is raised).
3572
3573 rounding = context._set_rounding_decision(NEVER_ROUND)
3574 instance = instance / Decimal(2)
3575 context._set_rounding_decision(rounding)
3576
3577 This will make it not round for that operation.
3578 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003579
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003580 rounding = self._rounding_decision
3581 self._rounding_decision = type
3582 return rounding
3583
3584 def _set_rounding(self, type):
3585 """Sets the rounding type.
3586
3587 Sets the rounding type, and returns the current (previous)
3588 rounding type. Often used like:
3589
3590 context = context.copy()
3591 # so you don't change the calling context
3592 # if an error occurs in the middle.
3593 rounding = context._set_rounding(ROUND_UP)
3594 val = self.__sub__(other, context=context)
3595 context._set_rounding(rounding)
3596
3597 This will make it round up for that operation.
3598 """
3599 rounding = self.rounding
3600 self.rounding= type
3601 return rounding
3602
Raymond Hettingerfed52962004-07-14 15:41:57 +00003603 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003604 """Creates a new Decimal instance but using self as context."""
3605 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003606 if d._isnan() and len(d._int) > self.prec - self._clamp:
3607 return self._raise_error(ConversionSyntax,
3608 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003609 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003610
Facundo Batista59c58842007-04-10 12:58:45 +00003611 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003612 def abs(self, a):
3613 """Returns the absolute value of the operand.
3614
3615 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003616 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003617 the plus operation on the operand.
3618
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003619 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003620 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003621 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003622 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003623 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003624 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003625 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003626 Decimal("101.5")
3627 """
3628 return a.__abs__(context=self)
3629
3630 def add(self, a, b):
3631 """Return the sum of the two operands.
3632
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003633 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003634 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003635 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003636 Decimal("1.02E+4")
3637 """
3638 return a.__add__(b, context=self)
3639
3640 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003641 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003642
Facundo Batista353750c2007-09-13 18:13:15 +00003643 def canonical(self, a):
3644 """Returns the same Decimal object.
3645
3646 As we do not have different encodings for the same number, the
3647 received object already is in its canonical form.
3648
3649 >>> ExtendedContext.canonical(Decimal('2.50'))
3650 Decimal("2.50")
3651 """
3652 return a.canonical(context=self)
3653
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003654 def compare(self, a, b):
3655 """Compares values numerically.
3656
3657 If the signs of the operands differ, a value representing each operand
3658 ('-1' if the operand is less than zero, '0' if the operand is zero or
3659 negative zero, or '1' if the operand is greater than zero) is used in
3660 place of that operand for the comparison instead of the actual
3661 operand.
3662
3663 The comparison is then effected by subtracting the second operand from
3664 the first and then returning a value according to the result of the
3665 subtraction: '-1' if the result is less than zero, '0' if the result is
3666 zero or negative zero, or '1' if the result is greater than zero.
3667
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003668 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003669 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003670 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003671 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003672 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003673 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003674 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003675 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003676 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003677 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003678 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003679 Decimal("-1")
3680 """
3681 return a.compare(b, context=self)
3682
Facundo Batista353750c2007-09-13 18:13:15 +00003683 def compare_signal(self, a, b):
3684 """Compares the values of the two operands numerically.
3685
3686 It's pretty much like compare(), but all NaNs signal, with signaling
3687 NaNs taking precedence over quiet NaNs.
3688
3689 >>> c = ExtendedContext
3690 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3691 Decimal("-1")
3692 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3693 Decimal("0")
3694 >>> c.flags[InvalidOperation] = 0
3695 >>> print c.flags[InvalidOperation]
3696 0
3697 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3698 Decimal("NaN")
3699 >>> print c.flags[InvalidOperation]
3700 1
3701 >>> c.flags[InvalidOperation] = 0
3702 >>> print c.flags[InvalidOperation]
3703 0
3704 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3705 Decimal("NaN")
3706 >>> print c.flags[InvalidOperation]
3707 1
3708 """
3709 return a.compare_signal(b, context=self)
3710
3711 def compare_total(self, a, b):
3712 """Compares two operands using their abstract representation.
3713
3714 This is not like the standard compare, which use their numerical
3715 value. Note that a total ordering is defined for all possible abstract
3716 representations.
3717
3718 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3719 Decimal("-1")
3720 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3721 Decimal("-1")
3722 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3723 Decimal("-1")
3724 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3725 Decimal("0")
3726 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3727 Decimal("1")
3728 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3729 Decimal("-1")
3730 """
3731 return a.compare_total(b)
3732
3733 def compare_total_mag(self, a, b):
3734 """Compares two operands using their abstract representation ignoring sign.
3735
3736 Like compare_total, but with operand's sign ignored and assumed to be 0.
3737 """
3738 return a.compare_total_mag(b)
3739
3740 def copy_abs(self, a):
3741 """Returns a copy of the operand with the sign set to 0.
3742
3743 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3744 Decimal("2.1")
3745 >>> ExtendedContext.copy_abs(Decimal('-100'))
3746 Decimal("100")
3747 """
3748 return a.copy_abs()
3749
3750 def copy_decimal(self, a):
3751 """Returns a copy of the decimal objet.
3752
3753 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3754 Decimal("2.1")
3755 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3756 Decimal("-1.00")
3757 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003758 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003759
3760 def copy_negate(self, a):
3761 """Returns a copy of the operand with the sign inverted.
3762
3763 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3764 Decimal("-101.5")
3765 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3766 Decimal("101.5")
3767 """
3768 return a.copy_negate()
3769
3770 def copy_sign(self, a, b):
3771 """Copies the second operand's sign to the first one.
3772
3773 In detail, it returns a copy of the first operand with the sign
3774 equal to the sign of the second operand.
3775
3776 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3777 Decimal("1.50")
3778 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3779 Decimal("1.50")
3780 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3781 Decimal("-1.50")
3782 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3783 Decimal("-1.50")
3784 """
3785 return a.copy_sign(b)
3786
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003787 def divide(self, a, b):
3788 """Decimal division in a specified context.
3789
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003790 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003791 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003792 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003793 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003794 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003795 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003796 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003797 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003798 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003799 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003800 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003801 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003802 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003803 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003804 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003805 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003806 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003807 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003808 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003809 Decimal("1.20E+6")
3810 """
3811 return a.__div__(b, context=self)
3812
3813 def divide_int(self, a, b):
3814 """Divides two numbers and returns the integer part of the result.
3815
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003816 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003817 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003818 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003819 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003820 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003821 Decimal("3")
3822 """
3823 return a.__floordiv__(b, context=self)
3824
3825 def divmod(self, a, b):
3826 return a.__divmod__(b, context=self)
3827
Facundo Batista353750c2007-09-13 18:13:15 +00003828 def exp(self, a):
3829 """Returns e ** a.
3830
3831 >>> c = ExtendedContext.copy()
3832 >>> c.Emin = -999
3833 >>> c.Emax = 999
3834 >>> c.exp(Decimal('-Infinity'))
3835 Decimal("0")
3836 >>> c.exp(Decimal('-1'))
3837 Decimal("0.367879441")
3838 >>> c.exp(Decimal('0'))
3839 Decimal("1")
3840 >>> c.exp(Decimal('1'))
3841 Decimal("2.71828183")
3842 >>> c.exp(Decimal('0.693147181'))
3843 Decimal("2.00000000")
3844 >>> c.exp(Decimal('+Infinity'))
3845 Decimal("Infinity")
3846 """
3847 return a.exp(context=self)
3848
3849 def fma(self, a, b, c):
3850 """Returns a multiplied by b, plus c.
3851
3852 The first two operands are multiplied together, using multiply,
3853 the third operand is then added to the result of that
3854 multiplication, using add, all with only one final rounding.
3855
3856 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3857 Decimal("22")
3858 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3859 Decimal("-8")
3860 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3861 Decimal("1.38435736E+12")
3862 """
3863 return a.fma(b, c, context=self)
3864
3865 def is_canonical(self, a):
3866 """Returns 1 if the operand is canonical; otherwise returns 0.
3867
3868 >>> ExtendedContext.is_canonical(Decimal('2.50'))
3869 Decimal("1")
3870 """
3871 return Dec_p1
3872
3873 def is_finite(self, a):
3874 """Returns 1 if the operand is finite, otherwise returns 0.
3875
3876 For it to be finite, it must be neither infinite nor a NaN.
3877
3878 >>> ExtendedContext.is_finite(Decimal('2.50'))
3879 Decimal("1")
3880 >>> ExtendedContext.is_finite(Decimal('-0.3'))
3881 Decimal("1")
3882 >>> ExtendedContext.is_finite(Decimal('0'))
3883 Decimal("1")
3884 >>> ExtendedContext.is_finite(Decimal('Inf'))
3885 Decimal("0")
3886 >>> ExtendedContext.is_finite(Decimal('NaN'))
3887 Decimal("0")
3888 """
3889 return a.is_finite()
3890
3891 def is_infinite(self, a):
3892 """Returns 1 if the operand is an Infinite, otherwise returns 0.
3893
3894 >>> ExtendedContext.is_infinite(Decimal('2.50'))
3895 Decimal("0")
3896 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
3897 Decimal("1")
3898 >>> ExtendedContext.is_infinite(Decimal('NaN'))
3899 Decimal("0")
3900 """
3901 return a.is_infinite()
3902
3903 def is_nan(self, a):
3904 """Returns 1 if the operand is qNaN or sNaN, otherwise returns 0.
3905
3906 >>> ExtendedContext.is_nan(Decimal('2.50'))
3907 Decimal("0")
3908 >>> ExtendedContext.is_nan(Decimal('NaN'))
3909 Decimal("1")
3910 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
3911 Decimal("1")
3912 """
3913 return a.is_nan()
3914
3915 def is_normal(self, a):
3916 """Returns 1 if the operand is a normal number, otherwise returns 0.
3917
3918 >>> c = ExtendedContext.copy()
3919 >>> c.Emin = -999
3920 >>> c.Emax = 999
3921 >>> c.is_normal(Decimal('2.50'))
3922 Decimal("1")
3923 >>> c.is_normal(Decimal('0.1E-999'))
3924 Decimal("0")
3925 >>> c.is_normal(Decimal('0.00'))
3926 Decimal("0")
3927 >>> c.is_normal(Decimal('-Inf'))
3928 Decimal("0")
3929 >>> c.is_normal(Decimal('NaN'))
3930 Decimal("0")
3931 """
3932 return a.is_normal(context=self)
3933
3934 def is_qnan(self, a):
3935 """Returns 1 if the operand is a quiet NaN, otherwise returns 0.
3936
3937 >>> ExtendedContext.is_qnan(Decimal('2.50'))
3938 Decimal("0")
3939 >>> ExtendedContext.is_qnan(Decimal('NaN'))
3940 Decimal("1")
3941 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
3942 Decimal("0")
3943 """
3944 return a.is_qnan()
3945
3946 def is_signed(self, a):
3947 """Returns 1 if the operand is negative, otherwise returns 0.
3948
3949 >>> ExtendedContext.is_signed(Decimal('2.50'))
3950 Decimal("0")
3951 >>> ExtendedContext.is_signed(Decimal('-12'))
3952 Decimal("1")
3953 >>> ExtendedContext.is_signed(Decimal('-0'))
3954 Decimal("1")
3955 """
3956 return a.is_signed()
3957
3958 def is_snan(self, a):
3959 """Returns 1 if the operand is a signaling NaN, otherwise returns 0.
3960
3961 >>> ExtendedContext.is_snan(Decimal('2.50'))
3962 Decimal("0")
3963 >>> ExtendedContext.is_snan(Decimal('NaN'))
3964 Decimal("0")
3965 >>> ExtendedContext.is_snan(Decimal('sNaN'))
3966 Decimal("1")
3967 """
3968 return a.is_snan()
3969
3970 def is_subnormal(self, a):
3971 """Returns 1 if the operand is subnormal, otherwise returns 0.
3972
3973 >>> c = ExtendedContext.copy()
3974 >>> c.Emin = -999
3975 >>> c.Emax = 999
3976 >>> c.is_subnormal(Decimal('2.50'))
3977 Decimal("0")
3978 >>> c.is_subnormal(Decimal('0.1E-999'))
3979 Decimal("1")
3980 >>> c.is_subnormal(Decimal('0.00'))
3981 Decimal("0")
3982 >>> c.is_subnormal(Decimal('-Inf'))
3983 Decimal("0")
3984 >>> c.is_subnormal(Decimal('NaN'))
3985 Decimal("0")
3986 """
3987 return a.is_subnormal(context=self)
3988
3989 def is_zero(self, a):
3990 """Returns 1 if the operand is a zero, otherwise returns 0.
3991
3992 >>> ExtendedContext.is_zero(Decimal('0'))
3993 Decimal("1")
3994 >>> ExtendedContext.is_zero(Decimal('2.50'))
3995 Decimal("0")
3996 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
3997 Decimal("1")
3998 """
3999 return a.is_zero()
4000
4001 def ln(self, a):
4002 """Returns the natural (base e) logarithm of the operand.
4003
4004 >>> c = ExtendedContext.copy()
4005 >>> c.Emin = -999
4006 >>> c.Emax = 999
4007 >>> c.ln(Decimal('0'))
4008 Decimal("-Infinity")
4009 >>> c.ln(Decimal('1.000'))
4010 Decimal("0")
4011 >>> c.ln(Decimal('2.71828183'))
4012 Decimal("1.00000000")
4013 >>> c.ln(Decimal('10'))
4014 Decimal("2.30258509")
4015 >>> c.ln(Decimal('+Infinity'))
4016 Decimal("Infinity")
4017 """
4018 return a.ln(context=self)
4019
4020 def log10(self, a):
4021 """Returns the base 10 logarithm of the operand.
4022
4023 >>> c = ExtendedContext.copy()
4024 >>> c.Emin = -999
4025 >>> c.Emax = 999
4026 >>> c.log10(Decimal('0'))
4027 Decimal("-Infinity")
4028 >>> c.log10(Decimal('0.001'))
4029 Decimal("-3")
4030 >>> c.log10(Decimal('1.000'))
4031 Decimal("0")
4032 >>> c.log10(Decimal('2'))
4033 Decimal("0.301029996")
4034 >>> c.log10(Decimal('10'))
4035 Decimal("1")
4036 >>> c.log10(Decimal('70'))
4037 Decimal("1.84509804")
4038 >>> c.log10(Decimal('+Infinity'))
4039 Decimal("Infinity")
4040 """
4041 return a.log10(context=self)
4042
4043 def logb(self, a):
4044 """ Returns the exponent of the magnitude of the operand's MSD.
4045
4046 The result is the integer which is the exponent of the magnitude
4047 of the most significant digit of the operand (as though the
4048 operand were truncated to a single digit while maintaining the
4049 value of that digit and without limiting the resulting exponent).
4050
4051 >>> ExtendedContext.logb(Decimal('250'))
4052 Decimal("2")
4053 >>> ExtendedContext.logb(Decimal('2.50'))
4054 Decimal("0")
4055 >>> ExtendedContext.logb(Decimal('0.03'))
4056 Decimal("-2")
4057 >>> ExtendedContext.logb(Decimal('0'))
4058 Decimal("-Infinity")
4059 """
4060 return a.logb(context=self)
4061
4062 def logical_and(self, a, b):
4063 """Applies the logical operation 'and' between each operand's digits.
4064
4065 The operands must be both logical numbers.
4066
4067 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4068 Decimal("0")
4069 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4070 Decimal("0")
4071 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4072 Decimal("0")
4073 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4074 Decimal("1")
4075 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4076 Decimal("1000")
4077 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4078 Decimal("10")
4079 """
4080 return a.logical_and(b, context=self)
4081
4082 def logical_invert(self, a):
4083 """Invert all the digits in the operand.
4084
4085 The operand must be a logical number.
4086
4087 >>> ExtendedContext.logical_invert(Decimal('0'))
4088 Decimal("111111111")
4089 >>> ExtendedContext.logical_invert(Decimal('1'))
4090 Decimal("111111110")
4091 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4092 Decimal("0")
4093 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4094 Decimal("10101010")
4095 """
4096 return a.logical_invert(context=self)
4097
4098 def logical_or(self, a, b):
4099 """Applies the logical operation 'or' between each operand's digits.
4100
4101 The operands must be both logical numbers.
4102
4103 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4104 Decimal("0")
4105 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4106 Decimal("1")
4107 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4108 Decimal("1")
4109 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4110 Decimal("1")
4111 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4112 Decimal("1110")
4113 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4114 Decimal("1110")
4115 """
4116 return a.logical_or(b, context=self)
4117
4118 def logical_xor(self, a, b):
4119 """Applies the logical operation 'xor' between each operand's digits.
4120
4121 The operands must be both logical numbers.
4122
4123 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4124 Decimal("0")
4125 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4126 Decimal("1")
4127 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4128 Decimal("1")
4129 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4130 Decimal("0")
4131 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4132 Decimal("110")
4133 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4134 Decimal("1101")
4135 """
4136 return a.logical_xor(b, context=self)
4137
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004138 def max(self, a,b):
4139 """max compares two values numerically and returns the maximum.
4140
4141 If either operand is a NaN then the general rules apply.
4142 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004143 operation. If they are numerically equal then the left-hand operand
4144 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004145 infinity) of the two operands is chosen as the result.
4146
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004147 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004148 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004149 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004150 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004151 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004152 Decimal("1")
4153 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4154 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004155 """
4156 return a.max(b, context=self)
4157
Facundo Batista353750c2007-09-13 18:13:15 +00004158 def max_mag(self, a, b):
4159 """Compares the values numerically with their sign ignored."""
4160 return a.max_mag(b, context=self)
4161
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004162 def min(self, a,b):
4163 """min compares two values numerically and returns the minimum.
4164
4165 If either operand is a NaN then the general rules apply.
4166 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004167 operation. If they are numerically equal then the left-hand operand
4168 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004169 infinity) of the two operands is chosen as the result.
4170
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004171 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004172 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004173 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004174 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004175 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004176 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004177 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4178 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004179 """
4180 return a.min(b, context=self)
4181
Facundo Batista353750c2007-09-13 18:13:15 +00004182 def min_mag(self, a, b):
4183 """Compares the values numerically with their sign ignored."""
4184 return a.min_mag(b, context=self)
4185
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004186 def minus(self, a):
4187 """Minus corresponds to unary prefix minus in Python.
4188
4189 The operation is evaluated using the same rules as subtract; the
4190 operation minus(a) is calculated as subtract('0', a) where the '0'
4191 has the same exponent as the operand.
4192
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004193 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004194 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004195 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004196 Decimal("1.3")
4197 """
4198 return a.__neg__(context=self)
4199
4200 def multiply(self, a, b):
4201 """multiply multiplies two operands.
4202
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004203 If either operand is a special value then the general rules apply.
4204 Otherwise, the operands are multiplied together ('long multiplication'),
4205 resulting in a number which may be as long as the sum of the lengths
4206 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004207
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004208 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004209 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004210 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004211 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004212 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004213 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004214 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004215 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004216 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004217 Decimal("4.28135971E+11")
4218 """
4219 return a.__mul__(b, context=self)
4220
Facundo Batista353750c2007-09-13 18:13:15 +00004221 def next_minus(self, a):
4222 """Returns the largest representable number smaller than a.
4223
4224 >>> c = ExtendedContext.copy()
4225 >>> c.Emin = -999
4226 >>> c.Emax = 999
4227 >>> ExtendedContext.next_minus(Decimal('1'))
4228 Decimal("0.999999999")
4229 >>> c.next_minus(Decimal('1E-1007'))
4230 Decimal("0E-1007")
4231 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4232 Decimal("-1.00000004")
4233 >>> c.next_minus(Decimal('Infinity'))
4234 Decimal("9.99999999E+999")
4235 """
4236 return a.next_minus(context=self)
4237
4238 def next_plus(self, a):
4239 """Returns the smallest representable number larger than a.
4240
4241 >>> c = ExtendedContext.copy()
4242 >>> c.Emin = -999
4243 >>> c.Emax = 999
4244 >>> ExtendedContext.next_plus(Decimal('1'))
4245 Decimal("1.00000001")
4246 >>> c.next_plus(Decimal('-1E-1007'))
4247 Decimal("-0E-1007")
4248 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4249 Decimal("-1.00000002")
4250 >>> c.next_plus(Decimal('-Infinity'))
4251 Decimal("-9.99999999E+999")
4252 """
4253 return a.next_plus(context=self)
4254
4255 def next_toward(self, a, b):
4256 """Returns the number closest to a, in direction towards b.
4257
4258 The result is the closest representable number from the first
4259 operand (but not the first operand) that is in the direction
4260 towards the second operand, unless the operands have the same
4261 value.
4262
4263 >>> c = ExtendedContext.copy()
4264 >>> c.Emin = -999
4265 >>> c.Emax = 999
4266 >>> c.next_toward(Decimal('1'), Decimal('2'))
4267 Decimal("1.00000001")
4268 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4269 Decimal("-0E-1007")
4270 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4271 Decimal("-1.00000002")
4272 >>> c.next_toward(Decimal('1'), Decimal('0'))
4273 Decimal("0.999999999")
4274 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4275 Decimal("0E-1007")
4276 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4277 Decimal("-1.00000004")
4278 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4279 Decimal("-0.00")
4280 """
4281 return a.next_toward(b, context=self)
4282
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004283 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004284 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004285
4286 Essentially a plus operation with all trailing zeros removed from the
4287 result.
4288
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004289 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004290 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004291 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004292 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004293 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004294 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004295 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004296 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004297 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004298 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004299 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004300 Decimal("0")
4301 """
4302 return a.normalize(context=self)
4303
Facundo Batista353750c2007-09-13 18:13:15 +00004304 def number_class(self, a):
4305 """Returns an indication of the class of the operand.
4306
4307 The class is one of the following strings:
4308 -sNaN
4309 -NaN
4310 -Infinity
4311 -Normal
4312 -Subnormal
4313 -Zero
4314 +Zero
4315 +Subnormal
4316 +Normal
4317 +Infinity
4318
4319 >>> c = Context(ExtendedContext)
4320 >>> c.Emin = -999
4321 >>> c.Emax = 999
4322 >>> c.number_class(Decimal('Infinity'))
4323 '+Infinity'
4324 >>> c.number_class(Decimal('1E-10'))
4325 '+Normal'
4326 >>> c.number_class(Decimal('2.50'))
4327 '+Normal'
4328 >>> c.number_class(Decimal('0.1E-999'))
4329 '+Subnormal'
4330 >>> c.number_class(Decimal('0'))
4331 '+Zero'
4332 >>> c.number_class(Decimal('-0'))
4333 '-Zero'
4334 >>> c.number_class(Decimal('-0.1E-999'))
4335 '-Subnormal'
4336 >>> c.number_class(Decimal('-1E-10'))
4337 '-Normal'
4338 >>> c.number_class(Decimal('-2.50'))
4339 '-Normal'
4340 >>> c.number_class(Decimal('-Infinity'))
4341 '-Infinity'
4342 >>> c.number_class(Decimal('NaN'))
4343 'NaN'
4344 >>> c.number_class(Decimal('-NaN'))
4345 'NaN'
4346 >>> c.number_class(Decimal('sNaN'))
4347 'sNaN'
4348 """
4349 return a.number_class(context=self)
4350
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004351 def plus(self, a):
4352 """Plus corresponds to unary prefix plus in Python.
4353
4354 The operation is evaluated using the same rules as add; the
4355 operation plus(a) is calculated as add('0', a) where the '0'
4356 has the same exponent as the operand.
4357
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004358 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004359 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004360 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004361 Decimal("-1.3")
4362 """
4363 return a.__pos__(context=self)
4364
4365 def power(self, a, b, modulo=None):
4366 """Raises a to the power of b, to modulo if given.
4367
Facundo Batista353750c2007-09-13 18:13:15 +00004368 With two arguments, compute a**b. If a is negative then b
4369 must be integral. The result will be inexact unless b is
4370 integral and the result is finite and can be expressed exactly
4371 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004372
Facundo Batista353750c2007-09-13 18:13:15 +00004373 With three arguments, compute (a**b) % modulo. For the
4374 three argument form, the following restrictions on the
4375 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004376
Facundo Batista353750c2007-09-13 18:13:15 +00004377 - all three arguments must be integral
4378 - b must be nonnegative
4379 - at least one of a or b must be nonzero
4380 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004381
Facundo Batista353750c2007-09-13 18:13:15 +00004382 The result of pow(a, b, modulo) is identical to the result
4383 that would be obtained by computing (a**b) % modulo with
4384 unbounded precision, but is computed more efficiently. It is
4385 always exact.
4386
4387 >>> c = ExtendedContext.copy()
4388 >>> c.Emin = -999
4389 >>> c.Emax = 999
4390 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004391 Decimal("8")
Facundo Batista353750c2007-09-13 18:13:15 +00004392 >>> c.power(Decimal('-2'), Decimal('3'))
4393 Decimal("-8")
4394 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004395 Decimal("0.125")
Facundo Batista353750c2007-09-13 18:13:15 +00004396 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004397 Decimal("69.7575744")
Facundo Batista353750c2007-09-13 18:13:15 +00004398 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4399 Decimal("2.00000000")
4400 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004401 Decimal("0")
Facundo Batista353750c2007-09-13 18:13:15 +00004402 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004403 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004404 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004405 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004406 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004407 Decimal("-0")
Facundo Batista353750c2007-09-13 18:13:15 +00004408 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004409 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004410 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004411 Decimal("-Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004412 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004413 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004414 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004415 Decimal("NaN")
Facundo Batista353750c2007-09-13 18:13:15 +00004416
4417 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4418 Decimal("11")
4419 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4420 Decimal("-11")
4421 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4422 Decimal("1")
4423 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4424 Decimal("11")
4425 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4426 Decimal("11729830")
4427 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4428 Decimal("-0")
4429 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4430 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004431 """
4432 return a.__pow__(b, modulo, context=self)
4433
4434 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004435 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004436
4437 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004438 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004439 exponent is being increased), multiplied by a positive power of ten (if
4440 the exponent is being decreased), or is unchanged (if the exponent is
4441 already equal to that of the right-hand operand).
4442
4443 Unlike other operations, if the length of the coefficient after the
4444 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004445 operation condition is raised. This guarantees that, unless there is
4446 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004447 equal to that of the right-hand operand.
4448
4449 Also unlike other operations, quantize will never raise Underflow, even
4450 if the result is subnormal and inexact.
4451
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004452 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004453 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004454 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004455 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004456 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004457 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004458 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004459 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004460 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004461 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004462 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004463 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004464 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004465 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004466 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004467 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004468 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004469 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004470 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004471 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004472 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004473 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004474 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004475 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004476 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004477 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004478 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004479 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004480 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004481 Decimal("2E+2")
4482 """
4483 return a.quantize(b, context=self)
4484
Facundo Batista353750c2007-09-13 18:13:15 +00004485 def radix(self):
4486 """Just returns 10, as this is Decimal, :)
4487
4488 >>> ExtendedContext.radix()
4489 Decimal("10")
4490 """
4491 return Decimal(10)
4492
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004493 def remainder(self, a, b):
4494 """Returns the remainder from integer division.
4495
4496 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004497 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004498 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004499 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004500
4501 This operation will fail under the same conditions as integer division
4502 (that is, if integer division on the same two operands would fail, the
4503 remainder cannot be calculated).
4504
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004505 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004506 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004507 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004508 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004509 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004510 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004511 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004512 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004513 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004514 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004515 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004516 Decimal("1.0")
4517 """
4518 return a.__mod__(b, context=self)
4519
4520 def remainder_near(self, a, b):
4521 """Returns to be "a - b * n", where n is the integer nearest the exact
4522 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004523 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004524 sign of a.
4525
4526 This operation will fail under the same conditions as integer division
4527 (that is, if integer division on the same two operands would fail, the
4528 remainder cannot be calculated).
4529
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004530 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004531 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004532 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004533 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004534 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004535 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004536 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004537 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004538 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004539 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004540 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004541 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004542 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004543 Decimal("-0.3")
4544 """
4545 return a.remainder_near(b, context=self)
4546
Facundo Batista353750c2007-09-13 18:13:15 +00004547 def rotate(self, a, b):
4548 """Returns a rotated copy of a, b times.
4549
4550 The coefficient of the result is a rotated copy of the digits in
4551 the coefficient of the first operand. The number of places of
4552 rotation is taken from the absolute value of the second operand,
4553 with the rotation being to the left if the second operand is
4554 positive or to the right otherwise.
4555
4556 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4557 Decimal("400000003")
4558 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4559 Decimal("12")
4560 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4561 Decimal("891234567")
4562 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4563 Decimal("123456789")
4564 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4565 Decimal("345678912")
4566 """
4567 return a.rotate(b, context=self)
4568
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004569 def same_quantum(self, a, b):
4570 """Returns True if the two operands have the same exponent.
4571
4572 The result is never affected by either the sign or the coefficient of
4573 either operand.
4574
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004575 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004576 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004577 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004578 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004579 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004580 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004581 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004582 True
4583 """
4584 return a.same_quantum(b)
4585
Facundo Batista353750c2007-09-13 18:13:15 +00004586 def scaleb (self, a, b):
4587 """Returns the first operand after adding the second value its exp.
4588
4589 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4590 Decimal("0.0750")
4591 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4592 Decimal("7.50")
4593 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4594 Decimal("7.50E+3")
4595 """
4596 return a.scaleb (b, context=self)
4597
4598 def shift(self, a, b):
4599 """Returns a shifted copy of a, b times.
4600
4601 The coefficient of the result is a shifted copy of the digits
4602 in the coefficient of the first operand. The number of places
4603 to shift is taken from the absolute value of the second operand,
4604 with the shift being to the left if the second operand is
4605 positive or to the right otherwise. Digits shifted into the
4606 coefficient are zeros.
4607
4608 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4609 Decimal("400000000")
4610 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4611 Decimal("0")
4612 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4613 Decimal("1234567")
4614 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4615 Decimal("123456789")
4616 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4617 Decimal("345678900")
4618 """
4619 return a.shift(b, context=self)
4620
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004621 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004622 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004623
4624 If the result must be inexact, it is rounded using the round-half-even
4625 algorithm.
4626
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004627 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004628 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004629 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004630 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004631 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004632 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004633 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004634 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004635 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004636 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004637 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004638 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004639 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004640 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004641 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004642 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004643 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004644 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004645 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004646 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004647 """
4648 return a.sqrt(context=self)
4649
4650 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004651 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004652
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004653 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004654 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004655 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004656 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004657 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004658 Decimal("-0.77")
4659 """
4660 return a.__sub__(b, context=self)
4661
4662 def to_eng_string(self, a):
4663 """Converts a number to a string, using scientific notation.
4664
4665 The operation is not affected by the context.
4666 """
4667 return a.to_eng_string(context=self)
4668
4669 def to_sci_string(self, a):
4670 """Converts a number to a string, using scientific notation.
4671
4672 The operation is not affected by the context.
4673 """
4674 return a.__str__(context=self)
4675
Facundo Batista353750c2007-09-13 18:13:15 +00004676 def to_integral_exact(self, a):
4677 """Rounds to an integer.
4678
4679 When the operand has a negative exponent, the result is the same
4680 as using the quantize() operation using the given operand as the
4681 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4682 of the operand as the precision setting; Inexact and Rounded flags
4683 are allowed in this operation. The rounding mode is taken from the
4684 context.
4685
4686 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4687 Decimal("2")
4688 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4689 Decimal("100")
4690 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4691 Decimal("100")
4692 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4693 Decimal("102")
4694 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4695 Decimal("-102")
4696 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4697 Decimal("1.0E+6")
4698 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4699 Decimal("7.89E+77")
4700 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4701 Decimal("-Infinity")
4702 """
4703 return a.to_integral_exact(context=self)
4704
4705 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004706 """Rounds to an integer.
4707
4708 When the operand has a negative exponent, the result is the same
4709 as using the quantize() operation using the given operand as the
4710 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4711 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004712 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004713
Facundo Batista353750c2007-09-13 18:13:15 +00004714 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004715 Decimal("2")
Facundo Batista353750c2007-09-13 18:13:15 +00004716 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004717 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004718 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004719 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004720 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004721 Decimal("102")
Facundo Batista353750c2007-09-13 18:13:15 +00004722 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004723 Decimal("-102")
Facundo Batista353750c2007-09-13 18:13:15 +00004724 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004725 Decimal("1.0E+6")
Facundo Batista353750c2007-09-13 18:13:15 +00004726 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004727 Decimal("7.89E+77")
Facundo Batista353750c2007-09-13 18:13:15 +00004728 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004729 Decimal("-Infinity")
4730 """
Facundo Batista353750c2007-09-13 18:13:15 +00004731 return a.to_integral_value(context=self)
4732
4733 # the method name changed, but we provide also the old one, for compatibility
4734 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004735
4736class _WorkRep(object):
4737 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004738 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004739 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004740 # exp: None, int, or string
4741
4742 def __init__(self, value=None):
4743 if value is None:
4744 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004745 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004746 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004747 elif isinstance(value, Decimal):
4748 self.sign = value._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004749 cum = 0
Raymond Hettinger17931de2004-10-27 06:21:46 +00004750 for digit in value._int:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004751 cum = cum * 10 + digit
4752 self.int = cum
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004753 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004754 else:
4755 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004756 self.sign = value[0]
4757 self.int = value[1]
4758 self.exp = value[2]
4759
4760 def __repr__(self):
4761 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4762
4763 __str__ = __repr__
4764
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004765
4766
4767def _normalize(op1, op2, shouldround = 0, prec = 0):
4768 """Normalizes op1, op2 to have the same exp and length of coefficient.
4769
4770 Done during addition.
4771 """
Facundo Batista353750c2007-09-13 18:13:15 +00004772 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004773 tmp = op2
4774 other = op1
4775 else:
4776 tmp = op1
4777 other = op2
4778
Facundo Batista353750c2007-09-13 18:13:15 +00004779 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4780 # Then adding 10**exp to tmp has the same effect (after rounding)
4781 # as adding any positive quantity smaller than 10**exp; similarly
4782 # for subtraction. So if other is smaller than 10**exp we replace
4783 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4784 if shouldround:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004785 tmp_len = len(str(tmp.int))
4786 other_len = len(str(other.int))
Facundo Batista353750c2007-09-13 18:13:15 +00004787 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4788 if other_len + other.exp - 1 < exp:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004789 other.int = 1
Facundo Batista353750c2007-09-13 18:13:15 +00004790 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004791
Facundo Batista353750c2007-09-13 18:13:15 +00004792 tmp.int *= 10 ** (tmp.exp - other.exp)
4793 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004794 return op1, op2
4795
4796def _adjust_coefficients(op1, op2):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004797 """Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004798
4799 Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp.
4800
4801 Used on _WorkRep instances during division.
4802 """
4803 adjust = 0
Facundo Batista59c58842007-04-10 12:58:45 +00004804 # If op1 is smaller, make it larger
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004805 while op2.int > op1.int:
4806 op1.int *= 10
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004807 op1.exp -= 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004808 adjust += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004809
Facundo Batista59c58842007-04-10 12:58:45 +00004810 # If op2 is too small, make it larger
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004811 while op1.int >= (10 * op2.int):
4812 op2.int *= 10
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004813 op2.exp -= 1
4814 adjust -= 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004815
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004816 return op1, op2, adjust
4817
Facundo Batista353750c2007-09-13 18:13:15 +00004818
4819##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4820
4821# This function from Tim Peters was taken from here:
4822# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4823# The correction being in the function definition is for speed, and
4824# the whole function is not resolved with math.log because of avoiding
4825# the use of floats.
4826def _nbits(n, correction = {
4827 '0': 4, '1': 3, '2': 2, '3': 2,
4828 '4': 1, '5': 1, '6': 1, '7': 1,
4829 '8': 0, '9': 0, 'a': 0, 'b': 0,
4830 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4831 """Number of bits in binary representation of the positive integer n,
4832 or 0 if n == 0.
4833 """
4834 if n < 0:
4835 raise ValueError("The argument to _nbits should be nonnegative.")
4836 hex_n = "%x" % n
4837 return 4*len(hex_n) - correction[hex_n[0]]
4838
4839def _sqrt_nearest(n, a):
4840 """Closest integer to the square root of the positive integer n. a is
4841 an initial approximation to the square root. Any positive integer
4842 will do for a, but the closer a is to the square root of n the
4843 faster convergence will be.
4844
4845 """
4846 if n <= 0 or a <= 0:
4847 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4848
4849 b=0
4850 while a != b:
4851 b, a = a, a--n//a>>1
4852 return a
4853
4854def _rshift_nearest(x, shift):
4855 """Given an integer x and a nonnegative integer shift, return closest
4856 integer to x / 2**shift; use round-to-even in case of a tie.
4857
4858 """
4859 b, q = 1L << shift, x >> shift
4860 return q + (2*(x & (b-1)) + (q&1) > b)
4861
4862def _div_nearest(a, b):
4863 """Closest integer to a/b, a and b positive integers; rounds to even
4864 in the case of a tie.
4865
4866 """
4867 q, r = divmod(a, b)
4868 return q + (2*r + (q&1) > b)
4869
4870def _ilog(x, M, L = 8):
4871 """Integer approximation to M*log(x/M), with absolute error boundable
4872 in terms only of x/M.
4873
4874 Given positive integers x and M, return an integer approximation to
4875 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4876 between the approximation and the exact result is at most 22. For
4877 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4878 both cases these are upper bounds on the error; it will usually be
4879 much smaller."""
4880
4881 # The basic algorithm is the following: let log1p be the function
4882 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4883 # the reduction
4884 #
4885 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4886 #
4887 # repeatedly until the argument to log1p is small (< 2**-L in
4888 # absolute value). For small y we can use the Taylor series
4889 # expansion
4890 #
4891 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4892 #
4893 # truncating at T such that y**T is small enough. The whole
4894 # computation is carried out in a form of fixed-point arithmetic,
4895 # with a real number z being represented by an integer
4896 # approximation to z*M. To avoid loss of precision, the y below
4897 # is actually an integer approximation to 2**R*y*M, where R is the
4898 # number of reductions performed so far.
4899
4900 y = x-M
4901 # argument reduction; R = number of reductions performed
4902 R = 0
4903 while (R <= L and long(abs(y)) << L-R >= M or
4904 R > L and abs(y) >> R-L >= M):
4905 y = _div_nearest(long(M*y) << 1,
4906 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4907 R += 1
4908
4909 # Taylor series with T terms
4910 T = -int(-10*len(str(M))//(3*L))
4911 yshift = _rshift_nearest(y, R)
4912 w = _div_nearest(M, T)
4913 for k in xrange(T-1, 0, -1):
4914 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4915
4916 return _div_nearest(w*y, M)
4917
4918def _dlog10(c, e, p):
4919 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4920 approximation to 10**p * log10(c*10**e), with an absolute error of
4921 at most 1. Assumes that c*10**e is not exactly 1."""
4922
4923 # increase precision by 2; compensate for this by dividing
4924 # final result by 100
4925 p += 2
4926
4927 # write c*10**e as d*10**f with either:
4928 # f >= 0 and 1 <= d <= 10, or
4929 # f <= 0 and 0.1 <= d <= 1.
4930 # Thus for c*10**e close to 1, f = 0
4931 l = len(str(c))
4932 f = e+l - (e+l >= 1)
4933
4934 if p > 0:
4935 M = 10**p
4936 k = e+p-f
4937 if k >= 0:
4938 c *= 10**k
4939 else:
4940 c = _div_nearest(c, 10**-k)
4941
4942 log_d = _ilog(c, M) # error < 5 + 22 = 27
4943 log_10 = _ilog(10*M, M) # error < 15
4944 log_d = _div_nearest(log_d*M, log_10)
4945 log_tenpower = f*M # exact
4946 else:
4947 log_d = 0 # error < 2.31
4948 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4949
4950 return _div_nearest(log_tenpower+log_d, 100)
4951
4952def _dlog(c, e, p):
4953 """Given integers c, e and p with c > 0, compute an integer
4954 approximation to 10**p * log(c*10**e), with an absolute error of
4955 at most 1. Assumes that c*10**e is not exactly 1."""
4956
4957 # Increase precision by 2. The precision increase is compensated
4958 # for at the end with a division by 100.
4959 p += 2
4960
4961 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4962 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4963 # as 10**p * log(d) + 10**p*f * log(10).
4964 l = len(str(c))
4965 f = e+l - (e+l >= 1)
4966
4967 # compute approximation to 10**p*log(d), with error < 27
4968 if p > 0:
4969 k = e+p-f
4970 if k >= 0:
4971 c *= 10**k
4972 else:
4973 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4974
4975 # _ilog magnifies existing error in c by a factor of at most 10
4976 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4977 else:
4978 # p <= 0: just approximate the whole thing by 0; error < 2.31
4979 log_d = 0
4980
4981 # compute approximation to 10**p*f*log(10), with error < 17
4982 if f:
4983 sign_f = [-1, 1][f > 0]
4984 if p >= 0:
4985 M = 10**p * abs(f)
4986 else:
4987 M = _div_nearest(abs(f), 10**-p) # M = 10**p*|f|, error <= 0.5
4988
4989 if M:
4990 f_log_ten = sign_f*_ilog(10*M, M) # M*log(10), error <= 1.2 + 15 < 17
4991 else:
4992 f_log_ten = 0
4993 else:
4994 f_log_ten = 0
4995
4996 # error in sum < 17+27 = 44; error after division < 0.44 + 0.5 < 1
4997 return _div_nearest(f_log_ten + log_d, 100)
4998
4999def _iexp(x, M, L=8):
5000 """Given integers x and M, M > 0, such that x/M is small in absolute
5001 value, compute an integer approximation to M*exp(x/M). For 0 <=
5002 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5003 is usually much smaller)."""
5004
5005 # Algorithm: to compute exp(z) for a real number z, first divide z
5006 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5007 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5008 # series
5009 #
5010 # expm1(x) = x + x**2/2! + x**3/3! + ...
5011 #
5012 # Now use the identity
5013 #
5014 # expm1(2x) = expm1(x)*(expm1(x)+2)
5015 #
5016 # R times to compute the sequence expm1(z/2**R),
5017 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5018
5019 # Find R such that x/2**R/M <= 2**-L
5020 R = _nbits((long(x)<<L)//M)
5021
5022 # Taylor series. (2**L)**T > M
5023 T = -int(-10*len(str(M))//(3*L))
5024 y = _div_nearest(x, T)
5025 Mshift = long(M)<<R
5026 for i in xrange(T-1, 0, -1):
5027 y = _div_nearest(x*(Mshift + y), Mshift * i)
5028
5029 # Expansion
5030 for k in xrange(R-1, -1, -1):
5031 Mshift = long(M)<<(k+2)
5032 y = _div_nearest(y*(y+Mshift), Mshift)
5033
5034 return M+y
5035
5036def _dexp(c, e, p):
5037 """Compute an approximation to exp(c*10**e), with p decimal places of
5038 precision.
5039
5040 Returns d, f such that:
5041
5042 10**(p-1) <= d <= 10**p, and
5043 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5044
5045 In other words, d*10**f is an approximation to exp(c*10**e) with p
5046 digits of precision, and with an error in d of at most 1. This is
5047 almost, but not quite, the same as the error being < 1ulp: when d
5048 = 10**(p-1) the error could be up to 10 ulp."""
5049
5050 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5051 p += 2
5052
5053 # compute log10 with extra precision = adjusted exponent of c*10**e
5054 extra = max(0, e + len(str(c)) - 1)
5055 q = p + extra
5056 log10 = _dlog(10, 0, q) # error <= 1
5057
5058 # compute quotient c*10**e/(log10/10**q) = c*10**(e+q)/log10,
5059 # rounding down
5060 shift = e+q
5061 if shift >= 0:
5062 cshift = c*10**shift
5063 else:
5064 cshift = c//10**-shift
5065 quot, rem = divmod(cshift, log10)
5066
5067 # reduce remainder back to original precision
5068 rem = _div_nearest(rem, 10**extra)
5069
5070 # error in result of _iexp < 120; error after division < 0.62
5071 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5072
5073def _dpower(xc, xe, yc, ye, p):
5074 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5075 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5076
5077 10**(p-1) <= c <= 10**p, and
5078 (c-1)*10**e < x**y < (c+1)*10**e
5079
5080 in other words, c*10**e is an approximation to x**y with p digits
5081 of precision, and with an error in c of at most 1. (This is
5082 almost, but not quite, the same as the error being < 1ulp: when c
5083 == 10**(p-1) we can only guarantee error < 10ulp.)
5084
5085 We assume that: x is positive and not equal to 1, and y is nonzero.
5086 """
5087
5088 # Find b such that 10**(b-1) <= |y| <= 10**b
5089 b = len(str(abs(yc))) + ye
5090
5091 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5092 lxc = _dlog(xc, xe, p+b+1)
5093
5094 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5095 shift = ye-b
5096 if shift >= 0:
5097 pc = lxc*yc*10**shift
5098 else:
5099 pc = _div_nearest(lxc*yc, 10**-shift)
5100
5101 if pc == 0:
5102 # we prefer a result that isn't exactly 1; this makes it
5103 # easier to compute a correctly rounded result in __pow__
5104 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5105 coeff, exp = 10**(p-1)+1, 1-p
5106 else:
5107 coeff, exp = 10**p-1, -p
5108 else:
5109 coeff, exp = _dexp(pc, -(p+1), p+1)
5110 coeff = _div_nearest(coeff, 10)
5111 exp += 1
5112
5113 return coeff, exp
5114
5115def _log10_lb(c, correction = {
5116 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5117 '6': 23, '7': 16, '8': 10, '9': 5}):
5118 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5119 if c <= 0:
5120 raise ValueError("The argument to _log10_lb should be nonnegative.")
5121 str_c = str(c)
5122 return 100*len(str_c) - correction[str_c[0]]
5123
Facundo Batista59c58842007-04-10 12:58:45 +00005124##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005125
Facundo Batista353750c2007-09-13 18:13:15 +00005126def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005127 """Convert other to Decimal.
5128
5129 Verifies that it's ok to use in an implicit construction.
5130 """
5131 if isinstance(other, Decimal):
5132 return other
5133 if isinstance(other, (int, long)):
5134 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005135 if raiseit:
5136 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005137 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005138
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005139_infinity_map = {
5140 'inf' : 1,
5141 'infinity' : 1,
5142 '+inf' : 1,
5143 '+infinity' : 1,
5144 '-inf' : -1,
5145 '-infinity' : -1
5146}
5147
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005148def _isinfinity(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005149 """Determines whether a string or float is infinity.
5150
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005151 +1 for negative infinity; 0 for finite ; +1 for positive infinity
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005152 """
5153 num = str(num).lower()
5154 return _infinity_map.get(num, 0)
5155
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005156def _isnan(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005157 """Determines whether a string or float is NaN
5158
5159 (1, sign, diagnostic info as string) => NaN
5160 (2, sign, diagnostic info as string) => sNaN
5161 0 => not a NaN
5162 """
5163 num = str(num).lower()
5164 if not num:
5165 return 0
5166
Facundo Batista59c58842007-04-10 12:58:45 +00005167 # Get the sign, get rid of trailing [+-]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005168 sign = 0
5169 if num[0] == '+':
5170 num = num[1:]
Facundo Batista59c58842007-04-10 12:58:45 +00005171 elif num[0] == '-': # elif avoids '+-nan'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005172 num = num[1:]
5173 sign = 1
5174
5175 if num.startswith('nan'):
Facundo Batista59c58842007-04-10 12:58:45 +00005176 if len(num) > 3 and not num[3:].isdigit(): # diagnostic info
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005177 return 0
5178 return (1, sign, num[3:].lstrip('0'))
5179 if num.startswith('snan'):
5180 if len(num) > 4 and not num[4:].isdigit():
5181 return 0
5182 return (2, sign, num[4:].lstrip('0'))
5183 return 0
5184
5185
Facundo Batista59c58842007-04-10 12:58:45 +00005186##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005187
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005188# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005189# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005190
5191DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005192 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005193 traps=[DivisionByZero, Overflow, InvalidOperation],
5194 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005195 _rounding_decision=ALWAYS_ROUND,
Raymond Hettinger99148e72004-07-14 19:56:56 +00005196 Emax=999999999,
5197 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005198 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005199)
5200
5201# Pre-made alternate contexts offered by the specification
5202# Don't change these; the user should be able to select these
5203# contexts and be able to reproduce results from other implementations
5204# of the spec.
5205
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005206BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005207 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005208 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5209 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005210)
5211
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005212ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005213 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005214 traps=[],
5215 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005216)
5217
5218
Facundo Batista59c58842007-04-10 12:58:45 +00005219##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005220
Facundo Batista59c58842007-04-10 12:58:45 +00005221# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005222Inf = Decimal('Inf')
5223negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005224NaN = Decimal('NaN')
5225Dec_0 = Decimal(0)
5226Dec_p1 = Decimal(1)
5227Dec_n1 = Decimal(-1)
5228Dec_p2 = Decimal(2)
5229Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005230
Facundo Batista59c58842007-04-10 12:58:45 +00005231# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005232Infsign = (Inf, negInf)
5233
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005234
Facundo Batista59c58842007-04-10 12:58:45 +00005235##### crud for parsing strings #############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005236import re
5237
5238# There's an optional sign at the start, and an optional exponent
5239# at the end. The exponent has an optional sign and at least one
5240# digit. In between, must have either at least one digit followed
5241# by an optional fraction, or a decimal point followed by at least
5242# one digit. Yuck.
5243
5244_parser = re.compile(r"""
5245# \s*
5246 (?P<sign>[-+])?
5247 (
5248 (?P<int>\d+) (\. (?P<frac>\d*))?
5249 |
5250 \. (?P<onlyfrac>\d+)
5251 )
5252 ([eE](?P<exp>[-+]? \d+))?
5253# \s*
5254 $
Facundo Batista59c58842007-04-10 12:58:45 +00005255""", re.VERBOSE).match # Uncomment the \s* to allow leading or trailing spaces.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005256
5257del re
5258
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005259def _string2exact(s):
Facundo Batista59c58842007-04-10 12:58:45 +00005260 """Return sign, n, p s.t.
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00005261
Facundo Batista59c58842007-04-10 12:58:45 +00005262 Float string value == -1**sign * n * 10**p exactly
5263 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005264 m = _parser(s)
5265 if m is None:
5266 raise ValueError("invalid literal for Decimal: %r" % s)
5267
5268 if m.group('sign') == "-":
5269 sign = 1
5270 else:
5271 sign = 0
5272
5273 exp = m.group('exp')
5274 if exp is None:
5275 exp = 0
5276 else:
5277 exp = int(exp)
5278
5279 intpart = m.group('int')
5280 if intpart is None:
5281 intpart = ""
5282 fracpart = m.group('onlyfrac')
5283 else:
5284 fracpart = m.group('frac')
5285 if fracpart is None:
5286 fracpart = ""
5287
5288 exp -= len(fracpart)
5289
5290 mantissa = intpart + fracpart
5291 tmp = map(int, mantissa)
5292 backup = tmp
5293 while tmp and tmp[0] == 0:
5294 del tmp[0]
5295
5296 # It's a zero
5297 if not tmp:
5298 if backup:
5299 return (sign, tuple(backup), exp)
5300 return (sign, (0,), exp)
5301 mantissa = tuple(tmp)
5302
5303 return (sign, mantissa, exp)
5304
5305
5306if __name__ == '__main__':
5307 import doctest, sys
5308 doctest.testmod(sys.modules[__name__])